<?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"] ?? "";
    $file = $_FILES["csv_file"] ?? null;

    if (!$election_id || !$file || $file["error"] !== UPLOAD_ERR_OK) {
        die("Invalid submission or file upload error.");
    }

    $extension = pathinfo($file["name"], PATHINFO_EXTENSION);
    if (strtolower($extension) !== "csv") {
        die("Please upload a valid CSV file.");
    }

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

        $handle = fopen($file["tmp_name"], "r");
        if ($handle === false) {
            throw new Exception("Could not open the uploaded file.");
        }

        // Skip header if it exists
        $header = fgetcsv($handle);
        // Basic header validation (optional, but good)
        // Expected: student_id, name, email, track, grade_level

        $imported = 0;
        $updated = 0;

        while (($data = fgetcsv($handle)) !== false) {
            if (count($data) < 5) continue; // Skip malformed rows

            $student_id = trim($data[0]);
            $name = trim($data[1]);
            $email = trim($data[2]);
            $track = trim($data[3]);
            $grade_level = trim($data[4]);
            $section = trim($data[5] ?? "");

            if (!$student_id || !$name || !$email) continue;

            // 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]);
                $updated++;
            } else {
                // 1a. Create user in Supabase
                $supabaseUser = SupabaseAuth::createUser($email, "iloilohns");
                $supabase_uid = null;
                if ($supabaseUser['error']) {
                    if (str_contains(strtolower($supabaseUser['error']), 'already registered')) {
                        $sbUser = SupabaseAuth::getUserByEmail($email);
                        $supabase_uid = $sbUser['id'] ?? null;
                    } else {
                        // Log error but continue with other users? Or fail?
                        // Let's fail for now to be safe.
                        throw new Exception("Supabase Error for $email: " . $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]);
                $imported++;
            }

            // 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']]);
            }
        }

        fclose($handle);
        audit_log("Imported voters via CSV", "users", "multiple");
        
        $pdo->commit();
        header("Location: ../voter_management.php?success=import_complete&imported=$imported&updated=$updated");
        exit;
    } catch (Exception $e) {
        if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
        die("Error: " . $e->getMessage());
    }
}
