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

// Restrict to admin
if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
    die("Access denied.");
}

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

$success = '';
$error = '';

function activateStudentEnrollment($pdo, $student_id, $course_id) {
    $stmt = $pdo->prepare("
        SELECT COUNT(*)
        FROM enrollments
        WHERE student_id = ? AND course_id <> ? AND status IN ('enrolled', 'appeal_pending')
    ");
    $stmt->execute([$student_id, $course_id]);

    if ($stmt->fetchColumn() > 0) {
        throw new Exception("Student already has another active course. Ask them to complete a course change first.");
    }

    $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]);
}

// UPDATE STATUS
if (isset($_POST['update_status'])) {

    $app_id = $_POST['app_id'];
    $new_status = $_POST['status'];

    try {
        $pdo->beginTransaction();

        // Get application
        $stmt = $pdo->prepare("SELECT * FROM applications WHERE id = ?");
        $stmt->execute([$app_id]);
        $app = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$app) {
            throw new Exception("Application not found.");
        }

        // Update status
        $stmt = $pdo->prepare("UPDATE applications SET status = ? WHERE id = ?");
        $stmt->execute([$new_status, $app_id]);

        // IF ACCEPTED
        if ($new_status == 'accepted') {

            // Check if user exists
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$app['email']]);
            $existing_user = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$existing_user) {
                $username = explode('@', $app['email'])[0];
                $password = password_hash('Welcome123', PASSWORD_DEFAULT);

                $stmt = $pdo->prepare("
                    INSERT INTO users (username, email, password, role, status)
                    VALUES (?, ?, ?, 'student', 'accepted')
                ");
                $stmt->execute([$username, $app['email'], $password]);

                $user_id = $pdo->lastInsertId();
            } else {
                $user_id = $existing_user['id'];

                $stmt = $pdo->prepare("UPDATE users SET status='accepted' WHERE id=?");
                $stmt->execute([$user_id]);
            }

            // Enroll student
            if (!empty($app['course_id'])) {
                activateStudentEnrollment($pdo, $user_id, $app['course_id']);
            }
        }

        $pdo->commit();

        $success = "Application updated successfully!";
        if ($new_status == 'accepted') {
            $success .= " Student account created (Password: Welcome123)";
        }

    } catch (Exception $e) {
        $pdo->rollBack();
        $error = $e->getMessage();
    }
}

// FETCH APPLICATIONS
try {
    $stmt = $pdo->query("
        SELECT a.*, c.course_name 
        FROM applications a 
        LEFT JOIN courses c ON a.course_id = c.id 
        ORDER BY a.created_at DESC
    ");
    $applications = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $applications = [];
    $error = "Error fetching applications.";
}
?>

<div class="container-fluid py-4">

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="fw-bold">Manage Applications</h2>
        <span class="badge bg-secondary px-3 py-2 rounded-pill"><?php echo count($applications); ?> Total Applications</span>
    </div>

    <!-- Stats Summary -->
    <div class="row g-4 mb-4">
        <div class="col-md-4">
            <?php 
                $pending_apps = count(array_filter($applications, function($a) { return $a['status'] == 'pending'; }));
            ?>
            <div class="dash-card bg-white p-3 shadow-sm border-start border-4 border-warning">
                <div class="d-flex align-items-center">
                    <div class="icon-box bg-warning bg-opacity-10 text-warning me-3">
                        <i class="fas fa-file-invoice"></i>
                    </div>
                    <div>
                        <p class="text-muted small text-uppercase mb-0 fw-bold">Pending Review</p>
                        <h4 class="fw-bold mb-0"><?php echo $pending_apps; ?></h4>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <?php 
                $accepted_apps = count(array_filter($applications, function($a) { return $a['status'] == 'accepted'; }));
            ?>
            <div class="dash-card bg-white p-3 shadow-sm border-start border-4 border-success">
                <div class="d-flex align-items-center">
                    <div class="icon-box bg-success bg-opacity-10 text-success me-3">
                        <i class="fas fa-user-check"></i>
                    </div>
                    <div>
                        <p class="text-muted small text-uppercase mb-0 fw-bold">Accepted</p>
                        <h4 class="fw-bold mb-0"><?php echo $accepted_apps; ?></h4>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <?php 
                $rejected_apps = count(array_filter($applications, function($a) { return $a['status'] == 'rejected'; }));
            ?>
            <div class="dash-card bg-white p-3 shadow-sm border-start border-4 border-danger">
                <div class="d-flex align-items-center">
                    <div class="icon-box bg-danger bg-opacity-10 text-danger me-3">
                        <i class="fas fa-user-times"></i>
                    </div>
                    <div>
                        <p class="text-muted small text-uppercase mb-0 fw-bold">Rejected</p>
                        <h4 class="fw-bold mb-0"><?php echo $rejected_apps; ?></h4>
                    </div>
                </div>
            </div>
        </div>
    </div>

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

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

    <div class="card glass-card border-0 shadow-sm">
        <div class="card-header bg-white border-0 py-3">
            <h5 class="fw-bold mb-0">Student Enrollment Applications</h5>
        </div>
        <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">Applicant</th>
                            <th>Applied Course</th>
                            <th>Status</th>
                            <th>Application Date</th>
                            <th class="text-end pe-4">Manage Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($applications)): ?>
                            <tr><td colspan="5" class="text-center py-4 text-muted">No applications found</td></tr>
                        <?php endif; ?>

                        <?php foreach($applications as $app): ?>
                            <tr>
                                <td class="ps-4">
                                    <div class="fw-bold text-dark"><?php echo htmlspecialchars($app['full_name']); ?></div>
                                    <small class="text-muted"><?php echo htmlspecialchars($app['email']); ?></small>
                                </td>
                                <td>
                                    <span class="text-dark fw-medium"><?php echo $app['course_name'] ?? 'N/A'; ?></span>
                                </td>
                                <td>
                                    <span class="badge <?php 
                                        echo $app['status'] == 'accepted' ? 'bg-success' : ($app['status'] == 'rejected' ? 'bg-danger' : 'bg-warning text-dark'); 
                                    ?> text-capitalize px-3 py-2 rounded-pill">
                                        <?php echo $app['status']; ?>
                                    </span>
                                </td>
                                <td><i class="far fa-calendar-alt me-2 text-muted"></i><?php echo date('M d, Y', strtotime($app['created_at'])); ?></td>
                                <td class="text-end pe-4">
                                    <form method="POST" class="d-flex justify-content-end align-items-center gap-2">
                                        <input type="hidden" name="app_id" value="<?php echo $app['id']; ?>">
                                        <select name="status" class="form-select form-select-sm" style="width: auto; min-width: 120px;">
                                            <option value="pending" <?php echo $app['status'] == 'pending' ? 'selected' : ''; ?>>Pending</option>
                                            <option value="accepted" <?php echo $app['status'] == 'accepted' ? 'selected' : ''; ?>>Accept</option>
                                            <option value="rejected" <?php echo $app['status'] == 'rejected' ? 'selected' : ''; ?>>Reject</option>
                                        </select>
                                        <button type="submit" name="update_status" class="btn btn-sm btn-primary">Update</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div>

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