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

if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], ['admin', 'lecturer'])) {
    header("Location: dashboard.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$role = $_SESSION['role'];

function canReviewRequest($request, $role, $user_id) {
    return $role == 'admin' || $request['current_lecturer_id'] == $user_id || $request['requested_lecturer_id'] == $user_id;
}

function enrollStudentInCourse($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['approve_request'], $_POST['request_id'])) {
    $request_id = (int) $_POST['request_id'];

    $stmt = $pdo->prepare("
        SELECT r.*, cc.lecturer_id as current_lecturer_id, rc.lecturer_id as requested_lecturer_id
        FROM course_change_requests r
        JOIN courses cc ON r.current_course_id = cc.id
        JOIN courses rc ON r.requested_course_id = rc.id
        WHERE r.id = ? AND r.status = 'pending'
    ");
    $stmt->execute([$request_id]);
    $request = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($request && canReviewRequest($request, $role, $user_id)) {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM enrollments WHERE student_id = ? AND id <> ? AND status IN ('enrolled', 'appeal_pending')");
        $stmt->execute([$request['student_id'], $request['enrollment_id']]);
        if ($stmt->fetchColumn() > 0) {
            header("Location: manage_appeals.php?error=student_active");
            exit();
        }

        $pdo->beginTransaction();
        try {
            $stmt = $pdo->prepare("UPDATE course_change_requests SET status = 'approved', reviewed_by = ?, reviewed_at = NOW() WHERE id = ?");
            $stmt->execute([$user_id, $request_id]);

            $stmt = $pdo->prepare("UPDATE enrollments SET status = 'dropped', dropped_at = NOW() WHERE id = ?");
            $stmt->execute([$request['enrollment_id']]);

            enrollStudentInCourse($pdo, $request['student_id'], $request['requested_course_id']);
            $pdo->commit();

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

    header("Location: manage_appeals.php?error=not_allowed");
    exit();
}

if (isset($_POST['reject_request'], $_POST['request_id'])) {
    $request_id = (int) $_POST['request_id'];

    $stmt = $pdo->prepare("
        SELECT r.*, cc.lecturer_id as current_lecturer_id, rc.lecturer_id as requested_lecturer_id
        FROM course_change_requests r
        JOIN courses cc ON r.current_course_id = cc.id
        JOIN courses rc ON r.requested_course_id = rc.id
        WHERE r.id = ? AND r.status = 'pending'
    ");
    $stmt->execute([$request_id]);
    $request = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($request && canReviewRequest($request, $role, $user_id)) {
        $stmt = $pdo->prepare("UPDATE course_change_requests SET status = 'rejected', reviewed_by = ?, reviewed_at = NOW() WHERE id = ?");
        $stmt->execute([$user_id, $request_id]);

        header("Location: manage_appeals.php?success=request_rejected");
        exit();
    }

    header("Location: manage_appeals.php?error=not_allowed");
    exit();
}

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

    $stmt = $pdo->prepare("UPDATE enrollments SET status = 'appeal_approved' WHERE id = ?");
    $stmt->execute([$enrollment_id]);

    header("Location: manage_appeals.php?success=approved");
    exit();
}

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

    $stmt = $pdo->prepare("UPDATE enrollments SET status = 'appeal_rejected' WHERE id = ?");
    $stmt->execute([$enrollment_id]);

    header("Location: manage_appeals.php?success=rejected");
    exit();
}

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

$success_msg = '';
$error_msg = '';
if (isset($_GET['success'])) {
    $messages = [
        'approved' => 'Appeal approved successfully.',
        'rejected' => 'Appeal rejected successfully.',
        'request_approved' => 'Course change approved and enrollment updated.',
        'request_rejected' => 'Course change request rejected.'
    ];
    $success_msg = $messages[$_GET['success']] ?? '';
}

if (isset($_GET['error'])) {
    $messages = [
        'not_allowed' => 'You are not allowed to review that request.',
        'request_failed' => 'The request could not be processed. Please try again.',
        'student_active' => 'This student already has another active course.'
    ];
    $error_msg = $messages[$_GET['error']] ?? '';
}

$request_query = "
    SELECT r.*,
           u.username as student_name,
           u.email as student_email,
           current_course.course_name as current_course_name,
           requested_course.course_name as requested_course_name,
           current_course.lecturer_id as current_lecturer_id,
           requested_course.lecturer_id as requested_lecturer_id
    FROM course_change_requests r
    JOIN users u ON r.student_id = u.id
    JOIN courses current_course ON r.current_course_id = current_course.id
    JOIN courses requested_course ON r.requested_course_id = requested_course.id
    WHERE r.status = 'pending'
";

if ($role == 'lecturer') {
    $request_query .= " AND (current_course.lecturer_id = ? OR requested_course.lecturer_id = ?)";
    $stmt = $pdo->prepare($request_query . " ORDER BY r.created_at DESC");
    $stmt->execute([$user_id, $user_id]);
} else {
    $stmt = $pdo->prepare($request_query . " ORDER BY r.created_at DESC");
    $stmt->execute();
}

$change_requests = $stmt->fetchAll(PDO::FETCH_ASSOC);

$appeal_query = "
    SELECT e.*, c.course_name, u.username as student_name, u.email as student_email
    FROM enrollments e
    JOIN courses c ON e.course_id = c.id
    JOIN users u ON e.student_id = u.id
    WHERE e.status = 'appeal_pending'
";

if ($role == 'lecturer') {
    $appeal_query .= " AND c.lecturer_id = ?";
    $stmt = $pdo->prepare($appeal_query . " ORDER BY e.appeal_requested_at DESC");
    $stmt->execute([$user_id]);
} else {
    $stmt = $pdo->prepare($appeal_query . " ORDER BY e.appeal_requested_at DESC");
    $stmt->execute();
}

$appeals = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container-fluid py-4 requests-shell">
    <div class="requests-hero mb-4">
        <div>
            <p class="text-uppercase text-muted fw-semibold small mb-1">Academic review</p>
            <h2 class="fw-bold mb-1">Manage Course Requests</h2>
            <p class="text-muted mb-0">Review course changes and deadline appeals from one clean workspace.</p>
        </div>
        <a href="dashboard.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left me-2"></i>Back</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; ?>

    <div class="request-stats mb-4">
        <div class="request-stat">
            <span>Course changes</span>
            <strong><?= count($change_requests); ?></strong>
        </div>
        <div class="request-stat">
            <span>Drop appeals</span>
            <strong><?= count($appeals); ?></strong>
        </div>
    </div>

    <?php if (empty($change_requests) && empty($appeals)): ?>
        <div class="text-center py-5">
            <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
            <h4 class="text-muted">No pending requests</h4>
            <p class="text-muted">Course changes and appeals awaiting review will appear here.</p>
        </div>
    <?php endif; ?>

    <?php if (!empty($change_requests)): ?>
        <h5 class="fw-bold mb-3">Course Change Requests</h5>
        <div class="row g-3 mb-5">
            <?php foreach ($change_requests as $request): ?>
                <div class="col-xl-6">
                    <div class="review-card h-100">
                        <div class="d-flex justify-content-between gap-3 mb-3">
                            <div class="d-flex align-items-center">
                                <div class="review-avatar me-3"><i class="fas fa-user-graduate"></i></div>
                                <div>
                                    <div class="fw-bold"><?= htmlspecialchars($request['student_name']); ?></div>
                                    <small class="text-muted"><?= htmlspecialchars($request['student_email']); ?></small>
                                </div>
                            </div>
                            <span class="badge bg-warning text-dark align-self-start">Pending</span>
                        </div>

                        <div class="course-route mb-3">
                            <div>
                                <small>Current</small>
                                <strong><?= htmlspecialchars($request['current_course_name']); ?></strong>
                            </div>
                            <i class="fas fa-arrow-right"></i>
                            <div>
                                <small>Requested</small>
                                <strong><?= htmlspecialchars($request['requested_course_name']); ?></strong>
                            </div>
                        </div>

                        <p class="text-muted mb-3"><?= nl2br(htmlspecialchars($request['reason'])); ?></p>
                        <small class="text-muted d-block mb-3">Submitted <?= date('M d, Y H:i', strtotime($request['created_at'])); ?></small>

                        <form method="POST" class="d-flex gap-2">
                            <input type="hidden" name="request_id" value="<?= $request['id']; ?>">
                            <button type="submit" name="approve_request" class="btn btn-success flex-fill">
                                <i class="fas fa-check me-2"></i>Approve
                            </button>
                            <button type="submit" name="reject_request" class="btn btn-outline-danger flex-fill" onclick="return confirm('Reject this course change request?')">
                                <i class="fas fa-times me-2"></i>Reject
                            </button>
                        </form>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <?php if (!empty($appeals)): ?>
        <h5 class="fw-bold mb-3">Legacy Drop Appeals</h5>
        <div class="card shadow-sm border-0">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="bg-light">
                            <tr>
                                <th class="ps-4">Student</th>
                                <th>Course</th>
                                <th>Submitted</th>
                                <th>Reason</th>
                                <th class="text-end pe-4">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($appeals as $appeal): ?>
                                <tr>
                                    <td class="ps-4">
                                        <div class="fw-bold"><?= htmlspecialchars($appeal['student_name']); ?></div>
                                        <small class="text-muted"><?= htmlspecialchars($appeal['student_email']); ?></small>
                                    </td>
                                    <td><?= htmlspecialchars($appeal['course_name']); ?></td>
                                    <td><?= date('M d, Y H:i', strtotime($appeal['appeal_requested_at'])); ?></td>
                                    <td>
                                        <div class="text-truncate" style="max-width: 320px;" title="<?= htmlspecialchars($appeal['appeal_reason']); ?>">
                                            <?= htmlspecialchars(substr($appeal['appeal_reason'], 0, 120)); ?>...
                                        </div>
                                    </td>
                                    <td class="text-end pe-4">
                                        <form method="POST" class="d-inline">
                                            <input type="hidden" name="enrollment_id" value="<?= $appeal['id']; ?>">
                                            <button type="submit" name="approve_appeal" class="btn btn-sm btn-success me-1">
                                                <i class="fas fa-check me-1"></i>Approve
                                            </button>
                                            <button type="submit" name="reject_appeal" class="btn btn-sm btn-danger" onclick="return confirm('Reject this appeal?')">
                                                <i class="fas fa-times me-1"></i>Reject
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

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