<?php
/**
 * Login Process Handler (AJAX/API endpoint)
 * Kenyan Pension & Life Insurance Management System
 * 
 * Note: Main login processing is handled in login.php
 * This file can be used for AJAX login requests
 */

session_start();

// Set proper JSON headers
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    include 'layouts/dbconn.php';
    
    // Get username and password from the login form
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    
    // Validate input
    if (empty($username) || empty($password)) {
        echo json_encode([
            'success' => false, 
            'message' => 'Username and password are required'
        ]);
        exit;
    }
    
    // Get client IP address and user agent for security logging
    $ip_address = $_SERVER['REMOTE_ADDR'];
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    try {
        // Query based on Kenyan Pension & Life Insurance schema
        $sql = "SELECT u.user_id, u.username, u.email, u.password_hash, u.first_name, u.last_name,
                       u.phone_number, u.role_id, u.status, u.failed_login_attempts, u.locked_until,
                       r.role_name, r.role_id
                FROM users u 
                INNER JOIN roles r ON u.role_id = r.role_id 
                WHERE (u.username = ? OR u.email = ?) 
                AND u.deleted_at IS NULL
                AND r.is_active = 1";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ss", $username, $username);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $user = $result->fetch_assoc();
            
            // Check if account is locked
            if ($user['locked_until'] && strtotime($user['locked_until']) > time()) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Account is locked. Please try again later or contact administrator.',
                    'locked' => true
                ]);
                exit;
            }
            
            // Check account status
            if ($user['status'] !== 'ACTIVE') {
                echo json_encode([
                    'success' => false,
                    'message' => 'Your account is not active. Please contact administrator.',
                    'inactive' => true
                ]);
                exit;
            }
            
            // Verify the password
            if (password_verify($password, $user['password_hash'])) {
                // Password is correct - Reset failed attempts and update last login
                $update_sql = "UPDATE users SET 
                              failed_login_attempts = 0,
                              locked_until = NULL,
                              last_login = CURRENT_TIMESTAMP 
                              WHERE user_id = ?";
                $update_stmt = $conn->prepare($update_sql);
                $update_stmt->bind_param("i", $user['user_id']);
                $update_stmt->execute();
                $update_stmt->close();
                
                // Get user permissions
                $permissions_sql = "SELECT p.permission_name 
                                   FROM permissions p
                                   INNER JOIN role_permissions rp ON p.permission_id = rp.permission_id
                                   WHERE rp.role_id = ?";
                $perm_stmt = $conn->prepare($permissions_sql);
                $perm_stmt->bind_param("i", $user['role_id']);
                $perm_stmt->execute();
                $perm_result = $perm_stmt->get_result();
                $user_permissions = [];
                while ($perm_row = $perm_result->fetch_assoc()) {
                    $user_permissions[] = $perm_row['permission_name'];
                }
                $perm_stmt->close();
                
                // Set session variables
                $_SESSION['user_id'] = $user['user_id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['email'] = $user['email'];
                $_SESSION['full_name'] = $user['first_name'] . ' ' . $user['last_name'];
                $_SESSION['first_name'] = $user['first_name'];
                $_SESSION['last_name'] = $user['last_name'];
                $_SESSION['phone_number'] = $user['phone_number'];
                $_SESSION['role_id'] = $user['role_id'];
                $_SESSION['role_name'] = $user['role_name'];
                $_SESSION['user_permissions'] = $user_permissions;
                $_SESSION['login_time'] = time();
                $_SESSION['session_token'] = bin2hex(random_bytes(32));
                
                // Log successful login
                $log_sql = "INSERT INTO audit_logs (event_type, event_category, event_description, performed_by, ip_address, created_at) 
                           VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)";
                $log_stmt = $conn->prepare($log_sql);
                $event_type = 'USER_LOGIN';
                $event_category = 'SYSTEM';
                $event_description = json_encode([
                    'login_time' => date('Y-m-d H:i:s'),
                    'ip_address' => $ip_address,
                    'role' => $user['role_name'],
                    'session_id' => session_id()
                ]);
                $performed_by = $user['username'];
                $log_stmt->bind_param("sssss", $event_type, $event_category, $event_description, $performed_by, $ip_address);
                $log_stmt->execute();
                $log_stmt->close();
                
                // Determine redirect URL based on roles
                $redirect_url = match(strtoupper($user['role_name'])) {
                    'ADMIN', 'SUPER ADMIN' => 'index.php',
                    'TRUSTEE' => 'trustee_dashboard.php',
                    'EMPLOYER' => 'employer_dashboard.php',
                    'MEMBER' => 'member_portal.php',
                    'INSURANCE OFFICER' => 'insurance_dashboard.php',
                    'AGENT' => 'agent_dashboard.php',
                    default => 'index.php'
                };
                
                // Prepare response data
                $response_data = [
                    'success' => true,
                    'message' => 'Login successful',
                    'user' => [
                        'user_id' => $user['user_id'],
                        'username' => $user['username'],
                        'full_name' => $user['first_name'] . ' ' . $user['last_name'],
                        'email' => $user['email'],
                        'phone_number' => $user['phone_number'],
                        'role_id' => $user['role_id'],
                        'role_name' => $user['role_name']
                    ],
                    'permissions' => $user_permissions,
                    'redirect_url' => $redirect_url,
                    'session_token' => $_SESSION['session_token'],
                    'login_time' => date('Y-m-d H:i:s'),
                    'system_info' => [
                        'system_name' => 'Kenyan Pension & Life Insurance Management System',
                        'version' => '1.0.0',
                        'login_method' => 'ajax'
                    ]
                ];
                
                echo json_encode($response_data);
                
            } else {
                // Invalid password - increment failed attempts
                $failed_attempts = ($user['failed_login_attempts'] ?? 0) + 1;
                $max_attempts = 5;
                
                // Lock account after max attempts (lock for 30 minutes)
                $locked_until = null;
                if ($failed_attempts >= $max_attempts) {
                    $locked_until = date('Y-m-d H:i:s', time() + (30 * 60)); // 30 minutes
                }
                
                $increment_sql = "UPDATE users SET 
                                failed_login_attempts = ?,
                                locked_until = ?
                                WHERE user_id = ?";
                $increment_stmt = $conn->prepare($increment_sql);
                $increment_stmt->bind_param("isi", $failed_attempts, $locked_until, $user['user_id']);
                $increment_stmt->execute();
                $increment_stmt->close();
                
                // Log failed login attempt
                $log_sql = "INSERT INTO audit_logs (event_type, event_category, event_description, performed_by, ip_address, created_at) 
                           VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)";
                $log_stmt = $conn->prepare($log_sql);
                $event_type = 'FAILED_LOGIN';
                $event_category = 'SYSTEM';
                $event_description = json_encode([
                    'reason' => 'invalid_password',
                    'attempt_time' => date('Y-m-d H:i:s'),
                    'attempts_count' => $failed_attempts,
                    'username_attempted' => $username
                ]);
                $performed_by = $user['username'];
                $log_stmt->bind_param("sssss", $event_type, $event_category, $event_description, $performed_by, $ip_address);
                $log_stmt->execute();
                $log_stmt->close();
                
                $remaining_attempts = $max_attempts - $failed_attempts;
                $message = $remaining_attempts > 0 
                    ? "Invalid username or password. $remaining_attempts attempts remaining."
                    : "Invalid username or password. Account will be locked after next failed attempt.";
                
                if ($failed_attempts >= $max_attempts) {
                    $message = "Account locked due to too many failed login attempts. Please try again in 30 minutes.";
                }
                
                echo json_encode([
                    'success' => false,
                    'message' => $message,
                    'remaining_attempts' => $remaining_attempts,
                    'will_lock' => $remaining_attempts <= 0
                ]);
            }
        } else {
            // User not found - log the attempt
            $log_sql = "INSERT INTO audit_logs (event_type, event_category, event_description, performed_by, ip_address, created_at) 
                       VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)";
            $log_stmt = $conn->prepare($log_sql);
            $event_type = 'FAILED_LOGIN';
            $event_category = 'SYSTEM';
            $event_description = json_encode([
                'reason' => 'user_not_found',
                'username_attempted' => $username,
                'attempt_time' => date('Y-m-d H:i:s')
            ]);
            $performed_by = 'UNKNOWN';
            $log_stmt->bind_param("sssss", $event_type, $event_category, $event_description, $performed_by, $ip_address);
            $log_stmt->execute();
            $log_stmt->close();
            
            echo json_encode([
                'success' => false,
                'message' => 'Invalid username or password',
                'user_found' => false
            ]);
        }
        
        $stmt->close();
        $conn->close();
        
    } catch (Exception $e) {
        error_log("Login error: " . $e->getMessage());
        
        // Log system error
        if (isset($conn)) {
            $log_sql = "INSERT INTO audit_logs (event_type, event_category, event_description, performed_by, ip_address, created_at) 
                       VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)";
            $log_stmt = $conn->prepare($log_sql);
            $event_type = 'SYSTEM_ERROR';
            $event_category = 'SYSTEM';
            $event_description = json_encode([
                'error_type' => 'login_system_error',
                'error_message' => $e->getMessage(),
                'error_time' => date('Y-m-d H:i:s'),
                'username_attempted' => $username
            ]);
            $performed_by = 'SYSTEM';
            $log_stmt->bind_param("sssss", $event_type, $event_category, $event_description, $performed_by, $ip_address);
            $log_stmt->execute();
            $log_stmt->close();
        }
        
        echo json_encode([
            'success' => false,
            'message' => 'A system error occurred during login. Please try again or contact support.',
            'error_type' => 'system_error'
        ]);
    }
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request method. Only POST requests are allowed.',
        'error_type' => 'method_not_allowed'
    ]);
}
?>
