<?php
session_start();

// Set proper JSON headers
header('Content-Type: application/json');

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Include your database connection file
    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(array(
            'success' => false, 
            'message' => 'Username and password are required'
        ));
        exit;
    }
    
    // Get client IP address
    $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 {
        // Check if user exists and get all relevant data including role information
        $sql = "SELECT u.*, ur.role_name, ur.is_active as role_active, b.branch_name, b.branch_code,
                       d.doctor_id, d.specialization, d.consultation_fee,
                       n.nurse_id, n.qualification as nurse_qualification
                FROM users u 
                INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                LEFT JOIN branches b ON u.branch_id = b.branch_id 
                LEFT JOIN doctors d ON u.user_id = d.user_id AND d.is_active = 1
                LEFT JOIN nurses n ON u.user_id = n.user_id AND n.is_active = 1
                WHERE (u.username = ? OR u.email = ?) AND u.status = 'ACTIVE'";
        
        $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 role is active
            if (!$user['role_active']) {
                echo json_encode(array(
                    'success' => false,
                    'message' => 'Your user role is currently inactive. Please contact administrator.'
                ));
                exit;
            }
            
            // Check for maximum login attempts
            $max_attempts_sql = "SELECT setting_value FROM system_settings WHERE setting_key = 'max_login_attempts'";
            $max_attempts_result = $conn->query($max_attempts_sql);
            $max_attempts = 5; // default
            if ($max_attempts_result && $max_attempts_result->num_rows > 0) {
                $max_attempts = (int)$max_attempts_result->fetch_assoc()['setting_value'];
            }
            
            if ($user['login_attempts'] >= $max_attempts) {
                echo json_encode(array(
                    'success' => false,
                    'message' => 'Account locked due to too many failed login attempts. Please contact administrator.'
                ));
                exit;
            }
            
            // Verify the entered password with the hashed password from the database
            if (password_verify($password, $user['password_hash'])) {
                // Password is correct - Reset login attempts and update last login
                $update_sql = "UPDATE users SET 
                              login_attempts = 0, 
                              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();
                
                // Set comprehensive session variables matching healthcare schema
                $_SESSION['user_id'] = $user['user_id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['email'] = $user['email'];
                $_SESSION['full_name'] = $user['full_name'];
                $_SESSION['role_id'] = $user['role_id'];
                $_SESSION['role_name'] = $user['role_name'];
                $_SESSION['staff_number'] = $user['staff_number']; // Changed from agent_code
                $_SESSION['license_number'] = $user['license_number'];
                $_SESSION['branch_id'] = $user['branch_id'];
                $_SESSION['branch_name'] = $user['branch_name'];
                $_SESSION['branch_code'] = $user['branch_code'];
                $_SESSION['supervisor_id'] = $user['supervisor_id'];
                $_SESSION['commission_rate'] = $user['commission_rate'];
                $_SESSION['login_time'] = time();
                
                // Set role-specific session data
                if ($user['doctor_id']) {
                    $_SESSION['doctor_id'] = $user['doctor_id'];
                    $_SESSION['specialization'] = $user['specialization'];
                    $_SESSION['consultation_fee'] = $user['consultation_fee'];
                }
                
                if ($user['nurse_id']) {
                    $_SESSION['nurse_id'] = $user['nurse_id'];
                    $_SESSION['nurse_qualification'] = $user['nurse_qualification'];
                }
                
                // Generate session token for additional security
                $_SESSION['session_token'] = bin2hex(random_bytes(32));
                
                // Log successful login activity
                $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, new_values, ip_address, user_agent, session_id) 
                           VALUES (?, 'LOGIN', 'AUTH', ?, 'USER', ?, ?, ?, ?)";
                $log_stmt = $conn->prepare($log_sql);
                $session_id = session_id();
                $login_data = json_encode(array(
                    'login_time' => date('Y-m-d H:i:s'),
                    'ip_address' => $ip_address,
                    'user_agent' => substr($user_agent, 0, 200),
                    'role' => $user['role_name']
                ));
                $log_stmt->bind_param("iissss", $user['user_id'], $user['user_id'], $login_data, $ip_address, $user_agent, $session_id);
                $log_stmt->execute();
                $log_stmt->close();
                
                // Determine redirect URL based on role
                $redirect_url = match($user['role_name']) {
                    'Doctor' => 'doctor/dashboard.php',
                    'Nurse' => 'nurse/dashboard.php',
                    'Receptionist' => 'front-office/dashboard.php',
                    'Lab Technician', 'Lab Manager' => 'lab/dashboard.php',
                    'Billing Clerk' => 'billing/dashboard.php',
                    'Super Admin', 'Hospital Admin' => 'admin/dashboard.php',
                    default => 'index.php'
                };
                
                // Prepare response data
                $response_data = array(
                    'success' => true,
                    'user' => array(
                        'user_id' => $user['user_id'],
                        'username' => $user['username'],
                        'full_name' => $user['full_name'],
                        'email' => $user['email'],
                        'role_id' => $user['role_id'],
                        'role_name' => $user['role_name'],
                        'staff_number' => $user['staff_number'],
                        'branch_name' => $user['branch_name'],
                        'commission_rate' => $user['commission_rate'],
                        'doctor_id' => $user['doctor_id'],
                        'nurse_id' => $user['nurse_id']
                    ),
                    'redirect_url' => $redirect_url
                );
                
                echo json_encode($response_data);
                
            } else {
                // Invalid password - increment login attempts
                $increment_sql = "UPDATE users SET login_attempts = login_attempts + 1 WHERE user_id = ?";
                $increment_stmt = $conn->prepare($increment_sql);
                $increment_stmt->bind_param("i", $user['user_id']);
                $increment_stmt->execute();
                $increment_stmt->close();
                
                // Log failed login attempt
                $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, new_values, ip_address, user_agent) 
                           VALUES (?, 'FAILED_LOGIN', 'AUTH', ?, 'USER', ?, ?, ?)";
                $log_stmt = $conn->prepare($log_sql);
                $failed_data = json_encode(array(
                    'reason' => 'invalid_password',
                    'attempt_time' => date('Y-m-d H:i:s'),
                    'attempts_count' => $user['login_attempts'] + 1
                ));
                $log_stmt->bind_param("iisss", $user['user_id'], $user['user_id'], $failed_data, $ip_address, $user_agent);
                $log_stmt->execute();
                $log_stmt->close();
                
                $remaining_attempts = $max_attempts - ($user['login_attempts'] + 1);
                $message = $remaining_attempts > 0 
                    ? "Invalid username or password. $remaining_attempts attempts remaining."
                    : "Invalid username or password. Account will be locked after next failed attempt.";
                
                echo json_encode(array(
                    'success' => false,
                    'message' => $message
                ));
            }
        } else {
            // User not found - log the attempt
            $log_sql = "INSERT INTO activity_log (action, module, record_type, new_values, ip_address, user_agent) 
                       VALUES ('FAILED_LOGIN', 'AUTH', 'SYSTEM', ?, ?, ?)";
            $log_stmt = $conn->prepare($log_sql);
            $failed_data = json_encode(array(
                'reason' => 'user_not_found',
                'username_attempted' => $username,
                'attempt_time' => date('Y-m-d H:i:s')
            ));
            $log_stmt->bind_param("sss", $failed_data, $ip_address, $user_agent);
            $log_stmt->execute();
            $log_stmt->close();
            
            echo json_encode(array(
                'success' => false,
                'message' => 'Invalid username or password'
            ));
        }
        
        $stmt->close();
        
    } catch (Exception $e) {
        error_log("Login error: " . $e->getMessage());
        
        echo json_encode(array(
            'success' => false,
            'message' => 'An error occurred during login. Please try again.'
        ));
    }
    
    $conn->close();
} else {
    echo json_encode(array(
        'success' => false,
        'message' => 'Invalid request method'
    ));
}
?>