<?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']) && str_contains($_SERVER['HTTP_REFERER'] ?? '', 'index.php')) { 
        // Only redirect back if we actually came from landing page modal
        header('Location: index.php?error=' . urlencode($error));
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - Iloilo National High School</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/landing.css?v=<?= time() ?>">
    <style>
        .login-page-container {
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 2;
            position: relative;
        }
    </style>
</head>
<body class="landing-page" style="background-image: url('assets/images/background.jpg?v=<?= filemtime('assets/images/background.jpg') ?>');">
    <div class="login-page-container">
        <div class="login-modal" style="display: block; position: static; animation: none;">
            <div class="modal-header">
                <div class="modal-header-content">
                    <div class="header-icon">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>
                    </div>
                    <h2>Election Login</h2>
                </div>
            </div>
            <div class="modal-body">
                <?php if ($error): ?>
                    <div style="background: #fee2e2; color: #b91c1c; padding: 0.75rem; border-radius: 10px; margin-bottom: 1.5rem; font-size: 0.85rem; border: 1px solid #fecaca; text-align: center;">
                        <?= htmlspecialchars($error) ?>
                    </div>
                <?php endif; ?>
                <form method="POST">
                    <div class="form-group">
                        <label>User Type</label>
                        <div class="input-container">
                            <i>
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>
                            </i>
                            <select name="role">
                                <option value="Voter">Voter</option>
                                <option value="Officer">Officer</option>
                                <option value="Adviser">Adviser</option>
                                <option value="Admin">Admin</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>UID</label>
                        <div class="input-container">
                            <i>
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="16" rx="2"></rect><line x1="7" y1="8" x2="17" y2="8"></line><line x1="7" y1="12" x2="17" y2="12"></line><line x1="7" y1="16" x2="12" y2="16"></line></svg>
                            </i>
                            <input type="text" name="student_id" placeholder="00-0000" required pattern="\d{2}-\d{4}">
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Email Account</label>
                        <div class="input-container">
                            <i>
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"></path><polyline points="22,6 12,13 2,6"></polyline></svg>
                            </i>
                            <input type="email" name="email" placeholder="firstname.lastname@iloilonhs.edu.ph" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Password</label>
                        <div class="input-container">
                            <i>
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>
                            </i>
                            <input type="password" id="passwordInput" name="password" placeholder="Enter your password" required>
                            <i class="password-toggle" onclick="togglePassword()">
                                <svg id="eyeIcon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
                            </i>
                        </div>
                    </div>

                    <button type="submit" class="modal-btn-login">
                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"></path><polyline points="10 17 15 12 10 7"></polyline><line x1="15" y1="12" x2="3" y2="12"></line></svg>
                        LOGIN
                    </button>
                </form>
                <div class="text-center mt-3">
                    <small style="color: var(--landing-text-muted); font-size: 0.8rem;">Don't have an account? <a href="signup.php" style="color: var(--landing-primary); font-weight: 600; text-decoration: none;">Register here</a></small>
                </div>
            </div>
        </div>
    </div>

    <script>
        function togglePassword() {
            const input = document.getElementById('passwordInput');
            const icon = document.getElementById('eyeIcon');
            if (input.type === 'password') {
                input.type = 'text';
                icon.innerHTML = '<path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path><line x1="1" y1="1" x2="23" y2="23"></line>';
            } else {
                input.type = 'password';
                icon.innerHTML = '<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle>';
            }
        }
    </script>
</body>
</html>
