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

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'student') {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];

function studentHasActiveEnrollment($pdo, $student_id) {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM enrollments WHERE student_id = ? AND status IN ('enrolled', 'appeal_pending')");
    $stmt->execute([$student_id]);
    return $stmt->fetchColumn() > 0;
}

function reactivateEnrollment($pdo, $student_id, $course_id) {
    $stmt = $pdo->prepare("
        INSERT INTO enrollments (student_id, course_id, status, progress, enrolled_at, drop_deadline, appeal_reason, appeal_requested_at, dropped_at)
        VALUES (?, ?, 'enrolled', 0, NOW(), DATE_ADD(NOW(), INTERVAL 4 DAY), NULL, NULL, NULL)
        ON DUPLICATE KEY UPDATE
            status = 'enrolled',
            progress = 0,
            enrolled_at = NOW(),
            drop_deadline = DATE_ADD(NOW(), INTERVAL 4 DAY),
            appeal_reason = NULL,
            appeal_requested_at = NULL,
            dropped_at = NULL
    ");
    $stmt->execute([$student_id, $course_id]);
}

if (isset($_POST['unenroll']) && isset($_POST['enrollment_id'])) {
    $enrollment_id = (int) $_POST['enrollment_id'];

    $stmt = $pdo->prepare("SELECT drop_deadline FROM enrollments WHERE id = ? AND student_id = ? AND status = 'enrolled'");
    $stmt->execute([$enrollment_id, $user_id]);
    $enrollment = $stmt->fetch();

    if ($enrollment) {
        $drop_deadline = new DateTime($enrollment['drop_deadline']);
        $current_date = new DateTime();

        if ($current_date <= $drop_deadline) {
            $stmt = $pdo->prepare("UPDATE enrollments SET status = 'dropped', dropped_at = NOW() WHERE id = ? AND student_id = ?");
            $stmt->execute([$enrollment_id, $user_id]);
            header("Location: my_learning.php?success=dropped");
            exit();
        }
    }
}

if (isset($_POST['reenroll']) && isset($_POST['course_id'])) {
    $course_id = (int) $_POST['course_id'];

    if (studentHasActiveEnrollment($pdo, $user_id)) {
        header("Location: my_learning.php?error=active_enrollment");
        exit();
    }

    reactivateEnrollment($pdo, $user_id, $course_id);
    header("Location: my_learning.php?success=reenrolled");
    exit();
}

if (isset($_POST['request_change'], $_POST['enrollment_id'], $_POST['requested_course_id'], $_POST['reason'])) {
    $enrollment_id = (int) $_POST['enrollment_id'];
    $requested_course_id = (int) $_POST['requested_course_id'];
    $reason = trim($_POST['reason']);

    $stmt = $pdo->prepare("
        SELECT id, course_id, status, drop_deadline
        FROM enrollments
        WHERE id = ? AND student_id = ? AND status = 'enrolled'
    ");
    $stmt->execute([$enrollment_id, $user_id]);
    $enrollment = $stmt->fetch(PDO::FETCH_ASSOC);

    $stmt = $pdo->prepare("SELECT id FROM courses WHERE id = ?");
    $stmt->execute([$requested_course_id]);
    $requested_course_exists = $stmt->fetchColumn();

    if (!$enrollment || !$requested_course_exists || $requested_course_id == $enrollment['course_id'] || $reason === '') {
        header("Location: my_learning.php?error=change_invalid");
        exit();
    }

    $stmt = $pdo->prepare("SELECT COUNT(*) FROM course_change_requests WHERE enrollment_id = ? AND status = 'pending'");
    $stmt->execute([$enrollment_id]);
    if ($stmt->fetchColumn() > 0) {
        header("Location: my_learning.php?error=change_pending");
        exit();
    }

    $drop_deadline = new DateTime($enrollment['drop_deadline']);
    $current_date = new DateTime();

    if ($current_date <= $drop_deadline) {
        $pdo->beginTransaction();
        try {
            $stmt = $pdo->prepare("UPDATE enrollments SET status = 'dropped', dropped_at = NOW() WHERE id = ? AND student_id = ?");
            $stmt->execute([$enrollment_id, $user_id]);

            reactivateEnrollment($pdo, $user_id, $requested_course_id);
            $pdo->commit();

            header("Location: my_learning.php?success=changed");
            exit();
        } catch (Throwable $e) {
            $pdo->rollBack();
            header("Location: my_learning.php?error=change_failed");
            exit();
        }
    }

    $stmt = $pdo->prepare("
        INSERT INTO course_change_requests (enrollment_id, student_id, current_course_id, requested_course_id, reason)
        VALUES (?, ?, ?, ?, ?)
    ");
    $stmt->execute([$enrollment_id, $user_id, $enrollment['course_id'], $requested_course_id, $reason]);

    header("Location: my_learning.php?success=change_requested");
    exit();
}

include('../header/header.php');

$success_msg = '';
$error_msg = '';

if (isset($_GET['success'])) {
    $messages = [
        'dropped' => 'Successfully dropped the course.',
        'changed' => 'Course changed successfully. Your new course is ready.',
        'reenrolled' => 'You have re-enrolled successfully.',
        'change_requested' => 'Course change request submitted. We will review it shortly.'
    ];
    $success_msg = $messages[$_GET['success']] ?? '';
}

if (isset($_GET['error'])) {
    $messages = [
        'active_enrollment' => 'You already have an active course. Drop or change it before re-enrolling.',
        'change_invalid' => 'Please choose a different course and include a reason.',
        'change_pending' => 'You already have a pending request for this course.',
        'change_failed' => 'We could not complete the course change. Please try again.'
    ];
    $error_msg = $messages[$_GET['error']] ?? '';
}

$stmt = $pdo->prepare("
    SELECT c.*, e.id as enrollment_id, e.status, e.enrolled_at, e.drop_deadline, e.appeal_reason, e.appeal_requested_at, e.dropped_at, e.progress
    FROM courses c
    JOIN enrollments e ON c.id = e.course_id
    WHERE e.student_id = ?
    ORDER BY e.enrolled_at DESC
");
$stmt->execute([$user_id]);
$enrolled_courses = $stmt->fetchAll(PDO::FETCH_ASSOC);

$stmt = $pdo->query("SELECT id, course_name, category FROM courses ORDER BY course_name ASC");
$available_courses = $stmt->fetchAll(PDO::FETCH_ASSOC);

$stmt = $pdo->prepare("
    SELECT r.*, rc.course_name as requested_course_name
    FROM course_change_requests r
    JOIN courses rc ON r.requested_course_id = rc.id
    WHERE r.student_id = ?
    ORDER BY r.created_at DESC
");
$stmt->execute([$user_id]);
$requests = $stmt->fetchAll(PDO::FETCH_ASSOC);
$requests_by_enrollment = [];
foreach ($requests as $request) {
    if (!isset($requests_by_enrollment[$request['enrollment_id']])) {
        $requests_by_enrollment[$request['enrollment_id']] = $request;
    }
}

$has_active_enrollment = studentHasActiveEnrollment($pdo, $user_id);
?>

<div class="container py-5 learning-shell">
    <div class="learning-hero mb-4">
        <div>
            <p class="text-uppercase text-muted fw-semibold small mb-1">Student learning</p>
            <h2 class="fw-bold mb-1">My Learning</h2>
            <p class="text-muted mb-0">Manage your current course, switch while eligible, or request approval when the deadline has passed.</p>
        </div>
        <a href="courses.php" class="btn btn-primary"><i class="fas fa-search me-2"></i>Browse Courses</a>
    </div>

    <?php if ($success_msg): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i><?php echo $success_msg; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if ($error_msg): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-circle me-2"></i><?php echo $error_msg; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if (empty($enrolled_courses)): ?>
        <div class="empty-learning text-center py-5">
            <i class="fas fa-book-open fa-3x text-muted mb-3"></i>
            <h4 class="text-muted">No courses enrolled yet</h4>
            <p class="text-muted mb-4">Browse courses and enroll in one to get started.</p>
            <a href="courses.php" class="btn btn-primary"><i class="fas fa-search me-2"></i>Browse Courses</a>
        </div>
    <?php else: ?>
        <div class="row g-4">
            <?php foreach ($enrolled_courses as $course): ?>
                <?php
                $request = $requests_by_enrollment[$course['enrollment_id']] ?? null;
                $pending_request = $request && $request['status'] == 'pending';
                $status_badge = '';
                $can_unenroll = false;
                $can_change = false;
                $can_reenroll = false;
                $drop_deadline = null;

                if ($course['status'] == 'enrolled') {
                    $status_badge = '<span class="badge bg-success"><i class="fas fa-check me-1"></i>Enrolled</span>';
                    $drop_deadline = new DateTime($course['drop_deadline']);
                    $current_date = new DateTime();
                    $can_unenroll = ($current_date <= $drop_deadline) && !$pending_request;
                    $can_change = !$pending_request;
                } elseif ($course['status'] == 'dropped') {
                    $status_badge = '<span class="badge bg-secondary"><i class="fas fa-times me-1"></i>Dropped</span>';
                    $can_reenroll = !$has_active_enrollment;
                } elseif ($course['status'] == 'appeal_pending') {
                    $status_badge = '<span class="badge bg-warning text-dark"><i class="fas fa-clock me-1"></i>Appeal Pending</span>';
                } elseif ($course['status'] == 'appeal_approved') {
                    $status_badge = '<span class="badge bg-info text-dark"><i class="fas fa-unlock me-1"></i>Released</span>';
                    $can_reenroll = !$has_active_enrollment;
                } elseif ($course['status'] == 'appeal_rejected') {
                    $status_badge = '<span class="badge bg-danger"><i class="fas fa-times-circle me-1"></i>Appeal Rejected</span>';
                    $can_reenroll = !$has_active_enrollment;
                }
                ?>
                <div class="col-lg-6">
                    <div class="learning-card h-100">
                        <div class="d-flex justify-content-between align-items-start gap-3 mb-3">
                            <div>
                                <h4 class="fw-bold mb-1"><?php echo htmlspecialchars($course['course_name']); ?></h4>
                                <small class="text-muted">Enrolled: <?php echo date('M d, Y', strtotime($course['enrolled_at'])); ?></small>
                            </div>
                            <?php echo $status_badge; ?>
                        </div>

                        <p class="text-muted mb-3">
                            <?php echo htmlspecialchars(substr($course['description'], 0, 150)); ?>...
                        </p>

                        <?php if ($pending_request): ?>
                            <div class="request-strip mb-3">
                                <div class="request-icon"><i class="fas fa-arrows-alt-h"></i></div>
                                <div>
                                    <div class="fw-semibold">Change request pending</div>
                                    <small>Requested: <?php echo htmlspecialchars($request['requested_course_name']); ?></small>
                                </div>
                            </div>
                        <?php endif; ?>

                        <?php if ($course['status'] == 'enrolled'): ?>
                            <div class="mb-3">
                                <div class="d-flex justify-content-between small mb-1">
                                    <span>Progress</span>
                                    <span class="fw-semibold"><?php echo $course['progress']; ?>%</span>
                                </div>
                                <div class="progress">
                                    <div class="progress-bar bg-success" style="width: <?php echo $course['progress']; ?>%"></div>
                                </div>
                            </div>

                            <?php if ($drop_deadline): ?>
                                <div class="deadline-panel mb-3">
                                    <i class="fas fa-calendar-check"></i>
                                    <span>
                                        <?php if ($can_unenroll): ?>
                                            Drop or change instantly until <strong><?= $drop_deadline->format('M d, Y, H:i'); ?></strong>.
                                        <?php else: ?>
                                            Deadline passed. Course changes now require review.
                                        <?php endif; ?>
                                    </span>
                                </div>
                            <?php endif; ?>

                            <div class="learning-actions">
                                <a href="view_notes.php?enrollment_id=<?php echo $course['enrollment_id']; ?>" class="btn btn-primary">
                                    <i class="fas fa-book me-2"></i>View Notes
                                </a>
                                <a href="assignments.php?enrollment_id=<?php echo $course['enrollment_id']; ?>" class="btn btn-outline-secondary">
                                    <i class="fas fa-tasks me-2"></i>Assignments
                                </a>
                            </div>

                            <?php if (!$pending_request): ?>
                                <div class="learning-actions mt-2">
                                    <?php if ($can_unenroll): ?>
                                        <button type="button"
                                                class="btn btn-outline-danger flex-fill"
                                                data-bs-toggle="modal"
                                                data-bs-target="#dropModal-<?= $course['enrollment_id']; ?>">
                                            <i class="fas fa-trash me-2"></i>Drop
                                        </button>
                                    <?php endif; ?>
                                    <button type="button" class="btn btn-outline-warning flex-fill" data-bs-toggle="modal" data-bs-target="#changeModal-<?= $course['enrollment_id']; ?>">
                                        <i class="fas fa-random me-2"></i>Change Course
                                    </button>
                                </div>
                            <?php endif; ?>
                        <?php elseif ($can_reenroll): ?>
                            <form method="POST">
                                <input type="hidden" name="course_id" value="<?= $course['id']; ?>">
                                <button type="submit" name="reenroll" class="btn btn-primary w-100">
                                    <i class="fas fa-redo me-2"></i>Re-enroll
                                </button>
                            </form>
                        <?php elseif ($course['status'] != 'enrolled'): ?>
                            <div class="alert alert-light border mb-0">
                                <i class="fas fa-info-circle me-2"></i>
                                Enrollments reopen when you have no active course.
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <?php if ($can_change): ?>
                    <div class="modal fade" id="changeModal-<?= $course['enrollment_id']; ?>" tabindex="-1" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-centered">
                            <div class="modal-content">
                                <form method="POST">
                                    <div class="modal-header">
                                        <div>
                                            <h5 class="modal-title fw-bold">Change Course</h5>
                                            <small class="text-muted">Choose the course you want to move into.</small>
                                        </div>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                    </div>
                                    <div class="modal-body">
                                        <input type="hidden" name="enrollment_id" value="<?= $course['enrollment_id']; ?>">
                                        <label class="form-label fw-semibold">New course</label>
                                        <select name="requested_course_id" class="form-select mb-3" required>
                                            <option value="">Select course</option>
                                            <?php foreach ($available_courses as $available_course): ?>
                                                <?php if ($available_course['id'] != $course['id']): ?>
                                                    <option value="<?= $available_course['id']; ?>">
                                                        <?= htmlspecialchars($available_course['course_name']); ?>
                                                    </option>
                                                <?php endif; ?>
                                            <?php endforeach; ?>
                                        </select>
                                        <label class="form-label fw-semibold">Reason</label>
                                        <textarea name="reason" class="form-control" rows="4" placeholder="Briefly explain why this course is a better fit." required></textarea>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                                        <button type="submit" name="request_change" class="btn btn-warning">
                                            <i class="fas fa-paper-plane me-2"></i>Submit
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

                <?php if ($can_unenroll): ?>
                    <div class="modal fade" id="dropModal-<?= $course['enrollment_id']; ?>" tabindex="-1" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-centered">
                            <div class="modal-content">
                                <form method="POST">
                                    <div class="modal-header">
                                        <div>
                                            <h5 class="modal-title fw-bold">Drop Course</h5>
                                            <small class="text-muted">This action removes the course from your current learning.</small>
                                        </div>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                    </div>
                                    <div class="modal-body">
                                        <input type="hidden" name="enrollment_id" value="<?= $course['enrollment_id']; ?>">
                                        <div class="deadline-panel mb-0">
                                            <i class="fas fa-exclamation-triangle"></i>
                                            <span>Do you want to drop <strong><?= htmlspecialchars($course['course_name']); ?></strong>?</span>
                                        </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                                        <button type="submit" name="unenroll" class="btn btn-danger">
                                            <i class="fas fa-trash me-2"></i>Drop Course
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<?php include('../footer/footer.php'); ?>
