<?php
session_start();
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.

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

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)) {
        $error_message = "Username and password are required";
    } else {
        // Get client IP address and user agent for 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 {
            // 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 
                    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 
                    WHERE u.username = ? OR u.email = ?";
            
            $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 user account is active (exact ENUM values from schema: ACTIVE, INACTIVE, SUSPENDED, PENDING)
                if ($user['status'] !== 'ACTIVE') {
                    $error_message = match($user['status']) {
                        'INACTIVE' => 'Your account is inactive. Please contact administrator.',
                        'SUSPENDED' => 'Your account has been suspended. Please contact administrator.',
                        'PENDING' => 'Your account is pending approval. Please contact administrator.',
                        default => 'Account status not valid. Please contact administrator.'
                    };
                } else if (!$user['role_active']) {
                    $error_message = 'Your user role is currently inactive. Please contact administrator.';
                } else {
                    // 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) {
                        $error_message = 'Account locked due to too many failed login attempts. Please contact administrator.';
                    } else {
                        // 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
                            $_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['agent_code'] = $user['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['target_monthly'] = $user['target_monthly'];
                            $_SESSION['login_time'] = time();
                            $_SESSION['session_token'] = bin2hex(random_bytes(32));

                            // Log successful login activity (matching exact activity_log schema)
                            $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)
                            ));
                            $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();

                            // Redirect based on role
                            header('Location: index.php');
                            exit();
                        } 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 (matching exact activity_log schema)
                            $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);
                            $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 (matching exact activity_log schema)
                $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();

                $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 - Hoslink EMR Platform')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>

<body>
    <!-- auth-page wrapper -->
    <div class="auth-page-wrapper py-5 d-flex justify-content-center align-items-center min-vh-100">
        
        <!-- auth-page content -->
        <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">
                                                    <img src="assets/images/logo/ultrasure_logo_white.png" alt="Hoslink EMR Platform" height="80" class="mb-3">
                                                </a>
                                                <h4 class="text-white mb-3">Digital EMR Platform</h4>
                                                <p class="text-white-50 mb-4">Leading emr platform in East Africa with smart tools, seamless policy management, and comprehensive customer service.</p>
                                            </div>
                                            
                                            <!-- Feature highlights -->
                                            <div class="row text-center text-white-50">
                                                <div class="col-12 mb-3">
                                                    <i class="ri-shield-check-line text-white h4 mb-2 d-block"></i>
                                                    <small>Smart Agent Tools</small>
                                                </div>
                                                <div class="col-12 mb-3">
                                                    <i class="ri-customer-service-2-line text-white h4 mb-2 d-block"></i>
                                                    <small>Customer-Centric Platform</small>
                                                </div>
                                                <div class="col-12">
                                                    <i class="ri-line-chart-line text-white h4 mb-2 d-block"></i>
                                                    <small>Performance Analytics</small>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <!-- end col -->

                                <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 Hoslink EMR Platform</p>
                                        </div>

                                        <div class="mt-4">
                                            <!-- Display error message if set -->
                                            <?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-unlock-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-fill"></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-circle-line me-2"></i>Sign In
                                                    </button>
                                                </div>

                                                <!-- Quick login help -->
                                                <div class="mt-4 p-3 bg-light rounded">
                                                    <h6 class="text-muted mb-2">
                                                        <i class="ri-information-line me-2"></i>Need Help?
                                                    </h6>
                                                    <small class="text-muted">
                                                        Contact your supervisor or IT administrator for account issues.<br>
                                                        <strong>Support:</strong> support@hoslinkcare.com
                                                    </small>
                                                </div>
                                            </form>
                                        </div>

                                        <div class="mt-4 text-center">
                                            <!-- <p class="mb-0 text-muted small">
                                                New agent? <a href="agent_registration.php" class="fw-semibold text-primary text-decoration-none">Apply here</a>
                                            </p> -->
                                        </div>
                                    </div>
                                </div>
                                <!-- end col -->
                            </div>
                            <!-- end row -->
                        </div>
                        <!-- end card -->
                    </div>
                    <!-- end col -->
                </div>
                <!-- end row -->
            </div>
            <!-- end container -->
        </div>
        <!-- end auth page content -->

        <!-- footer -->
        <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">Hoslink EMR Platform</span> - 
                                Leading Digital EMR Solutions in East Africa
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </footer>
        <!-- end Footer -->
    </div>
    <!-- end auth-page-wrapper -->

    <?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-fill';
        } else {
            passwordInput.type = 'password';
            icon.className = 'ri-eye-fill';
        }
    });

    // 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');
        
        // Reset validation states
        form.classList.remove('was-validated');
        
        // Basic validation
        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;
        }
        
        // Show loading state
        loginBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Signing in...';
        loginBtn.disabled = true;
        
        // Form will submit normally since we're not preventing default for valid forms
    });

    // 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
        });
    }
    </script>
</body>
</html>