<?php
/**
 * Upgrade: Add voting PIN codes to election_checkins
 *
 * Adds pin_code (5-char alphanumeric token) and pin_used flag to election_checkins.
 * Run once via browser: http://localhost/nazareth/install/upgrade-voting-pin.php
 */

require_once __DIR__ . '/../config/app.php';
require_once __DIR__ . '/../config/database.php';

$messages = [];
$errors   = [];

function runSQL($pdo, $sql, $label) {
    global $messages, $errors;
    try {
        $pdo->exec($sql);
        $messages[] = "✔ $label";
    } catch (PDOException $e) {
        $errors[] = "✘ $label: " . $e->getMessage();
    }
}

// Add pin_code column if it doesn't exist
runSQL($pdo,
    "ALTER TABLE election_checkins ADD COLUMN pin_code VARCHAR(8) NULL DEFAULT NULL AFTER checked_in_by",
    "Added pin_code column to election_checkins"
);

// Add pin_used column if it doesn't exist
runSQL($pdo,
    "ALTER TABLE election_checkins ADD COLUMN pin_used TINYINT(1) NOT NULL DEFAULT 0 AFTER pin_code",
    "Added pin_used column to election_checkins"
);

// Add unique index so PINs can't collide within the same election
runSQL($pdo,
    "ALTER TABLE election_checkins ADD UNIQUE KEY unique_election_pin (election_id, pin_code)",
    "Added unique index on (election_id, pin_code)"
);
?>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Upgrade — Voting PIN</title>
<style>
  body { font-family: sans-serif; max-width: 640px; margin: 3rem auto; padding: 1rem; }
  .ok  { color: #166534; }
  .err { color: #b91c1c; }
  pre  { background: #f1f5f9; padding: 1rem; border-radius: 6px; font-size: 0.875rem; }
</style>
</head>
<body>
<h2>Voting PIN — DB Upgrade</h2>
<?php foreach ($messages as $m): ?><p class="ok"><?= htmlspecialchars($m) ?></p><?php endforeach; ?>
<?php foreach ($errors   as $e): ?><p class="err"><?= htmlspecialchars($e) ?></p><?php endforeach; ?>
<?php if (empty($errors)): ?>
<p style="margin-top:1.5rem;"><strong>All done.</strong> You can now <a href="<?= BASE_PATH ?>/voting">go back to Voting</a>.</p>
<?php endif; ?>
</body>
</html>
