<?php
// Unified login.php
session_start();
require_once 'config/database.php';

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

if(isset($_SESSION['admin_id'])) {
    header('Location: admin/dashboard.php');
    exit;
}

if(isset($_SESSION['csr_id'])) {
    $csrRole = $_SESSION['csr_role'] ?? 'csr';
    if ($csrRole === 'csr_manager') {
        header('Location: csr_manager/dashboard.php');
    } elseif ($csrRole === 'team_leader') {
        header('Location: team_leader/dashboard.php');
    } else {
        header('Location: csr/dashboard.php');
    }
    exit;
}

$database = new Database();
$db = $database->getConnection();

$error = '';

if($_SERVER['REQUEST_METHOD'] == 'POST') {

    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $remember = isset($_POST['remember']);

    if(empty($email) || empty($password)) {

        $error = "Please enter email and password.";

    } else {

        // =========================================
        // ADMIN LOGIN
        // =========================================
        $admin_query = "SELECT * FROM admin_users WHERE email = :email AND is_active = 1 LIMIT 1";
        $admin_stmt = $db->prepare($admin_query);
        $admin_stmt->execute([':email' => $email]);

        $admin = $admin_stmt->fetch(PDO::FETCH_ASSOC);

        if($admin && password_verify($password, $admin['password'])) {

            $_SESSION['admin_id'] = $admin['id'];
            $_SESSION['admin_name'] = $admin['first_name'] . ' ' . $admin['last_name'];
            $_SESSION['admin_email'] = $admin['email'];

            $update = $db->prepare("UPDATE admin_users SET last_login = NOW() WHERE id = :id");
            $update->execute([':id' => $admin['id']]);

            header('Location: admin/dashboard.php');
            exit;
        }

        // =========================================
        // CSR LOGIN
        // =========================================
        $csr_query = "SELECT * FROM csr_users WHERE email = :email AND is_active = 1 LIMIT 1";
        $csr_stmt = $db->prepare($csr_query);
        $csr_stmt->execute([':email' => $email]);

        $csr = $csr_stmt->fetch(PDO::FETCH_ASSOC);

        if($csr && password_verify($password, $csr['password'])) {

            $_SESSION['csr_id'] = $csr['id'];
            $_SESSION['csr_name'] = $csr['first_name'] . ' ' . $csr['last_name'];
            $_SESSION['csr_email'] = $csr['email'];
            $_SESSION['csr_role'] = $csr['role'] ?? 'csr';

            $update = $db->prepare("UPDATE csr_users SET last_login = NOW() WHERE id = :id");
            $update->execute([':id' => $csr['id']]);

            // Route by role: csr_manager → own portal, team_leader → own portal, csr → CSR portal
            $csrRole = $csr['role'] ?? 'csr';
            if ($csrRole === 'csr_manager') {
                header('Location: csr_manager/dashboard.php');
            } elseif ($csrRole === 'team_leader') {
                header('Location: team_leader/dashboard.php');
            } else {
                header('Location: csr/dashboard.php');
            }
            exit;
        }

        // =========================================
        // CUSTOMER LOGIN
        // =========================================
        $customer_query = "SELECT id, first_name, last_name, email, password, is_active
                           FROM customers
                           WHERE email = :email
                           LIMIT 1";

        $customer_stmt = $db->prepare($customer_query);
        $customer_stmt->execute([':email' => $email]);

        $customer = $customer_stmt->fetch(PDO::FETCH_ASSOC);

        if($customer && password_verify($password, $customer['password'])) {

            if(!$customer['is_active']) {

                $error = "Your account has been deactivated.";

            } else {

                $_SESSION['customer_id'] = $customer['id'];
                $_SESSION['customer_name'] = $customer['first_name'] . ' ' . $customer['last_name'];
                $_SESSION['customer_email'] = $customer['email'];

                $update_query = "UPDATE customers SET last_login = NOW() WHERE id = :id";
                $update_stmt = $db->prepare($update_query);
                $update_stmt->execute([':id' => $customer['id']]);

                if($remember) {
                    $token = bin2hex(random_bytes(32));
                    setcookie('remember_token', $token, time() + (86400 * 30), '/');
                }

                header('Location: customer/dashboard.php');
                exit;
            }
        }

        $error = "Invalid email or password.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Unified Login - Home Service App</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
<link rel="stylesheet" href="assets/theme.css">

<style>
html,
body {
    min-height: 100vh !important;
    width: 100% !important;
    margin: 0 !important;
}

body {
    background: linear-gradient(135deg, #080240 0%, #093349 100%) !important;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    min-height: 100vh !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    padding: 20px !important;
}

.login-container {
    max-width: 420px !important;
    width: 100% !important;
    margin: 0 auto !important;
}

.login-card {
    background: rgba(255, 255, 255, 0.08);
    border-radius: 20px;
    box-shadow: 0 20px 40px rgba(0,0,0,0.35);
    overflow: hidden;
    border: 1px solid rgba(255,255,255,0.12);
    backdrop-filter: blur(14px);
}

.login-header {
    background: linear-gradient(135deg, #080240 0%, #093349 100%);
    color: white;
    padding: 30px;
    text-align: center;
    border-bottom: 1px solid rgba(255,255,255,0.12);
}

.login-header h2 {
    color: #ffffff !important;
    font-weight: 700;
    margin: 0;
}

.ushs-logo {
    width: 82px !important;
    height: 82px !important;
    border-radius: 50% !important;
    background: #ffffff !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    margin: 0 auto 16px !important;
    box-shadow: 0 0 22px rgba(255,255,255,0.30) !important;
    overflow: hidden !important;
}

.ushs-logo img {
    width: 120% !important;
    height: 120% !important;
    object-fit: cover !important;
    object-position: center !important;
    display: block !important;
}

.login-body {
    padding: 30px;
}

.login-body label {
    color: #ffffff !important;
    font-weight: 600;
    margin-bottom: 7px;
}

.form-control {
    border-radius: 10px;
    border: 2px solid #b8d9ee !important;
    padding: 12px 15px;
    color: #000000 !important;
    background-color: #ffffff !important;
    min-height: 46px !important;
    line-height: 1.2 !important;
}

.form-control:focus {
    color: #000000 !important;
    background-color: #ffffff !important;
    border-color: #38bdf8 !important;
    box-shadow: 0 0 0 0.18rem rgba(56,189,248,0.25) !important;
}

.form-control::placeholder {
    color: #666666 !important;
    opacity: 1 !important;
}

.password-wrapper {
    position: relative !important;
}

.password-wrapper .form-control {
    padding-right: 38px !important;
}

.toggle-password,
.toggle-password:hover,
.toggle-password:focus,
.toggle-password:active {
    position: absolute !important;
    top: 51% !important;
    right: 1px !important;
    bottom: auto !important;
    left: auto !important;
    transform: translateY(-50%) !important;
    width: 32px !important;
    height: 32px !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    margin: 0 !important;
    padding: 0 !important;
    border: none !important;
    border-radius: 8px !important;
    background: rgba(56, 189, 248, 0.18) !important;
    color: #ffffff !important;
    line-height: 1 !important;
    cursor: pointer !important;
    z-index: 20 !important;
}

.toggle-password i,
.toggle-password:hover i,
.toggle-password:focus i,
.toggle-password:active i {
    color: #ffffff !important;
    font-size: 16px !important;
    line-height: 1 !important;
    margin: 0 !important;
    padding: 0 !important;
}

.form-check-label,
.remember-text {
    color: #ffffff !important;
    font-weight: 500;
}

.form-check-input {
    border: 2px solid #b8d9ee !important;
}

.form-check-input:checked {
    background-color: #078ca0 !important;
    border-color: #078ca0 !important;
}

.btn-login {
    width: 100%;
    background: linear-gradient(135deg, #078ca0 0%, #066b80 100%);
    color: white !important;
    border: none;
    padding: 12px;
    border-radius: 10px;
    font-weight: bold;
    transition: all 0.2s ease;
}

.btn-login:hover {
    transform: translateY(-1px);
    box-shadow: 0 10px 20px rgba(7,140,160,0.25);
    color: white !important;
}

.create-account-text {
    color: #ffffff !important;
    font-weight: 500;
}

.create-account-btn,
.create-account-btn:link,
.create-account-btn:visited,
.create-account-btn:hover,
.create-account-btn:focus,
.create-account-btn:active {
    background: #ffffff !important;
    color: #080240 !important;
    border: 2px solid #ffffff !important;
    opacity: 1 !important;
    text-shadow: none !important;
    box-shadow: none !important;
}

.create-account-btn i,
.create-account-btn:hover i,
.create-account-btn:focus i,
.create-account-btn:active i {
    color: #080240 !important;
}

.create-account-btn:hover {
    background: #eaf7ff !important;
    border-color: #eaf7ff !important;
}

.alert {
    border-radius: 12px;
    font-weight: 600;
}

@media (max-width: 576px) {
    body {
        padding: 14px !important;
    }

    .login-body {
        padding: 24px 20px;
    }

    .login-header {
        padding: 26px 20px;
    }

    .form-control {
        font-size: 16px;
        min-height: 46px !important;
    }

    .ushs-logo {
        width: 76px !important;
        height: 76px !important;
    }
}


/* Final centering override for the unified login page */
html,
body.login-page {
    width: 100% !important;
    min-width: 100% !important;
    min-height: 100vh !important;
    margin: 0 !important;
}

body.login-page {
    display: grid !important;
    place-items: center !important;
    padding: 24px !important;
    overflow-x: hidden !important;
    background: linear-gradient(135deg, oklch(0.18 0.04 260), oklch(0.22 0.04 260)) !important;
}

body.login-page .login-container {
    width: min(420px, calc(100vw - 32px)) !important;
    max-width: 420px !important;
    margin: 0 auto !important;
    position: relative !important;
    left: auto !important;
    right: auto !important;
    transform: none !important;
}

body.login-page .login-card {
    width: 100% !important;
    margin: 0 auto !important;
    background: oklch(0.22 0.04 260 / 0.92) !important;
    border: 1px solid oklch(0.98 0.005 250 / 0.15) !important;
    border-radius: 0.625rem !important;
}

</style>

<link rel="stylesheet" href="assets/portal-dark.css">

<style>

html,
body {
    min-height: 100vh !important;
    width: 100% !important;
    margin: 0 !important;
}

body {
    background: linear-gradient(135deg, #080240 0%, #093349 100%) !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    padding: 20px !important;
}

.login-container {
    max-width: 420px !important;
    width: 100% !important;
    margin: 0 auto !important;
}

.ushs-logo {
    width: 82px !important;
    height: 82px !important;
    border-radius: 50% !important;
    background: linear-gradient(135deg, rgba(8,2,64,0.95), rgba(9,51,73,0.95)) !important;
    border: 1px solid rgba(56, 189, 248, 0.45) !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    margin: 0 auto 16px !important;
    box-shadow: 0 0 24px rgba(56, 189, 248, 0.30) !important;
    overflow: hidden !important;
}

.ushs-logo img {
    width: 120% !important;
    height: 120% !important;
    object-fit: cover !important;
    object-position: center !important;
    display: block !important;
}

.create-account-btn,
.create-account-btn:link,
.create-account-btn:visited,
.create-account-btn:hover,
.create-account-btn:focus,
.create-account-btn:active {
    background: #ffffff !important;
    color: #080240 !important;
    border: 2px solid #ffffff !important;
    opacity: 1 !important;
    text-shadow: none !important;
    box-shadow: none !important;
}

.create-account-btn i,
.create-account-btn:hover i,
.create-account-btn:focus i,
.create-account-btn:active i {
    color: #080240 !important;
}

.password-wrapper {
    position: relative !important;
}

.password-wrapper .form-control {
    padding-right: 38px !important;
}

.toggle-password,
.toggle-password:hover,
.toggle-password:focus,
.toggle-password:active {
    position: absolute !important;
    top: 50% !important;
    right: 3px !important;
    bottom: auto !important;
    left: auto !important;
    transform: translateY(-50%) !important;

    width: auto !important;
    height: auto !important;

    display: flex !important;
    align-items: center !important;
    justify-content: center !important;

    margin: 0 !important;
    padding: 0 !important;

    border: none !important;
    outline: none !important;
    box-shadow: none !important;
    background: transparent !important;

    color: #ffffff !important;
    line-height: 1 !important;
    cursor: pointer !important;
    z-index: 20 !important;
}

.toggle-password i,
.toggle-password:hover i,
.toggle-password:focus i,
.toggle-password:active i {
    color: #ffffff !important;
    font-size: 17px !important;
    line-height: 1 !important;
    margin: 0 !important;
    padding: 0 !important;
}

.form-control {
    min-height: 46px !important;
    line-height: 1.2 !important;
}

@media (max-width: 576px) {
    .ushs-logo {
        width: 76px !important;
        height: 76px !important;
    }
}
</style>

    <link rel="stylesheet" href="assets/ushs-global-theme.css">
</head>

<body class="login-page">

<div class="login-container">

    <div class="login-card">

        <div class="login-header">
            <div class="ushs-logo">
                <img src="logo/ushs_logo.png" alt="USHS Logo">
            </div>
            <h2>USHS Portal</h2>
        </div>

        <div class="login-body">

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

            <form method="POST">

                <div class="mb-3">
                    <label>Email</label>
                    <input 
                        type="email" 
                        name="email" 
                        class="form-control" 
                        placeholder="Enter your email"
                        required
                    >
                </div>

                <div class="mb-3">
                    <label>Password</label>

                    <div class="password-wrapper">
                        <input 
                            type="password" 
                            name="password" 
                            id="login_password"
                            class="form-control" 
                            placeholder="Enter your password"
                            required
                        >

                        <button 
                            type="button" 
                            class="toggle-password" 
                            onclick="togglePassword('login_password', this)"
                            aria-label="Show or hide password"
                        >
                            <i class="bi bi-eye-fill"></i>
                        </button>
                    </div>
                </div>

                <div class="mb-3 form-check">
                    <input 
                        type="checkbox" 
                        class="form-check-input" 
                        name="remember" 
                        id="remember"
                    >

                    <label class="form-check-label remember-text" for="remember">
                        Remember Me
                    </label>
                </div>

                <button type="submit" class="btn-login">
                    Login
                </button>

            </form>

            <div class="text-center mt-4">

                <p class="mb-2 create-account-text">
                    Don't have an account?
                </p>

                <a href="register.php" class="btn create-account-btn w-100 rounded-3 py-2 fw-semibold">
                    <i class="bi bi-person-plus-fill me-2"></i>
                    Create Customer Account
                </a>

            </div>

        </div>

    </div>

</div>

<script>
function togglePassword(inputId, button) {
    const input = document.getElementById(inputId);
    const icon = button.querySelector('i');

    if (input.type === 'password') {
        input.type = 'text';
        icon.classList.remove('bi-eye-fill');
        icon.classList.add('bi-eye-slash-fill');
    } else {
        input.type = 'password';
        icon.classList.remove('bi-eye-slash-fill');
        icon.classList.add('bi-eye-fill');
    }
}
</script>

</body>
</html>