<?php
require_once 'auth_helper.php';

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $student_id = $_POST['student_id'] ?? '';
    $email = $_POST['email'] ?? '';
    $role = $_POST['role'] ?? '';
    $password = $_POST['password'] ?? '';
    
    // 1. Find user locally to verify student_id, email and role match
    $stmt = db()->prepare("SELECT * FROM users WHERE student_id = ? AND email = ? AND role = ?");
    $stmt->execute([$student_id, $email, $role]);
    $user = $stmt->fetch();
    
    if ($user) {
        // 2. Authenticate with Supabase
        $auth = SupabaseAuth::signIn($email, $password);
        
        if ($auth['error']) {
            // Check if user exists locally with this password but not in Supabase yet
            if (!empty($user['password_hash']) && password_verify($password, $user['password_hash'])) {
                // Migrate to Supabase
                $supabaseUser = SupabaseAuth::createUser($email, $password);
                if (!$supabaseUser['error']) {
                    $auth = SupabaseAuth::signIn($email, $password);
                }
            }
        }

        if (!$auth['error']) {
            // Update supabase_uid if missing
            if (empty($user['supabase_uid'])) {
                $supabase_uid = $auth['data']['user']['id'] ?? null;
                $upd = db()->prepare("UPDATE users SET supabase_uid = ? WHERE id = ?");
                $upd->execute([$supabase_uid, $user['id']]);
            }

            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_role'] = $user['role'];
            header('Location: index.php');
            exit;
        } else {
            $error = 'Authentication failed: ' . $auth['error'];
        }
    } else {
        $error = 'Invalid Credentials. Please check your UID, Email, and Role.';
    }

    if ($error && isset($_POST['role'])) { // Redirect back to landing if coming from modal
        header('Location: index.php?error=' . urlencode($error));
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login - Online Election System</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background-color: #f8fafc; font-family: 'Inter', sans-serif; }
        .login-card { max-width: 400px; margin: 100px auto; border-radius: 8px; box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1); }
    </style>
</head>
<body>
    <div class="card login-card p-4">
        <h2 class="text-center mb-4" style="color: #1e293b;">Election Login</h2>
        <?php if ($error): ?>
            <div class="alert alert-danger"><?php echo $error; ?></div>
        <?php endif; ?>
        <form method="POST">
            <div class="mb-3">
                <label class="form-label">Student ID (XX-XXXX)</label>
                <input type="text" name="student_id" class="form-control" placeholder="00-0000" required pattern="\d{2}-\d{4}">
            </div>
            <div class="mb-3">
                <label class="form-label">Email Account</label>
                <input type="email" name="email" class="form-control" required>
            </div>
            <div class="mb-3">
                <label class="form-label">Role</label>
                <select name="role" class="form-select">
                    <option value="Voter">Voter</option>
                    <option value="Officer">Officer</option>
                    <option value="Adviser">Adviser</option>
                    <option value="Admin">Admin</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">Password</label>
                <input type="password" name="password" class="form-control" required>
            </div>
            <button type="submit" class="btn btn-primary w-100" style="background-color: #2563eb;">Login</button>
        </form>
        <div class="mt-3 text-center">
            <small>Don't have an account? <a href="signup.php">Register</a></small>
        </div>
    </div>
</body>
</html>
