<?php
session_start();
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

// Redirect if already logged in
if (isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit();
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    include 'layouts/dbconn.php';

    $username = trim($_POST['username']);
    $password = $_POST['password'];

    if (empty($username) || empty($password)) {
        $error_message = "Username and password are required";
    } else {
        $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 your ENT schema structure
            $sql = "SELECT u.*, ur.role_name, ur.role_code,
                           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_number,
                           d.medical_license,
                           d.specialization,
                           n.nursing_license,
                           lt.license_number as tech_license
                    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
                    LEFT JOIN doctors d ON u.user_id = d.user_id  
                    LEFT JOIN nurses n ON u.user_id = n.user_id
                    LEFT JOIN lab_technicians lt ON u.user_id = lt.user_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();

                // Check login attempts (your schema has login_attempts field)
                $max_attempts = 5;
                $failed_attempts = $user['login_attempts'] ?? 0;
                
                if ($failed_attempts >= $max_attempts) {
                    $error_message = 'Account locked due to too many failed login attempts. Please contact administrator.';
                } else {
                    // Verify password (your schema uses password_hash field)
                    if (password_verify($password, $user['password_hash'])) {
                        // 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-specific 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['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['login_time'] = time();
                        $_SESSION['session_token'] = bin2hex(random_bytes(32));

                        // Set role-specific session data
                        if ($user['user_category'] === 'PATIENT') {
                            $_SESSION['patient_number'] = $user['patient_number'];
                        } elseif ($user['user_category'] === 'DOCTOR') {
                            $_SESSION['medical_license'] = $user['medical_license'];
                            $_SESSION['specialization'] = $user['specialization'];
                        } elseif ($user['user_category'] === 'NURSE') {
                            $_SESSION['nursing_license'] = $user['nursing_license'];
                        } elseif ($user['user_category'] === 'TECHNICIAN') {
                            $_SESSION['tech_license'] = $user['tech_license'];
                        }

                        // Log successful login 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);
                        $login_data = json_encode(array(
                            'login_time' => date('Y-m-d H:i:s'),
                            'ip_address' => $ip_address,
                            'role' => $user['role_name'],
                            'user_category' => $user['user_category'],
                            '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();

                        // ENT-specific role redirects
                        $redirect_url = match($user['role_code']) {
                            'SUPER_ADMIN' => 'index.php',
                            'HOSPITAL_ADMIN' => 'index.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'
                        };
                        
                        header("Location: $redirect_url");
                        exit();
                    } 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
                        ));
                        $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);
                        $error_message = $remaining_attempts > 0 
                            ? "Invalid username or password. $remaining_attempts attempts remaining."
                            : "Invalid username or password. Account will be locked after next failed attempt.";
                    }
                }
            } else {
                // User not found - log the attempt
                $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')
                ));
                $log_stmt->bind_param("sss", $failed_data, $ip_address, substr($user_agent, 0, 500));
                $log_stmt->execute();
                $log_stmt->close();

                $error_message = "Invalid username or password";
            }

            $stmt->close();

        } catch (Exception $e) {
            error_log("Login error: " . $e->getMessage());
            $error_message = "An error occurred during login. Please try again.";
        }

        $conn->close();
    }
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Sign In - Prodigy ENT Hospital Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <style>
        :root {
            --primary-green: #2d7a2d;
            --primary-green-light: #4caf50;
            --primary-green-dark: #1b5e20;
            --accent-green: #81c784;
            --success-green: #66bb6a;
            --light-green: #e8f5e8;
            --very-light-green: #f1f8f1;
            --medical-teal: #26a69a;
            --medical-teal-light: #4db6ac;
            --text-dark: #2e2e2e;
            --text-muted: #6c757d;
            --white: #ffffff;
            --light-gray: #f8f9fa;
            --border-color: #dee2e6;
        }

        body {
            background: linear-gradient(135deg, var(--very-light-green) 0%, var(--light-green) 100%);
            min-height: 100vh;
        }

        .auth-page-wrapper {
            background: linear-gradient(135deg, var(--very-light-green) 0%, var(--light-green) 100%);
        }

        .card {
            border: none;
            box-shadow: 0 10px 30px rgba(45, 122, 45, 0.1);
            border-radius: 16px;
            overflow: hidden;
        }

        /* Left side - White background with green accents for logo visibility */
        .bg-primary {
            background: linear-gradient(135deg, #ffffff 0%, #f8fffe 30%, #f0fdf4 100%) !important;
            border-right: 4px solid var(--primary-green);
        }
        
        /* Alternative gradient option - uncomment to use */
        /* 
        .bg-primary {
            background: linear-gradient(135deg, var(--very-light-green) 0%, #ffffff 50%, var(--very-light-green) 100%) !important;
        }
        */

        /* Form styling */
        .form-control {
            border: 2px solid var(--border-color);
            border-radius: 8px;
            padding: 12px 16px;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .form-control:focus {
            border-color: var(--primary-green);
            box-shadow: 0 0 0 0.2rem rgba(45, 122, 45, 0.25);
        }

        .input-group-text {
            background-color: var(--light-green);
            border: 2px solid var(--border-color);
            border-right: none;
            color: var(--primary-green);
        }

        .form-control:focus + .input-group-text,
        .input-group .form-control:focus ~ .input-group-text {
            border-color: var(--primary-green);
        }

        /* Button styling */
        .btn-primary {
            background: linear-gradient(135deg, var(--primary-green) 0%, var(--primary-green-light) 100%);
            border: none;
            border-radius: 8px;
            padding: 12px 24px;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-primary:hover {
            background: linear-gradient(135deg, var(--primary-green-dark) 0%, var(--primary-green) 100%);
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(45, 122, 45, 0.3);
        }

        .btn-outline-secondary {
            border-color: var(--border-color);
            color: var(--text-muted);
        }

        .btn-outline-secondary:hover {
            background-color: var(--light-green);
            border-color: var(--primary-green);
            color: var(--primary-green);
        }

        /* Alert styling */
        .alert-danger {
            background-color: #fff5f5;
            border-color: #fed7d7;
            color: #c53030;
            border-left: 4px solid #e53e3e;
        }

        /* Link styling */
        a {
            color: var(--primary-green);
            text-decoration: none;
        }

        a:hover {
            color: var(--primary-green-dark);
            text-decoration: underline;
        }

        /* Text colors */
        .text-primary {
            color: var(--primary-green) !important;
        }

        .text-info {
            color: var(--medical-teal) !important;
        }

        /* Background variants */
        .bg-info {
            background-color: rgba(38, 166, 154, 0.1) !important;
        }

        .bg-light {
            background-color: var(--very-light-green) !important;
        }

        /* Form validation */
        .is-valid {
            border-color: var(--success-green);
        }

        .is-invalid {
            border-color: #e53e3e;
        }

        /* Checkbox styling */
        .form-check-input:checked {
            background-color: var(--primary-green);
            border-color: var(--primary-green);
        }

        .form-check-input:focus {
            box-shadow: 0 0 0 0.2rem rgba(45, 122, 45, 0.25);
        }

        /* Logo container enhancements */
        .position-relative img {
            filter: none;
            drop-shadow: 0 2px 10px rgba(45, 122, 45, 0.1);
        }
        
        /* Add subtle green accent behind logo */
        .logo-accent {
            position: absolute;
            top: -10px;
            left: -10px;
            right: -10px;
            bottom: -10px;
            background: linear-gradient(135deg, var(--light-green), var(--very-light-green));
            border-radius: 50%;
            z-index: -1;
            opacity: 0.3;
        }

        /* Medical service icons */
        .text-white-50 {
            opacity: 0.9;
        }

        /* Footer styling */
        .footer {
            background: transparent;
        }

        .footer .text-primary {
            color: var(--primary-green) !important;
        }

        /* Responsive adjustments */
        @media (max-width: 768px) {
            .card {
                margin: 15px;
            }
            
            .p-lg-5 {
                padding: 2rem !important;
            }
        }

        /* Enhanced visual elements */
        .card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, var(--primary-green) 0%, var(--medical-teal) 100%);
            z-index: 1;
        }

        /* Spinner color for loading state */
        .spinner-border {
            color: var(--white);
        }

        /* Input group enhancements */
        .input-group {
            border-radius: 8px;
            overflow: hidden;
        }

        .input-group .form-control:not(:first-child) {
            border-left: none;
        }

        /* Enhanced shadow for better depth */
        .shadow-lg {
            box-shadow: 0 1rem 3rem rgba(45, 122, 45, 0.175) !important;
        }
    </style>
</head>

<body>
    <div class="auth-page-wrapper py-5 d-flex justify-content-center align-items-center min-vh-100">
        <div class="auth-page-content overflow-hidden pt-lg-5">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card overflow-hidden border-0 shadow-lg">
                            <div class="row g-0">
                                <div class="col-lg-6">
                                    <div class="p-lg-5 p-4 h-100 bg-primary bg-gradient">
                                        <div class="position-relative h-100 d-flex flex-column align-items-center justify-content-center text-center">
                                            <div class="mb-4">
                                                <a href="index.php" class="d-block position-relative">
                                                    <div class="logo-accent"></div>
                                                    <img src="assets/images/prodigy.png" alt="ENT Hospital" height="80" class="mb-3 position-relative">
                                                </a>
                                                <h4 class="text-dark mb-3">Prodigy ENT Hospital Management</h4>
                                                <p class="text-muted mb-4">Comprehensive healthcare management platform for Ear, Nose & Throat medical services.</p>
                                            </div>
                                            
                                            <div class="row text-center">
                                                <div class="col-12 mb-3">
                                                    <i class="ri-stethoscope-line text-primary h4 mb-2 d-block"></i>
                                                    <small class="text-muted">Patient Care Management</small>
                                                </div>
                                                <div class="col-12 mb-3">
                                                    <i class="ri-calendar-line text-primary h4 mb-2 d-block"></i>
                                                    <small class="text-muted">Appointment Scheduling</small>
                                                </div>
                                                <div class="col-12 mb-3">
                                                    <i class="ri-test-tube-line text-primary h4 mb-2 d-block"></i>
                                                    <small class="text-muted">Laboratory Services</small>
                                                </div>
                                                <div class="col-12">
                                                    <i class="ri-line-chart-line text-primary h4 mb-2 d-block"></i>
                                                    <small class="text-muted">Medical Analytics</small>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-lg-6">
                                    <div class="p-lg-5 p-4">
                                        <div class="text-center mb-4">
                                            <h5 class="text-primary mb-2">Welcome Back!</h5>
                                            <p class="text-muted">Sign in to continue to Prodigy ENT Hospital Management System</p>
                                        </div>

                                        <div class="mt-4">
                                            <?php if(isset($error_message)): ?>
                                                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                                    <i class="ri-error-warning-line me-2"></i>
                                                    <?php echo htmlspecialchars($error_message); ?>
                                                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                                </div>
                                            <?php endif; ?>

                                            <form id="login-form" method="POST" novalidate>
                                                <div class="mb-3">
                                                    <label for="username" class="form-label">Username or Email</label>
                                                    <div class="input-group">
                                                        <span class="input-group-text"><i class="ri-user-line"></i></span>
                                                        <input type="text" class="form-control" id="username" name="username" 
                                                               placeholder="Enter username or email" 
                                                               value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>"
                                                               required>
                                                    </div>
                                                    <div class="invalid-feedback">
                                                        Please enter your username or email.
                                                    </div>
                                                </div>

                                                <div class="mb-3">
                                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                                        <label class="form-label mb-0" for="password">Password</label>
                                                        <a href="forgot_password.php" class="text-muted text-decoration-none small">
                                                            <i class="ri-lock-line me-1"></i>Forgot password?
                                                        </a>
                                                    </div>
                                                    <div class="input-group">
                                                        <span class="input-group-text"><i class="ri-lock-line"></i></span>
                                                        <input type="password" class="form-control" placeholder="Enter password" 
                                                               id="password" name="password" required>
                                                        <button class="btn btn-outline-secondary" type="button" id="password-addon">
                                                            <i class="ri-eye-line"></i>
                                                        </button>
                                                    </div>
                                                    <div class="invalid-feedback">
                                                        Please enter your password.
                                                    </div>
                                                </div>

                                                <div class="form-check mb-3">
                                                    <input class="form-check-input" type="checkbox" value="" id="auth-remember-check">
                                                    <label class="form-check-label" for="auth-remember-check">
                                                        Remember me on this device
                                                    </label>
                                                </div>

                                                <div class="mt-4">
                                                    <button class="btn btn-primary w-100" type="submit" id="login-btn">
                                                        <i class="ri-login-box-line me-2"></i>Sign In
                                                    </button>
                                                </div>

                                                <!-- ENT System User Roles -->
                                                <div class="mt-4 p-3 bg-light rounded">
                                                    <h6 class="text-muted mb-2">
                                                        <i class="ri-information-line me-2"></i>User Access Levels
                                                    </h6>
                                                    <small class="text-muted">
                                                        <strong>Medical Staff:</strong> Doctors, Nurses, Technicians<br>
                                                        <strong>Administrative:</strong> Reception, Billing, Records<br>
                                                        <strong>Management:</strong> Hospital Admin, System Admin<br>
                                                        <strong>Patient Portal:</strong> Online patient access
                                                    </small>
                                                </div>

                                                <!-- Support information -->
                                                <div class="mt-3 p-3 bg-info bg-opacity-10 rounded">
                                                    <h6 class="text-info mb-2">
                                                        <i class="ri-headphone-line me-2"></i>Need Help?
                                                    </h6>
                                                    <small class="text-muted">
                                                        Contact IT Support for technical issues.<br>
                                                        <strong>Support:</strong> support@prodigykenya.com<br>
                                                        <strong>Phone:</strong> +254-722-279-159<br>
                                                        <strong>Emergency:</strong> +254-722-279-159
                                                    </small>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <footer class="footer">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="text-center">
                            <p class="mb-0 text-muted">
                                &copy; <script>document.write(new Date().getFullYear())</script> 
                                <span class="text-primary fw-semibold">Prodigy ENT Hospital</span> - 
                                Professional Healthcare Management System
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </footer>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>

    <script>
    // Password toggle functionality
    document.getElementById('password-addon').addEventListener('click', function() {
        const passwordInput = document.getElementById('password');
        const icon = this.querySelector('i');
        
        if (passwordInput.type === 'password') {
            passwordInput.type = 'text';
            icon.className = 'ri-eye-off-line';
        } else {
            passwordInput.type = 'password';
            icon.className = 'ri-eye-line';
        }
    });

    // Form validation and submission
    document.getElementById('login-form').addEventListener('submit', function(event) {
        const form = this;
        const username = document.getElementById('username');
        const password = document.getElementById('password');
        const loginBtn = document.getElementById('login-btn');
        
        form.classList.remove('was-validated');
        
        let isValid = true;
        
        if (!username.value.trim()) {
            username.classList.add('is-invalid');
            isValid = false;
        } else {
            username.classList.remove('is-invalid');
            username.classList.add('is-valid');
        }
        
        if (!password.value) {
            password.classList.add('is-invalid');
            isValid = false;
        } else {
            password.classList.remove('is-invalid');
            password.classList.add('is-valid');
        }
        
        if (!isValid) {
            event.preventDefault();
            form.classList.add('was-validated');
            return;
        }
        
        loginBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Signing in...';
        loginBtn.disabled = true;
    });

    // Auto-focus on username field
    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('username').focus();
    });

    // Show success message if redirected from logout
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('logout') === 'success') {
        Swal.fire({
            icon: 'success',
            title: 'Logged Out',
            text: 'You have been successfully logged out.',
            timer: 2000,
            showConfirmButton: false
        });
    }

    // Auto-dismiss alerts
    setTimeout(function() {
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(function(alert) {
            if (alert.querySelector('.btn-close')) {
                alert.querySelector('.btn-close').click();
            }
        });
    }, 10000);

    // Security: Clear password on page unload
    window.addEventListener('beforeunload', function() {
        document.getElementById('password').value = '';
    });

    // Prevent multiple submissions
    let isSubmitting = false;
    document.getElementById('login-form').addEventListener('submit', function(e) {
        if (isSubmitting) {
            e.preventDefault();
            return false;
        }
        isSubmitting = true;
    });

    window.addEventListener('load', function() {
        isSubmitting = false;
        const loginBtn = document.getElementById('login-btn');
        loginBtn.innerHTML = '<i class="ri-login-box-line me-2"></i>Sign In';
        loginBtn.disabled = false;
    });
    </script>
    <script>
     (function() {
       var script = document.createElement('script');
       script.src = 'https://ent.nelcare.co.ke/chatbot-widget.js';
       script.async = true;
       document.head.appendChild(script);
     })();
   </script>
</body>
</html>