<?php
/**
 * One-time script to standardize roll numbers in the database
 */
define('IBVTE_ACCESS', true);
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/db.php';

// Check if we are on live server or local
$serverHost = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? '';
$isLocalhost = php_sapi_name() === 'cli' || in_array($serverHost, ['localhost', '127.0.0.1']);

echo "<h3>Standardizing Database Records</h3>";
echo "Environment: " . (ENVIRONMENT) . "<br>";

$db = DB();

try {
    $students = $db->fetchAll("SELECT id, roll_number, full_name FROM students");
    $updatedCount = 0;

    echo "<div style='font-family: monospace; font-size: 13px; line-height: 1.5;'>";
    foreach ($students as $s) {
        $oldRoll = $s['roll_number'];
        
        // 1. Remove non-numeric characters (like R-)
        $newRoll = preg_replace('/[^0-9]/', '', $oldRoll);
        
        // 2. Pad to 10 digits
        if (!empty($newRoll)) {
            $newRoll = str_pad($newRoll, 10, '0', STR_PAD_LEFT);
        } else {
            // If it was empty or just text, we might need a fallback, but usually we just keep it or skip
            continue;
        }
        
        if ($oldRoll !== $newRoll) {
            $db->update('students', ['roll_number' => $newRoll], ['id' => $s['id']]);
            echo "✅ Updated {$s['full_name']}: <span style='color:red;'>$oldRoll</span> → <span style='color:green;'>$newRoll</span><br>";
            $updatedCount++;
        }
    }
    echo "</div>";

    echo "<h4>Update Complete! Standardized $updatedCount records.</h4>";
    
    // --- TESTING DATA SETUP ---
    echo "<h3>Setting up test data...</h3>";
    // 1. Ensure Vijay Kumar (0026448251) has Paid status and an Admit Card
    $db->query("UPDATE students SET payment_status = 'paid' WHERE roll_number = '0026448251'");
    $vijay = $db->fetchOne("SELECT id FROM students WHERE roll_number = '0026448251'");
    if ($vijay) {
        $db->query("INSERT IGNORE INTO admit_cards (student_id, admit_card_number, exam_session, exam_type, exam_centre, generated_at) 
                    VALUES (?, 'AC0026448251', '2023-24', 'annual', 'IBVTE MAIN CAMPUS', NOW())", [$vijay['id']]);
        echo "✅ Setup Vijay Kumar (Admit Card & Paid Status)<br>";
    }
    // --------------------------
    
    // Security: Only delete if not on localhost
    if (!$isLocalhost) {
        echo "<p style='color:orange;'>Deleting this script for security...</p>";
        unlink(__FILE__);
    }

} catch (Exception $e) {
    echo "<p style='color:red;'>Error: " . $e->getMessage() . "</p>";
}
?>
