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

echo "Starting course change request migration...<br>";

try {
    $stmt = $pdo->query("DESCRIBE enrollments");
    $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);

    if (!in_array('status', $columns)) {
        $pdo->exec("
            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
        ");
        echo "Added enrollment status fields.<br>";
    }

    $pdo->exec("
        UPDATE enrollments
        SET drop_deadline = DATE_ADD(enrolled_at, INTERVAL 4 DAY)
        WHERE drop_deadline IS NULL
    ");
    echo "Synced missing drop deadlines.<br>";

    $pdo->exec("
        CREATE TABLE IF NOT EXISTS course_change_requests (
            id INT AUTO_INCREMENT PRIMARY KEY,
            enrollment_id INT NOT NULL,
            student_id INT NOT NULL,
            current_course_id INT NOT NULL,
            requested_course_id INT NOT NULL,
            reason TEXT NOT NULL,
            status ENUM('pending', 'approved', 'rejected') DEFAULT 'pending',
            reviewed_by INT NULL,
            reviewed_at TIMESTAMP NULL DEFAULT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (enrollment_id) REFERENCES enrollments(id) ON DELETE CASCADE,
            FOREIGN KEY (student_id) REFERENCES users(id) ON DELETE CASCADE,
            FOREIGN KEY (current_course_id) REFERENCES courses(id) ON DELETE CASCADE,
            FOREIGN KEY (requested_course_id) REFERENCES courses(id) ON DELETE CASCADE,
            FOREIGN KEY (reviewed_by) REFERENCES users(id) ON DELETE SET NULL
        )
    ");
    echo "Course change requests table is ready.<br>";

    echo "<br><strong>Migration completed successfully.</strong>";
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>
