<?php
require_once '../auth_helper.php';
require_login();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
    $userId = $_POST['id'];
    $name = $_POST['name'];
    $studentId = $_POST['student_id'];
    $email = $_POST['email'];
    $track = $_POST['track'];
    $gradeLevel = $_POST['grade_level'];
    $section = $_POST['section'] ?? '';
    $password = $_POST['password'] ?? '';
    $pdo = db();

    try {
        $stmt = $pdo->prepare("SELECT email, supabase_uid FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $userRecord = $stmt->fetch();

        if (!empty($password)) {
            // Update Supabase password
            if ($userRecord && $userRecord['supabase_uid']) {
                SupabaseAuth::updateUserPassword($userRecord['supabase_uid'], $password);
            }
            
            $stmt = $pdo->prepare("UPDATE users SET name = ?, student_id = ?, email = ?, track = ?, grade_level = ?, section = ? WHERE id = ?");
            $stmt->execute([$name, $studentId, $email, $track, $gradeLevel, $section, $userId]);
        } else {
            $stmt = $pdo->prepare("UPDATE users SET name = ?, student_id = ?, email = ?, track = ?, grade_level = ?, section = ? WHERE id = ?");
            $stmt->execute([$name, $studentId, $email, $track, $gradeLevel, $section, $userId]);
        }

        // Log the action
        $currentUser = get_user();
        audit_log('voter_updated', 'users', $userId, null, null, "Updated voter ID $userId info");

        header("Location: ../voter_management.php?success=voter_updated");
        exit;
    } catch (PDOException $e) {
        die("Error updating voter: " . $e->getMessage());
    }
} else {
    header("Location: ../voter_management.php");
    exit;
}
