<?php
require_once __DIR__ . '/config.php';

function generate_uuid() {
    return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand(0, 0xffff), mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0x0fff) | 0x4000,
        mt_rand(0, 0x3fff) | 0x8000,
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );
}

$pdo = db();
$driver = $pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
echo "Connected using driver: $driver\n";

try {
    $pdo->beginTransaction();

    echo "Clearing existing data (preserving Admin)...\n";
    
    // Order matters for foreign keys
    $pdo->exec("DELETE FROM audit_logs");
    $pdo->exec("DELETE FROM votes");
    $pdo->exec("DELETE FROM candidates");
    $pdo->exec("DELETE FROM positions");
    $pdo->exec("DELETE FROM election_assignments");
    $pdo->exec("DELETE FROM elections");
    $pdo->exec("DELETE FROM users WHERE role != 'Admin'");

    // Ensure admin exists
    $admin = $pdo->query("SELECT id FROM users WHERE role = 'Admin' LIMIT 1")->fetch();
    if (!$admin) {
        $adminId = generate_uuid();
        $stmt = $pdo->prepare("INSERT INTO users (id, student_id, name, email, password_hash, role, access_level) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$adminId, '00-0000', 'Admin User', 'Admin@iloilonhs.edu.ph', password_hash('Testing', PASSWORD_DEFAULT), 'Admin', 4]);
        echo "Created default admin.\n";
    } else {
        $adminId = $admin['id'];
        echo "Preserved existing admin: " . $adminId . "\n";
    }

    echo "Adding mock elections and positions...\n";
    $electionId = generate_uuid();
    $stmt = $pdo->prepare("INSERT INTO elections (id, title, description, status, start_date_and_time, end_date_and_time, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $electionId, 
        'SSG General Elections 2026', 
        'Annual election for Supreme Student Government.', 
        'Ongoing', 
        date('Y-m-d H:i:s', strtotime('-1 day')), 
        date('Y-m-d H:i:s', strtotime('+7 days')), 
        $adminId
    ]);

    $positions = [
        ['President', 1, 1],
        ['Vice President', 1, 2],
        ['Secretary', 1, 3],
        ['Treasurer', 1, 4]
    ];
    $posIds = [];
    $stmt = $pdo->prepare("INSERT INTO positions (id, election_id, name, max_votes, sort_order) VALUES (?, ?, ?, ?, ?)");
    foreach ($positions as $p) {
        $id = generate_uuid();
        $stmt->execute([$id, $electionId, $p[0], $p[1], $p[2]]);
        $posIds[$p[0]] = $id;
    }

    echo "Adding mock students (voters)...\n";
    $tracks = ['STEM', 'ABM', 'HUMSS', 'GAS', 'TVL'];
    $sections = ['A', 'B', 'C', 'D'];
    $voters = [];
    $stmt = $pdo->prepare("INSERT INTO users (id, student_id, name, email, password_hash, grade_level, track, section, role) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $assignStmt = $pdo->prepare("INSERT INTO election_assignments (id, election_id, user_id, role_in_election, assigned_by) VALUES (?, ?, ?, ?, ?)");

    for ($i = 1; $i <= 40; $i++) {
        $id = generate_uuid();
        $studentId = sprintf('26-%04d', $i);
        $track = $tracks[array_rand($tracks)];
        $grade = rand(11, 12);
        $section = $sections[array_rand($sections)];
        
        $stmt->execute([
            $id, 
            $studentId, 
            "Student $i", 
            "student$i@iloilonhs.edu.ph", 
            password_hash('password', PASSWORD_DEFAULT), 
            $grade, 
            $track, 
            $section, 
            'Voter'
        ]);
        
        $assignStmt->execute([generate_uuid(), $electionId, $id, 'Voter', $adminId]);
        $voters[] = ['id' => $id, 'grade' => $grade, 'track' => $track];
    }

    echo "Adding candidates...\n";
    $candidateIds = [];
    foreach ($posIds as $posName => $posId) {
        for ($c = 1; $c <= 2; $c++) {
            $voter = array_shift($voters);
            $userId = $voter['id'];
            $candId = generate_uuid();
            
            $candStmt = $pdo->prepare("INSERT INTO candidates (id, election_id, position_id, user_id, party_name, approved) VALUES (?, ?, ?, ?, ?, ?)");
            $candStmt->execute([$candId, $electionId, $posId, $userId, ($c == 1 ? 'Alpha Party' : 'Beta Party'), true]);
            $candidateIds[$posId][] = $candId;

            $updStmt = $pdo->prepare("UPDATE election_assignments SET role_in_election = 'Candidate' WHERE election_id = ? AND user_id = ?");
            $updStmt->execute([$electionId, $userId]);
        }
    }

    echo "Generating mock votes...\n";
    $voteStmt = $pdo->prepare("INSERT INTO votes (id, election_id, position_id, candidate_id, voter_id) VALUES (?, ?, ?, ?, ?)");
    foreach ($voters as $v) {
        // 85% turnout
        if (rand(1, 100) <= 85) {
            foreach ($posIds as $posId) {
                $candId = $candidateIds[$posId][array_rand($candidateIds[$posId])];
                $voteStmt->execute([generate_uuid(), $electionId, $posId, $candId, $v['id']]);
            }
        }
    }

    $pdo->commit();
    echo "Done! Mock data successfully generated.\n";

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    echo "FATAL ERROR: " . $e->getMessage() . "\n";
    exit(1);
}
