<?php
require_once 'auth_helper.php';

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $student_id = $_POST['student_id'] ?? '';
    $name = $_POST['name'] ?? '';
    $email = $_POST['email'] ?? '';
    $password = $_POST['password'] ?? '';
    $role = $_POST['role'] ?? 'Voter';
    
    // Simple validation
    if (!preg_match('/^\d{2}-\d{4}$/', $student_id)) {
        $error = 'Invalid Student ID format. Use XX-XXXX.';
    } else {
        try {
            // 1. Create user in Supabase
            $supabaseUser = SupabaseAuth::createUser($email, $password);
            $supabase_uid = null;
            if ($supabaseUser['error']) {
                if (str_contains(strtolower($supabaseUser['error']), 'already registered')) {
                    $sbUser = SupabaseAuth::getUserByEmail($email);
                    $supabase_uid = $sbUser['id'] ?? null;
                } else {
                    throw new Exception("Supabase Error: " . $supabaseUser['error']);
                }
            } else {
                $supabase_uid = $supabaseUser['data']['id'] ?? null;
            }

            $id = uuid();
            $stmt = db()->prepare("INSERT INTO users (id, supabase_uid, student_id, name, email, role) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$id, $supabase_uid, $student_id, $name, $email, $role]);
            
            $_SESSION['user_id'] = $id;
            $_SESSION['user_role'] = $role;
            audit_log('User registered', 'users', $id);
            header('Location: index.php');
            exit;
        } catch (PDOException $e) {
            if ($e->getCode() == 23000) {
                $error = 'Student ID or Email already exists.';
            } else {
                $error = 'An error occurred: ' . $e->getMessage();
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Signup - 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; }
        .signup-card { max-width: 500px; margin: 50px auto; border-radius: 8px; box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1); }
    </style>
</head>
<body>
    <div class="card signup-card p-4">
        <h2 class="text-center mb-4" style="color: #1e293b;">Voter Registration</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">Full Name</label>
                <input type="text" name="name" class="form-control" required>
            </div>
            <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 Address</label>
                <input type="email" name="email" class="form-control" required>
            </div>
            <div class="mb-3">
                <label class="form-label">Password</label>
                <input type="password" name="password" 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>
            <button type="submit" class="btn btn-primary w-100" style="background-color: #2563eb;">Register</button>
        </form>
        <div class="mt-3 text-center">
            <small>Already have an account? <a href="login.php">Login</a></small>
        </div>
    </div>
</body>
</html>
