<?php
declare(strict_types=1);
require_once __DIR__ . "/../auth_helper.php";
require_login();
require_role(["Admin", "Adviser", "Officer"]);

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $election_id = $_POST["election_id"] ?? "";
    $student_id = $_POST["student_id"] ?? "";
    $name = $_POST["name"] ?? "";
    $email = $_POST["email"] ?? "";
    $password = $_POST["password"] ?? "iloilohns";
    $track = $_POST["track"] ?? "";
    $grade_level = $_POST["grade_level"] ?? "";
    $section = $_POST["section"] ?? "";

    if (!$election_id || !$student_id || !$name || !$email) {
        die("Missing fields");
    }

    try {
        $pdo = db();
        $pdo->beginTransaction();

        // 1. Check if user already exists
        $stmt = $pdo->prepare("SELECT id FROM users WHERE student_id = ? OR email = ?");
        $stmt->execute([$student_id, $email]);
        $existing = $stmt->fetch();

        if ($existing) {
            $user_id = $existing["id"];
            // Update track/grade/section if needed
            $upd = $pdo->prepare("UPDATE users SET track = ?, grade_level = ?, section = ? WHERE id = ?");
            $upd->execute([$track, $grade_level, $section, $user_id]);
        } else {
            // 1a. Create user in Supabase
            $supabaseUser = SupabaseAuth::createUser($email, $password);
            $supabase_uid = null;
            if ($supabaseUser['error']) {
                // If user already exists in Supabase, try to get their UID
                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;
            }

            // Create new user locally
            $user_id = uuid();
            $stmt = $pdo->prepare("INSERT INTO users (id, supabase_uid, student_id, name, email, track, grade_level, section, role) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'Voter')");
            $stmt->execute([$user_id, $supabase_uid, $student_id, $name, $email, $track, $grade_level, $section]);
        }

        // 2. Assign to election
        $chk = $pdo->prepare("SELECT COUNT(*) FROM election_assignments WHERE election_id = ? AND user_id = ?");
        $chk->execute([$election_id, $user_id]);
        if ($chk->fetchColumn() == 0) {
            $ea = $pdo->prepare("INSERT INTO election_assignments (id, election_id, user_id, role_in_election, assigned_by) VALUES (?, ?, ?, 'Voter', ?)");
            $ea->execute([uuid(), $election_id, $user_id, $_SESSION['user_id']]);
        }

        audit_log("Registered voter", "users", $user_id);
        
        $pdo->commit();
        header("Location: ../voter_management.php?success=voter_added");
        exit;
    } catch (Exception $e) {
        if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
        die("Error: " . $e->getMessage());
    }
}
