<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require_once "includes/db.php";

$page_title = "Login | MediPrime";

/**
 * -------------------------------------------------
 * Redirect user based on role
 * -------------------------------------------------
 */
function redirectByRole(string $role): void {
    $map = [
        "Super_admin"     => "dashboard.php",
        "Admin"           => "admin_dashboard.php",
        "Staff"           => "staff_dashboard.php",
        "Doctor"          => "doctor_dashboard.php",
        "Nurse"           => "nurse_dashboard.php",
        "Lab_technician"  => "lab_dashboard.php",
        "Pharmacist"      => "pharmacist_dashboard.php",
        "Receptionist"    => "reception_dashboard.php",
        "Radiologist"     => "radiology_dashboard.php",
        "Accountant"      => "accountant_dashboard.php",
        "Cashier"         => "cashier_dashboard.php",
        "Cleaner"         => "cleaner_dashboard.php",
        "Security"        => "security_dashboard.php",
        "Driver"          => "driver_dashboard.php",
        "Dentist"          => "dentist_dashboard.php",
        "Manager"         => "manager_dashboard.php"
    ];

    header("Location: " . ($map[$role] ?? "dashboard.php"));
    exit;
}

/**
 * -------------------------------------------------
 * CSRF Token
 * -------------------------------------------------
 */
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$error = "";

/**
 * -------------------------------------------------
 * Login submission
 * -------------------------------------------------
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $login    = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $csrf     = $_POST['csrf_token'] ?? '';

    /* ---------- CSRF validation ---------- */
    if (!$csrf || !hash_equals($_SESSION['csrf_token'], $csrf)) {
        $error = "Invalid CSRF token.";
    }
    elseif ($login === '' || $password === '') {
        $error = "Email/Phone and Password are required.";
    }
    else {

        /* ---------- Fetch user (FIXED PDO ISSUE) ---------- */
        $stmt = $pdo->prepare("
            SELECT id, username, password_hash, user_role, facility_id
            FROM users
            WHERE email = :email OR phone = :phone
            LIMIT 1
        ");
        $stmt->execute([
            'email' => $login,
            'phone' => $login
        ]);

        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user || !password_verify($password, $user['password_hash'])) {
            $error = "Invalid email/phone or password.";
        }
        else {

            /* ---------- Facility enforcement ---------- */
            if ($user['user_role'] !== 'Super_admin' && empty($user['facility_id'])) {
                $error = "Your account is not assigned to any facility. Contact administrator.";
            }
            else {

                /* ---------- Validate facility ---------- */
                $facility = null;

                if (!empty($user['facility_id'])) {
                    $stmt2 = $pdo->prepare("
                        SELECT id, name, category
                        FROM facility
                        WHERE id = :fid
                        LIMIT 1
                    ");
                    $stmt2->execute(['fid' => $user['facility_id']]);
                    $facility = $stmt2->fetch(PDO::FETCH_ASSOC);

                    if (!$facility) {
                        $error = "Assigned facility not found. Contact administrator.";
                    }
                }

                if ($error === "") {

                    /* ---------- Secure session ---------- */
                    session_regenerate_id(true);

                    $_SESSION['user_id']           = $user['id'];
                    $_SESSION['username']          = $user['username'];
                    $_SESSION['user_role']         = $user['user_role'];
                    $_SESSION['facility_id']       = $user['facility_id'] ?? null;
                    $_SESSION['facility_name']     = $facility['name'] ?? null;
                    $_SESSION['facility_category'] = $facility['category'] ?? null;
                    $_SESSION['LAST_ACTIVITY']     = time();

                    redirectByRole($user['user_role']);
                }
            }
        }
    }
}
?>


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?= htmlspecialchars($page_title) ?></title>
<link rel="stylesheet" href="app-assets/css/bootstrap.css">
<style>
body { background: #f4f6f9; }
.left-panel { background: #f7f7f7; padding: 40px; border-radius: 10px; text-align: center; }
.login-card { border-radius: 10px; padding: 30px; margin-top: 50px; }
.text-danger { color: red; font-size: 0.9rem; }
.show-hide { cursor: pointer; position: absolute; right: 10px; top: 10px; }
.position-relative { position: relative; }
</style>
</head>
<body>

<div class="container mt-5">
    <div class="row justify-content-center">

        <div class="col-lg-6 col-md-6 col-12 left-panel">
            <h2 style="font-weight: 900; font-size: 1.5rem; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;">
                        <span style="color: ;">MEDI</span><span style="color: #28a745;">PRIME</span> Medical System
                    </h2>
            <p>MediPrime is a comprehensive healthcare management platform designed to streamline medical workflows, enhance patient care, and provide real-time analytics for health facilities of all sizes.</p>
            <img src="app-assets/images/logo/logo.jpg" class="img-fluid mt-2" width="1500" height="1500">
        </div>

        <div class="col-lg-6 col-md-6 col-12">
            <div class="card login-card">
                <h4 class="text-center mb-3">Login</h4>

                <?php if ($error): ?>
                    <div class="alert alert-danger" id="login-error"><?= htmlspecialchars($error) ?></div>
                <?php endif; ?>

                <form method="POST" id="loginForm">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">

                    <div class="mb-3">
                        <label>Email or Phone</label>
                        <input type="text" name="email" id="email" class="form-control" required>
                        <small class="text-danger" id="email-error"></small>
                    </div>

                    <div class="mb-3 position-relative">
                        <label>Password</label>
                        <input type="password" name="password" id="password" class="form-control" required>
                        <span class="show-hide" id="toggle-password">Show Password</span>
                        <small class="text-danger" id="password-error"></small>
                    </div>

                    <button type="submit" class="btn btn-primary w-100">Login</button>
                    <!--<p class="text-center mt-2"><a href="forgot.php">Forgot Password</a></p>-->
                </form>
            </div>
        </div>

    </div>
</div>

<script>
// Show/Hide password
document.getElementById('toggle-password').addEventListener('click', function() {
    const pwd = document.getElementById('password');
    if (pwd.type === 'password') {
        pwd.type = 'text';
        this.innerText = 'Hide Password';
    } else {
        pwd.type = 'password';
        this.innerText = 'Show Password';
    }
});

// Live validation
document.getElementById('email').addEventListener('input', function() {
    const val = this.value.trim();
    document.getElementById('email-error').textContent = val ? '' : "Email or phone is required";
});
document.getElementById('password').addEventListener('input', function() {
    const val = this.value.trim();
    document.getElementById('password-error').textContent = val ? '' : "Password is required";
});
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
