<?php
session_start();
require_once __DIR__ . '/../config/database.php';

// Simple protection: only admin can run
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] ?? '') !== 'admin') {
    echo "Access denied. Please login as admin.";
    exit();
}

$action = $_GET['action'] ?? '';

function backup_table($pdo, $table) {
    $date = date('Ymd_His');
    $backupTable = $table . '_backup_' . $date;
    $pdo->exec("CREATE TABLE `$backupTable` LIKE `$table`");
    $pdo->exec("INSERT INTO `$backupTable` SELECT * FROM `$table`");
    return $backupTable;
}

if ($action === 'run') {
    try {
        // Backup
        $backup = backup_table($pdo, 'class_subjects');

        // Alter
        $pdo->exec("ALTER TABLE class_subjects ADD COLUMN group_name VARCHAR(100) DEFAULT NULL");
        $pdo->exec("ALTER TABLE class_subjects ADD INDEX idx_class_group (class_id, group_name)");

        echo "Backup created: $backup<br>Column group_name added and index created.<br>";
        echo "<a href=\"add_group_column_class_subjects.php\">Back</a>";
    } catch (Exception $e) {
        echo "Error: " . htmlspecialchars($e->getMessage());
    }
    exit();
}

?>

<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>Migration - add group_name to class_subjects</title></head>
<body>
<h3>Migration: add group_name to class_subjects</h3>
<p>This script will:<ol><li>create a backup table</li><li>add <code>group_name</code> column</li><li>add index <code>idx_class_group</code></li></ol></p>
<p><strong>Only run once.</strong> Backup will be created automatically.</p>
<form method="get">
    <input type="hidden" name="action" value="run">
    <button type="submit">Run migration</button>
</form>
</body>
</html>