<?php
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(array(
            '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 {
        // Enhanced query to get user data with ENT-specific roles and profiles
        $sql = "SELECT u.*, ur.role_name, ur.role_code, ur.description as role_description,
                       CASE 
                           WHEN p.patient_id IS NOT NULL THEN 'PATIENT'
                           WHEN d.doctor_id IS NOT NULL THEN 'DOCTOR' 
                           WHEN n.nurse_id IS NOT NULL THEN 'NURSE'
                           WHEN lt.tech_id IS NOT NULL THEN 'TECHNICIAN'
                           ELSE 'STAFF'
                       END as user_category,
                       p.patient_id,
                       p.patient_number,
                       p.insurance_provider_id,
                       d.doctor_id,
                       d.medical_license,
                       d.specialization,
                       d.sub_specialization,
                       d.consultation_fee,
                       d.is_consultant,
                       d.is_surgeon,
                       n.nurse_id,
                       n.nursing_license,
                       n.is_head_nurse,
                       lt.tech_id,
                       lt.license_number as tech_license,
                       lt.is_senior_tech,
                       hb.branch_name,
                       hb.branch_code
                FROM users u 
                INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                LEFT JOIN patients p ON u.user_id = p.user_id AND p.is_active = 1
                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
                LEFT JOIN lab_technicians lt ON u.user_id = lt.user_id AND lt.is_active = 1
                LEFT JOIN hospital_branches hb ON u.branch_id = hb.branch_id
                WHERE (u.username = ? OR u.email = ?) AND u.status = 'ACTIVE' AND ur.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();
            
            // Get maximum login attempts from system settings
            $max_attempts = 5; // default
            $max_attempts_sql = "SELECT setting_value FROM system_settings WHERE setting_key = 'max_login_attempts'";
            $max_attempts_result = $conn->query($max_attempts_sql);
            if ($max_attempts_result && $max_attempts_result->num_rows > 0) {
                $max_attempts = (int)$max_attempts_result->fetch_assoc()['setting_value'];
            }
            
            // Check login attempts (using your schema's login_attempts field)
            $failed_attempts = $user['login_attempts'] ?? 0;
            if ($failed_attempts >= $max_attempts) {
                echo json_encode(array(
                    'success' => false,
                    'message' => 'Account locked due to too many failed login attempts. Please contact administrator.',
                    'locked' => true
                ));
                exit;
            }
            
            // Verify the password with the hashed password (using password_hash field from your schema)
            if (password_verify($password, $user['password_hash'])) {
                // Password is correct - Reset failed 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 ENT Hospital Management System session variables
                $_SESSION['user_id'] = $user['user_id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['email'] = $user['email'];
                $_SESSION['full_name'] = $user['full_name'];
                $_SESSION['phone_primary'] = $user['phone_primary'];
                $_SESSION['phone_secondary'] = $user['phone_secondary'];
                $_SESSION['role_id'] = $user['role_id'];
                $_SESSION['role_name'] = $user['role_name'];
                $_SESSION['role_code'] = $user['role_code'];
                $_SESSION['user_type'] = $user['user_type'];
                $_SESSION['user_category'] = $user['user_category'];
                $_SESSION['branch_id'] = $user['branch_id'];
                $_SESSION['branch_name'] = $user['branch_name'];
                $_SESSION['branch_code'] = $user['branch_code'];
                $_SESSION['staff_number'] = $user['staff_number'];
                $_SESSION['login_time'] = time();
                
                // Generate session token for additional security
                $_SESSION['session_token'] = bin2hex(random_bytes(32));
                
                // Set role-specific session data based on user category
                $profile_data = array();
                
                if ($user['user_category'] === 'PATIENT' && $user['patient_id']) {
                    $_SESSION['patient_id'] = $user['patient_id'];
                    $_SESSION['patient_number'] = $user['patient_number'];
                    $_SESSION['insurance_provider_id'] = $user['insurance_provider_id'];
                    $profile_data['patient_number'] = $user['patient_number'];
                    $profile_data['has_insurance'] = !empty($user['insurance_provider_id']);
                }
                
                if ($user['user_category'] === 'DOCTOR' && $user['doctor_id']) {
                    $_SESSION['doctor_id'] = $user['doctor_id'];
                    $_SESSION['medical_license'] = $user['medical_license'];
                    $_SESSION['specialization'] = $user['specialization'];
                    $_SESSION['sub_specialization'] = $user['sub_specialization'];
                    $_SESSION['consultation_fee'] = $user['consultation_fee'];
                    $_SESSION['is_consultant'] = $user['is_consultant'];
                    $_SESSION['is_surgeon'] = $user['is_surgeon'];
                    $profile_data['medical_license'] = $user['medical_license'];
                    $profile_data['specialization'] = $user['specialization'];
                    $profile_data['is_consultant'] = $user['is_consultant'];
                }
                
                if ($user['user_category'] === 'NURSE' && $user['nurse_id']) {
                    $_SESSION['nurse_id'] = $user['nurse_id'];
                    $_SESSION['nursing_license'] = $user['nursing_license'];
                    $_SESSION['is_head_nurse'] = $user['is_head_nurse'];
                    $profile_data['nursing_license'] = $user['nursing_license'];
                    $profile_data['is_head_nurse'] = $user['is_head_nurse'];
                }
                
                if ($user['user_category'] === 'TECHNICIAN' && $user['tech_id']) {
                    $_SESSION['tech_id'] = $user['tech_id'];
                    $_SESSION['tech_license'] = $user['tech_license'];
                    $_SESSION['is_senior_tech'] = $user['is_senior_tech'];
                    $profile_data['tech_license'] = $user['tech_license'];
                    $profile_data['is_senior_tech'] = $user['is_senior_tech'];
                }
                
                // Log successful login activity using your activity_log schema
                $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values, ip_address, user_agent, logged_at) 
                           VALUES (?, 'LOGIN', 'authentication', ?, ?, ?, ?, NOW())";
                $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'],
                    'user_category' => $user['user_category'],
                    'branch' => $user['branch_name'],
                    'session_id' => $session_id
                ));
                $log_stmt->bind_param("issss", $user['user_id'], $user['user_id'], $login_data, $ip_address, substr($user_agent, 0, 500));
                $log_stmt->execute();
                $log_stmt->close();
                
                // Determine redirect URL based on ENT hospital roles
                $redirect_url = match($user['role_code']) {
                    'SUPER_ADMIN' => 'index.php',
                    'HOSPITAL_ADMIN' => 'admin_dashboard.php',
                    'ENT_CONSULTANT' => 'doctor_dashboard.php',
                    'ENT_DOCTOR' => 'doctor_dashboard.php',
                    'RESIDENT_DOCTOR' => 'resident_dashboard.php',
                    'HEAD_NURSE' => 'nursing_dashboard.php',
                    'ENT_NURSE' => 'nursing_dashboard.php',
                    'AUDIOLOGIST' => 'audiologist_dashboard.php',
                    'LAB_TECHNICIAN' => 'lab_dashboard.php',
                    'RECEPTIONIST' => 'reception_dashboard.php',
                    'BILLING_CLERK' => 'billing_dashboard.php',
                    'MEDICAL_RECORDS' => 'records_dashboard.php',
                    'PATIENT' => 'patient_portal.php',
                    default => 'index.php'
                };
                
                // Get quick stats relevant to the user's role
                $stats = array();
                
                try {
                    // For Doctors - get their patient and consultation statistics
                    if ($user['user_category'] === 'DOCTOR' && $user['doctor_id']) {
                        $doctor_stats_sql = "SELECT 
                                            COUNT(DISTINCT c.consultation_id) as total_consultations,
                                            COUNT(DISTINCT a.appointment_id) as total_appointments,
                                            COUNT(DISTINCT CASE WHEN a.appointment_date = CURDATE() THEN a.appointment_id END) as today_appointments,
                                            COUNT(DISTINCT c.patient_id) as unique_patients_treated,
                                            COALESCE(SUM(c.consultation_fee), 0) as total_revenue,
                                            COUNT(DISTINCT pp.procedure_id) as procedures_performed
                                            FROM doctors d
                                            LEFT JOIN consultations c ON d.doctor_id = c.doctor_id AND c.status = 'COMPLETED'
                                            LEFT JOIN appointments a ON d.doctor_id = a.doctor_id
                                            LEFT JOIN patient_procedures pp ON d.doctor_id = pp.performed_by AND pp.status = 'COMPLETED'
                                            WHERE d.doctor_id = ? AND d.is_active = 1";
                        $doctor_stats_stmt = $conn->prepare($doctor_stats_sql);
                        $doctor_stats_stmt->bind_param("i", $user['doctor_id']);
                        $doctor_stats_stmt->execute();
                        $doctor_stats_result = $doctor_stats_stmt->get_result();
                        
                        if ($doctor_stats_result->num_rows > 0) {
                            $stats = $doctor_stats_result->fetch_assoc();
                        }
                        $doctor_stats_stmt->close();
                    }
                    
                    // For Nurses - get patient care statistics
                    if ($user['user_category'] === 'NURSE' && $user['nurse_id']) {
                        $nurse_stats_sql = "SELECT 
                                          COUNT(DISTINCT pv.visit_id) as patients_cared_for,
                                          COUNT(DISTINCT CASE WHEN pv.registration_date = CURDATE() THEN pv.visit_id END) as today_patients,
                                          COUNT(DISTINCT pp.procedure_id) as procedures_assisted
                                          FROM nurses n
                                          LEFT JOIN patient_visits pv ON pv.registered_by = n.user_id
                                          LEFT JOIN patient_procedures pp ON JSON_CONTAINS(pp.assisted_by, CAST(n.user_id AS JSON))
                                          WHERE n.nurse_id = ? AND n.is_active = 1";
                        $nurse_stats_stmt = $conn->prepare($nurse_stats_sql);
                        $nurse_stats_stmt->bind_param("i", $user['nurse_id']);
                        $nurse_stats_stmt->execute();
                        $nurse_stats_result = $nurse_stats_stmt->get_result();
                        
                        if ($nurse_stats_result->num_rows > 0) {
                            $nurse_stats = $nurse_stats_result->fetch_assoc();
                            $stats = array_merge($stats, $nurse_stats);
                        }
                        $nurse_stats_stmt->close();
                    }
                    
                    // For Lab Technicians - get lab order statistics
                    if ($user['user_category'] === 'TECHNICIAN' && $user['tech_id']) {
                        $tech_stats_sql = "SELECT 
                                         COUNT(DISTINCT lot.order_test_id) as tests_processed,
                                         COUNT(DISTINCT CASE WHEN lot.status = 'PENDING' THEN lot.order_test_id END) as pending_tests,
                                         COUNT(DISTINCT CASE WHEN lot.completed_at >= CURDATE() THEN lot.order_test_id END) as today_completed,
                                         COUNT(DISTINCT lo.patient_id) as patients_served
                                         FROM lab_technicians lt
                                         LEFT JOIN lab_order_tests lot ON lt.user_id = lot.tested_by
                                         LEFT JOIN lab_orders lo ON lot.order_id = lo.order_id
                                         WHERE lt.tech_id = ? AND lt.is_active = 1";
                        $tech_stats_stmt = $conn->prepare($tech_stats_sql);
                        $tech_stats_stmt->bind_param("i", $user['tech_id']);
                        $tech_stats_stmt->execute();
                        $tech_stats_result = $tech_stats_stmt->get_result();
                        
                        if ($tech_stats_result->num_rows > 0) {
                            $tech_stats = $tech_stats_result->fetch_assoc();
                            $stats = array_merge($stats, $tech_stats);
                        }
                        $tech_stats_stmt->close();
                    }
                    
                    // For Patients - get their visit and appointment history
                    if ($user['user_category'] === 'PATIENT' && $user['patient_id']) {
                        $patient_stats_sql = "SELECT 
                                            COUNT(DISTINCT pv.visit_id) as total_visits,
                                            COUNT(DISTINCT a.appointment_id) as total_appointments,
                                            COUNT(DISTINCT CASE WHEN a.appointment_date >= CURDATE() THEN a.appointment_id END) as upcoming_appointments,
                                            COALESCE(SUM(pv.amount_paid), 0) as total_payments,
                                            COUNT(DISTINCT c.consultation_id) as total_consultations
                                            FROM patients p
                                            LEFT JOIN patient_visits pv ON p.patient_id = pv.patient_id
                                            LEFT JOIN appointments a ON p.patient_id = a.patient_id
                                            LEFT JOIN consultations c ON p.patient_id = c.patient_id
                                            WHERE p.patient_id = ? AND p.is_active = 1";
                        $patient_stats_stmt = $conn->prepare($patient_stats_sql);
                        $patient_stats_stmt->bind_param("i", $user['patient_id']);
                        $patient_stats_stmt->execute();
                        $patient_stats_result = $patient_stats_stmt->get_result();
                        
                        if ($patient_stats_result->num_rows > 0) {
                            $patient_stats = $patient_stats_result->fetch_assoc();
                            $stats = array_merge($stats, $patient_stats);
                        }
                        $patient_stats_stmt->close();
                    }
                    
                    // For Administrative staff - get general hospital statistics
                    if (in_array($user['role_code'], ['RECEPTIONIST', 'BILLING_CLERK', 'MEDICAL_RECORDS'])) {
                        $admin_stats_sql = "SELECT 
                                          COUNT(DISTINCT pv.visit_id) as today_visits,
                                          COUNT(DISTINCT a.appointment_id) as today_appointments,
                                          COUNT(DISTINCT CASE WHEN p.status = 'PENDING' THEN p.payment_id END) as pending_payments,
                                          COUNT(DISTINCT CASE WHEN lo.status = 'PENDING' THEN lo.order_id END) as pending_lab_orders
                                          FROM patient_visits pv
                                          LEFT JOIN appointments a ON DATE(a.appointment_date) = CURDATE()
                                          LEFT JOIN payments p ON p.status = 'PENDING'
                                          LEFT JOIN lab_orders lo ON lo.status = 'PENDING'
                                          WHERE DATE(pv.registration_date) = CURDATE()";
                        $admin_stats_result = $conn->query($admin_stats_sql);
                        
                        if ($admin_stats_result && $admin_stats_result->num_rows > 0) {
                            $admin_stats = $admin_stats_result->fetch_assoc();
                            $stats = array_merge($stats, $admin_stats);
                        }
                    }
                    
                } catch (Exception $e) {
                    // Stats are optional, continue without them if there's an error
                    error_log("Stats query error: " . $e->getMessage());
                }
                
                // Prepare comprehensive response data
                $response_data = array(
                    'success' => true,
                    'message' => 'Login successful',
                    'user' => array(
                        'user_id' => $user['user_id'],
                        'username' => $user['username'],
                        'full_name' => $user['full_name'],
                        'email' => $user['email'],
                        'phone_primary' => $user['phone_primary'],
                        'role_id' => $user['role_id'],
                        'role_name' => $user['role_name'],
                        'role_code' => $user['role_code'],
                        'user_type' => $user['user_type'],
                        'user_category' => $user['user_category'],
                        'staff_number' => $user['staff_number'],
                        'branch_name' => $user['branch_name'],
                        'branch_code' => $user['branch_code'],
                        'profile_data' => $profile_data
                    ),
                    'stats' => $stats,
                    'redirect_url' => $redirect_url,
                    'session_token' => $_SESSION['session_token'],
                    'login_time' => date('Y-m-d H:i:s'),
                    'system_info' => array(
                        'system_name' => 'ENT Hospital Management System',
                        'version' => '1.0.0',
                        'login_method' => 'ajax'
                    )
                );
                
                echo json_encode($response_data);
                
            } else {
                // Invalid password - increment failed attempts
                $increment_sql = "UPDATE users SET login_attempts = COALESCE(login_attempts, 0) + 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, new_values, ip_address, user_agent, logged_at) 
                           VALUES (?, 'FAILED_LOGIN', 'authentication', ?, ?, ?, ?, NOW())";
                $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' => $failed_attempts + 1,
                    'username_attempted' => $username
                ));
                $log_stmt->bind_param("issss", $user['user_id'], $user['user_id'], $failed_data, $ip_address, substr($user_agent, 0, 500));
                $log_stmt->execute();
                $log_stmt->close();
                
                $remaining_attempts = $max_attempts - ($failed_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,
                    'remaining_attempts' => $remaining_attempts,
                    'will_lock' => $remaining_attempts <= 0
                ));
            }
        } else {
            // User not found - log the attempt without revealing this information
            $log_sql = "INSERT INTO activity_log (action, module, record_id, new_values, ip_address, user_agent, logged_at) 
                       VALUES ('FAILED_LOGIN', 'authentication', '0', ?, ?, ?, NOW())";
            $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'),
                'ip_address' => $ip_address
            ));
            $log_stmt->bind_param("sss", $failed_data, $ip_address, substr($user_agent, 0, 500));
            $log_stmt->execute();
            $log_stmt->close();
            
            echo json_encode(array(
                'success' => false,
                'message' => 'Invalid username or password',
                'user_found' => false
            ));
        }
        
        $stmt->close();
        
    } catch (Exception $e) {
        error_log("Login error: " . $e->getMessage());
        
        // Log system error
        $log_sql = "INSERT INTO activity_log (action, module, record_id, new_values, ip_address, user_agent, logged_at) 
                   VALUES ('SYSTEM_ERROR', 'authentication', '0', ?, ?, ?, NOW())";
        $log_stmt = $conn->prepare($log_sql);
        $error_data = json_encode(array(
            'error_type' => 'login_system_error',
            'error_message' => $e->getMessage(),
            'error_time' => date('Y-m-d H:i:s'),
            'username_attempted' => $username
        ));
        $log_stmt->bind_param("sss", $error_data, $ip_address, substr($user_agent, 0, 500));
        $log_stmt->execute();
        $log_stmt->close();
        
        echo json_encode(array(
            'success' => false,
            'message' => 'A system error occurred during login. Please try again or contact support.',
            'error_type' => 'system_error'
        ));
    }
    
    $conn->close();
} else {
    echo json_encode(array(
        'success' => false,
        'message' => 'Invalid request method. Only POST requests are allowed.',
        'error_type' => 'method_not_allowed'
    ));
}
?>