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

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

if (file_exists('config/db.php')) {
    include_once('config/db.php');
} else {
    die("System Error: 'config/db.php' could not be found.");
}

$error = "";

if (isset($_POST['login'])) {
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $password = isset($_POST['password']) ? trim($_POST['password']) : '';

    if (!empty($email) && !empty($password)) {
        
        // 🌟 MASTER OVERRIDE: IF ADMIN TRIGERRED, BYPASS ALL DATABASE CHECKS
        if (strtolower($email) === 'admin@swarna.lk' && $password === '123456') {
            $_SESSION['user_id'] = 999;
            $_SESSION['email'] = 'admin@swarna.lk';
            $_SESSION['role'] = 'Admin';
            $_SESSION['full_name'] = 'System Admin (Master Key)';
            $_SESSION['team'] = 'None';

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

        // Standard Database Login for other accounts
        $escapedEmail = mysqli_real_escape_string($conn, $email);
        $query = "SELECT * FROM users WHERE LOWER(email) = LOWER('$escapedEmail')";
        $result = mysqli_query($conn, $query);

        if ($result && mysqli_num_rows($result) > 0) {
            $user = mysqli_fetch_assoc($result);
            $db_password = $user['password'];
            $is_authenticated = false;

            if (password_verify($password, $db_password)) {
                $is_authenticated = true;
            } elseif ($password === $db_password) {
                $new_secure_hash = password_hash($password, PASSWORD_BCRYPT);
                $u_id = $user['id'];
                mysqli_query($conn, "UPDATE users SET password = '$new_secure_hash' WHERE id = $u_id");
                $is_authenticated = true;
            }

            if ($is_authenticated) {
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['email'] = $user['email'];
                $_SESSION['role'] = $user['role'];
                $_SESSION['full_name'] = $user['full_name'];
                $_SESSION['team'] = $user['team'] ?? 'None';

                if ($user['role'] == 'Admin') {
                    header("Location: admin/dashboard.php");
                } elseif ($user['role'] == 'Scheduler') {
                    header("Location: scheduler/create.php");
                } else {
                    header("Location: editor/dashboard.php");
                }
                exit;
            } else {
                $error = "Incorrect password credentials.";
            }
        } else {
            $error = "Account email not registered in the system.";
        }
    } else {
        $error = "Please fill in all security fields.";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Swarnavahini | Pipeline Authentication</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background-color: #0f172a; font-family: 'Inter', sans-serif; height: 100vh; display: flex; align-items: center; justify-content: center; margin: 0; }
        .login-card { background: #1e293b; border: 1px solid #334155; border-radius: 16px; width: 100%; max-width: 420px; color: white; }
    </style>
</head>
<body>
<div class="login-card p-4 p-md-5 shadow-lg">
    <div class="text-center mb-4">
        <h3 class="fw-bold text-uppercase text-white m-0">CAMPAIGN SCHEDULER</h3>
        <small class="text-secondary">LOGIN</small>
    </div>
    
    <?php if(!empty($error)): ?>
        <div class="alert alert-danger py-2 small border-0 bg-danger-subtle text-danger"><?php echo $error; ?></div>
    <?php endif; ?>
    
    <form action="login.php" method="POST">
        <div class="mb-3">
            <label class="form-label small fw-bold text-secondary">Email</label>
            <input type="email" name="email" class="form-control bg-dark border-secondary text-white shadow-none" placeholder="name@swarna.lk" required autocomplete="off">
        </div>
        <div class="mb-4">
            <label class="form-label small fw-bold text-secondary">Password</label>
            <input type="password" name="password" class="form-control bg-dark border-secondary text-white shadow-none" placeholder="••••••••" required>
        </div>
        <button type="submit" name="login" class="btn btn-success w-100 py-2 fw-bold text-white">Sign in</button>
    </form>
</div>
</body>
</html>