<?php
require_once('config.php');

echo "Starting final enrollment migration...<br>";

try {
    // Drop old appeal columns if they exist and add proper status system
    $stmt = $pdo->query("DESCRIBE enrollments");
    $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    $columns_to_drop = ['appeal_status', 'appeal_requested_at', 'appeal_reason'];
    foreach ($columns_to_drop as $col) {
        if (in_array($col, $columns)) {
            $sql = "ALTER TABLE enrollments DROP COLUMN $col";
            $pdo->exec($sql);
            echo "✓ Dropped old column: $col<br>";
        }
    }

    // Add status and drop_deadline columns
    if (!in_array('status', $columns)) {
        $sql = "ALTER TABLE enrollments 
                ADD COLUMN status ENUM('enrolled', 'dropped', 'appeal_pending', 'appeal_approved', 'appeal_rejected') DEFAULT 'enrolled',
                ADD COLUMN drop_deadline TIMESTAMP NULL DEFAULT NULL,
                ADD COLUMN appeal_reason TEXT NULL DEFAULT NULL,
                ADD COLUMN appeal_requested_at TIMESTAMP NULL DEFAULT NULL,
                ADD COLUMN dropped_at TIMESTAMP NULL DEFAULT NULL";
        $pdo->exec($sql);
        echo "✓ Added new status and deadline columns to enrollments<br>";
    } else {
        echo "✓ Status columns already exist<br>";
    }

    // Update existing enrollments to set drop_deadline (4 days after enrolled_at)
    $sql = "UPDATE enrollments 
            SET drop_deadline = DATE_ADD(enrolled_at, INTERVAL 4 DAY) 
            WHERE drop_deadline IS NULL";
    $pdo->exec($sql);
    echo "✓ Updated existing enrollments with drop deadlines<br>";

    echo "<br><strong>Final enrollment migration completed successfully!</strong>";
    echo "<br><br>You can now delete this file.";

} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>