<?php
header('Content-Type: application/json');
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

$response = ['success' => false, 'message' => ''];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $response['message'] = "Security check failed (CSRF). Please try again.";
    } else {
        $login_input = trim($_POST['login_input'] ?? '');
        $password = $_POST['password'] ?? '';
        
        if (empty($login_input) || empty($password)) {
            $response['message'] = "Please enter both email/phone number and password.";
        } else {
            // Rate limiting: max 5 failed attempts per 15 minutes per IP
            $client_ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
            $rate_limit_key = 'login_attempts_' . md5($client_ip);
            
            if (!isset($_SESSION[$rate_limit_key])) {
                $_SESSION[$rate_limit_key] = ['count' => 0, 'first_attempt' => time()];
            }
            
            $rate_data = $_SESSION[$rate_limit_key];
            $window_seconds = 900; // 15 minutes
            $max_attempts = 5;
            
            // Reset window if expired
            if ((time() - $rate_data['first_attempt']) > $window_seconds) {
                $_SESSION[$rate_limit_key] = ['count' => 0, 'first_attempt' => time()];
                $rate_data = $_SESSION[$rate_limit_key];
            }
            
            if ($rate_data['count'] >= $max_attempts) {
                $remaining = $window_seconds - (time() - $rate_data['first_attempt']);
                $response['message'] = "Too many failed login attempts. Please try again in " . ceil($remaining / 60) . " minute(s).";
            } else {
                try {
                    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? OR phone = ?");
                    $stmt->execute([$login_input, $login_input]);
                    $user = $stmt->fetch();
                    
                    if ($user && password_verify($password, $user['password'])) {
                        if ($user['status'] !== 'active') {
                            $response['message'] = "Your account is currently inactive. Please contact an admin.";
                        } elseif (isset($user['is_email_verified']) && $user['is_email_verified'] == false && !empty($user['email_verification_token'])) {
                            // Email verification is required — block login until verified
                            $response['message'] = "Your email address has not been verified yet. Please check your inbox for the verification link.";
                        } else {
                            // Reset rate limit on successful login
                            unset($_SESSION[$rate_limit_key]);
                            
                            // Regenerate session ID to prevent session fixation attacks
                            session_regenerate_id(true);
                            
                            // Populate session
                            $_SESSION['user_id'] = $user['id'];
                            $_SESSION['username'] = $user['username'];
                            $_SESSION['email'] = $user['email'];
                            $_SESSION['role'] = $user['role'];
                            $_SESSION['status'] = $user['status'];
                            
                            // Audit log: successful login (#14)
                            logAuditEvent('login', 'user', $user['id'], 'Successful login');
                            
                            $response['success'] = true;
                            
                            $redirect = trim($_POST['redirect'] ?? '');
                            if (!empty($redirect) && preg_match('/^[a-z0-9_\-\.\/]+\.php(\?[a-z0-9_&=\-\.\/\%]*)?$/i', $redirect)) {
                                $response['redirect'] = $redirect;
                            } else {
                                $response['redirect'] = 'dashboard.php';
                            }
                        }
                    } else {
                        // Increment failed attempt counter
                        $_SESSION[$rate_limit_key]['count']++;
                        $response['message'] = "Invalid email/phone number or password.";
                    }
                } catch (PDOException $e) {
                    error_log("Login error: " . $e->getMessage());
                    $response['message'] = "An unexpected error occurred. Please try again later.";
                }
            }
        }
    }
} else {
    $response['message'] = "Invalid request method.";
}

echo json_encode($response);
