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

// Admin Security Check
if (!isset($_SESSION['admin_logged_in'])) { header("Location: login.php"); exit; }

$msg = "";

// 1. Update Enrollment Logic
if(isset($_POST['update_course'])) {
    // If empty, set as NULL to prevent foreign key errors
    $c_id = !empty($_POST['course_id']) ? $_POST['course_id'] : NULL;
    $t_ends = !empty($_POST['trial_ends']) ? $_POST['trial_ends'] : NULL;
    $s_id = $_POST['student_id'];
    
    try {
        $stmt = $pdo->prepare("UPDATE students SET course_id = ?, trial_ends = ? WHERE id = ?");
        $stmt->execute([$c_id, $t_ends, $s_id]);
        $msg = "<div class='alert alert-success d-flex align-items-center mb-4 rounded-4 border-0 shadow-sm fade-up'><i class='fas fa-check-circle me-3 fa-2x text-success'></i> <div><strong class='d-block text-success'>Updated Successfully!</strong> <span class='text-muted'>Student enrollment access has been updated.</span></div></div>";
    } catch(PDOException $e) {
        $msg = "<div class='alert alert-danger fw-bold rounded-4 border-0 shadow-sm'><i class='fas fa-exclamation-triangle me-2'></i> Database Error!</div>";
    }
}

// 2. Delete / Remove Access Logic
if(isset($_GET['remove_access'])) {
    $s_id = (int)$_GET['remove_access'];
    try {
        $stmt = $pdo->prepare("UPDATE students SET course_id = NULL, trial_ends = NULL WHERE id = ?");
        $stmt->execute([$s_id]);
        $msg = "<div class='alert alert-success d-flex align-items-center mb-4 rounded-4 border-0 shadow-sm fade-up'><i class='fas fa-check-circle me-3 fa-2x text-success'></i> <div><strong class='d-block text-success'>Access Revoked!</strong> <span class='text-muted'>Student's course enrollment has been removed.</span></div></div>";
    } catch(PDOException $e) {
        $msg = "<div class='alert alert-danger fw-bold rounded-4 border-0 shadow-sm'><i class='fas fa-exclamation-triangle me-2'></i> Error removing access!</div>";
    }
}

include 'includes/header.php'; 
include 'includes/sidebar.php'; 

// Fetch Data
$students = $pdo->query("SELECT s.*, c.title as course_name FROM students s LEFT JOIN courses c ON s.course_id = c.id ORDER BY s.id DESC")->fetchAll(PDO::FETCH_ASSOC);
$courses = $pdo->query("SELECT id, title FROM courses WHERE status='active'")->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
    :root { --theme-green: #064e3b; --theme-dark: #022c22; --theme-gold: #d4af37; --bg-soft: #f8fafc; }
    .main-content { background-color: var(--bg-soft); min-height: 100vh; padding-bottom: 50px; font-family: 'Outfit', sans-serif; }
    
    /* Header & Mobile Menu */
    .dashboard-header { background: #fff; padding: 20px 30px; border-radius: 20px; box-shadow: 0 5px 20px rgba(0,0,0,0.03); margin-bottom: 30px; border-left: 6px solid var(--theme-green); }
    #sidebarToggle { display: none; width: 45px; height: 45px; border-radius: 12px; background: #f1f5f9; border: 1px solid #e2e8f0; color: var(--theme-green); cursor: pointer; transition: 0.3s; display: inline-flex; align-items: center; justify-content: center; }
    #sidebarToggle:hover { background: var(--theme-green); color: #fff; }

    /* Desktop Table */
    .desktop-table-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 20px; box-shadow: 0 10px 40px rgba(0,0,0,0.02); overflow: hidden; }
    .table-hover tbody tr:hover { background-color: #f8fafc; }
    .table thead th { border: none; padding: 18px 20px; color: #64748b; font-weight: 800; text-transform: uppercase; font-size: 11px; letter-spacing: 0.5px; background-color: #f1f5f9; }
    
    /* Avatar */
    .avatar-circle { width: 45px; height: 45px; border-radius: 12px; background: rgba(6, 78, 59, 0.1); color: var(--theme-green); display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 18px; }
    
    /* Animations */
    .fade-up { animation: fadeInUp 0.5s ease-out forwards; }
    @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(15px); } 100% { opacity: 1; transform: translateY(0); } }
    
    /* Buttons & Badges */
    .act-btn { width: 34px; height: 34px; border-radius: 10px; display: inline-flex; align-items: center; justify-content: center; border: none; transition: 0.3s; margin: 0 3px; text-decoration: none; cursor: pointer; }
    .act-edit { background: #f1f5f9; color: var(--theme-green); } 
    .act-edit:hover { background: var(--theme-green); color: #fff; transform: translateY(-2px); }
    .act-delete { background: #fef2f2; color: #ef4444; } 
    .act-delete:hover { background: #ef4444; color: #fff; transform: translateY(-2px); }
    
    .status-badge { padding: 6px 14px; border-radius: 8px; font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.5px; display: inline-flex; align-items: center; gap: 5px; }

    /* Modal Styling */
    .modal-content { border-radius: 24px; border: none; box-shadow: 0 20px 50px rgba(0,0,0,0.1); }
    .form-control, .form-select { border-radius: 12px; border: 2px solid #f1f5f9; padding: 12px 15px; font-size: 15px; background: #f8fafc; transition: 0.3s; }
    .form-control:focus, .form-select:focus { border-color: var(--theme-green); background: #fff; box-shadow: 0 0 0 4px rgba(6, 78, 59, 0.1); }

    /* 📱 Mobile Specific Styles */
    .student-mobile-card { background: #fff; border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 4px 15px rgba(0,0,0,0.03); overflow: hidden; transition: 0.3s; }
    
    @media (max-width: 991.98px) {
        .main-content { padding: 15px !important; }
        .dashboard-header { padding: 20px; flex-direction: column; align-items: flex-start !important; gap: 15px; }
        .dashboard-header .header-top { width: 100%; display: flex; justify-content: flex-start; align-items: center; gap: 15px; }
        .header-title { font-size: 1.2rem; }
    }
    @media (min-width: 992px) {
        #sidebarToggle { display: none !important; }
    }
</style>

<div class="main-content p-3 p-md-4">
    
    <div class="dashboard-header d-flex justify-content-between align-items-center fade-up">
        <div class="header-top">
            <button id="sidebarToggle" class="shadow-sm"><i class="fas fa-bars fs-5"></i></button>
            <div>
                <h4 class="mb-0 fw-bold text-dark header-title">Course Enrollments</h4>
                <p class="text-muted small fw-bold mb-0 d-none d-md-block">Manage student courses and access expiry dates</p>
            </div>
        </div>
        <button class="btn btn-light border fw-bold px-4 py-2 rounded-3 shadow-sm" onclick="location.reload();">
            <i class="fas fa-sync-alt me-2 text-primary"></i> Refresh
        </button>
    </div>

    <?= $msg ?>

    <div class="desktop-table-card d-none d-lg-block fade-up" style="animation-delay: 0.1s;">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0 border-0">
                <thead>
                    <tr>
                        <th class="ps-4">Student Profile</th>
                        <th>Assigned Course</th>
                        <th>Access / Trial Status</th>
                        <th class="text-end pe-4">Manage Access</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($students as $s): 
                        // Expiry Logic Calculation
                        $expiry_time = strtotime($s['trial_ends']);
                        $is_lifetime = ($s['trial_ends'] == '2099-12-31' || $expiry_time > strtotime('+10 years'));
                        $is_expired = (!$is_lifetime && $expiry_time < time() && $s['trial_ends'] != null);
                    ?>
                    <tr>
                        <td class="py-3 ps-4">
                            <div class="d-flex align-items-center gap-3">
                                <div class="avatar-circle shadow-sm"><?= strtoupper(substr($s['name'], 0, 1)) ?></div>
                                <div>
                                    <div class="fw-bold text-dark" style="font-size: 15px;"><?= htmlspecialchars($s['name']) ?></div>
                                    <small class="text-muted fw-semibold"><?= htmlspecialchars($s['email']) ?></small>
                                </div>
                            </div>
                        </td>
                        <td>
                            <span class="badge bg-primary-subtle text-primary border border-primary-subtle px-3 py-2 rounded-pill">
                                <i class="fas fa-book-open me-1"></i> <?= $s['course_name'] ?? 'Not Assigned' ?>
                            </span>
                        </td>
                        <td>
                            <?php if(empty($s['trial_ends'])): ?>
                                <span class="status-badge bg-secondary-subtle text-secondary"><i class="fas fa-clock"></i> No Limit Set</span>
                            <?php elseif($is_lifetime): ?>
                                <span class="status-badge bg-success-subtle text-success border border-success-subtle"><i class="fas fa-infinity"></i> Lifetime Access</span>
                            <?php elseif($is_expired): ?>
                                <span class="status-badge bg-danger-subtle text-danger border border-danger-subtle"><i class="fas fa-exclamation-triangle"></i> Expired (<?= date('d M, Y', $expiry_time) ?>)</span>
                            <?php else: ?>
                                <span class="status-badge bg-warning-subtle text-warning border border-warning-subtle"><i class="fas fa-hourglass-half"></i> Active till <?= date('d M, Y', $expiry_time) ?></span>
                            <?php endif; ?>
                        </td>
                        <td class="text-end pe-4">
                            <button class="act-btn act-edit shadow-sm" onclick='openEnrollModal(<?= htmlspecialchars(json_encode($s), ENT_QUOTES, 'UTF-8') ?>)' title="Edit Course & Expiry">
                                <i class="fas fa-pen"></i>
                            </button>
                            <a href="?remove_access=<?= $s['id'] ?>" class="act-btn act-delete shadow-sm" onclick="return confirm('Are you sure you want to remove course access for this student?');" title="Remove Course Access">
                                <i class="fas fa-trash-alt"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="d-block d-lg-none fade-up" style="animation-delay: 0.1s;">
        <div class="row g-3">
            <?php foreach($students as $s): 
                $expiry_time = strtotime($s['trial_ends']);
                $is_lifetime = ($s['trial_ends'] == '2099-12-31' || $expiry_time > strtotime('+10 years'));
                $is_expired = (!$is_lifetime && $expiry_time < time() && $s['trial_ends'] != null);
            ?>
            <div class="col-12">
                <div class="student-mobile-card p-3">
                    <div class="d-flex align-items-center gap-3 mb-3 pb-3 border-bottom">
                        <div class="avatar-circle shadow-sm" style="width: 45px; height: 45px; font-size: 16px;"><?= strtoupper(substr($s['name'], 0, 1)) ?></div>
                        <div>
                            <h6 class="fw-bold text-dark mb-0" style="font-size: 15px;"><?= htmlspecialchars($s['name']) ?></h6>
                            <small class="text-muted fw-bold" style="font-size: 12px;"><?= htmlspecialchars($s['email']) ?></small>
                        </div>
                    </div>
                    
                    <div class="mb-3 px-2">
                        <div class="mb-2">
                            <small class="text-muted text-uppercase fw-bold d-block mb-1" style="font-size: 10px;">Assigned Course</small>
                            <span class="badge bg-primary-subtle text-primary px-3 py-2 rounded-pill w-100 text-start">
                                <i class="fas fa-book-open me-1"></i> <?= $s['course_name'] ?? 'Not Assigned' ?>
                            </span>
                        </div>
                        <div>
                            <small class="text-muted text-uppercase fw-bold d-block mb-1 mt-3" style="font-size: 10px;">Access Status</small>
                            <?php if(empty($s['trial_ends'])): ?>
                                <span class="status-badge bg-secondary-subtle text-secondary"><i class="fas fa-clock"></i> No Limit Set</span>
                            <?php elseif($is_lifetime): ?>
                                <span class="status-badge bg-success-subtle text-success"><i class="fas fa-infinity"></i> Lifetime Access</span>
                            <?php elseif($is_expired): ?>
                                <span class="status-badge bg-danger-subtle text-danger"><i class="fas fa-exclamation-triangle"></i> Expired (<?= date('d M', $expiry_time) ?>)</span>
                            <?php else: ?>
                                <span class="status-badge bg-warning-subtle text-warning"><i class="fas fa-hourglass-half"></i> Active till <?= date('d M', $expiry_time) ?></span>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="d-flex gap-2 mt-3 pt-2 border-top">
                        <button class="btn btn-light border flex-grow-1 fw-bold text-success" style="font-size: 13px; padding: 10px;" onclick='openEnrollModal(<?= htmlspecialchars(json_encode($s), ENT_QUOTES, 'UTF-8') ?>)'>
                            <i class="fas fa-pen me-2"></i> Edit
                        </button>
                        <a href="?remove_access=<?= $s['id'] ?>" class="btn btn-light border flex-grow-1 fw-bold text-danger" style="font-size: 13px; padding: 10px;" onclick="return confirm('Remove course access for this student?');">
                            <i class="fas fa-trash-alt me-2"></i> Delete
                        </a>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<div class="modal fade" id="enrollModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <form method="POST" class="modal-content p-2">
            <div class="modal-header border-0 pb-0">
                <h5 class="fw-bold mb-0 text-dark"><i class="fas fa-user-check text-success me-2"></i> Update Access</h5>
                <button type="button" class="btn-close shadow-none" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            
            <div class="modal-body p-4">
                <input type="hidden" name="student_id" id="eid">
                
                <div class="mb-4">
                    <label class="form-label small fw-bold text-uppercase text-muted">Assign Course</label>
                    <div class="input-group">
                        <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-book"></i></span>
                        <select name="course_id" id="ecid" class="form-select border-start-0 ps-0 fw-bold">
                            <option value="">-- No Course --</option>
                            <?php foreach($courses as $c) echo "<option value='{$c['id']}'>{$c['title']}</option>"; ?>
                        </select>
                    </div>
                </div>
                
                <div class="mb-2">
                    <label class="form-label small fw-bold text-uppercase text-muted d-flex justify-content-between">
                        <span>Access Expiry Date</span>
                        <button type="button" class="btn btn-sm btn-outline-success py-0 px-2 fw-bold" style="font-size: 10px;" onclick="setLifetime()">Set Lifetime</button>
                    </label>
                    <div class="input-group">
                        <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-calendar-alt"></i></span>
                        <input type="date" name="trial_ends" id="etrial" class="form-control border-start-0 ps-0 fw-bold">
                    </div>
                </div>
            </div>
            
            <div class="modal-footer border-0 pt-0 px-4 pb-4">
                <button type="submit" name="update_course" class="btn btn-dark w-100 py-3 fw-bold rounded-3 shadow-sm" style="background: var(--theme-green); border: none;">
                    SAVE ENROLLMENT DETAILS
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    // Set Lifetime Access Shortcut
    function setLifetime() {
        document.getElementById('etrial').value = '2099-12-31';
    }

    // Open Modal and Populate Data
    function openEnrollModal(data) {
        document.getElementById('eid').value = data.id;
        document.getElementById('ecid').value = data.course_id || "";
        
        // Handle Expiry Date
        let expiry = data.trial_ends;
        if(expiry) {
            document.getElementById('etrial').value = expiry.split(' ')[0]; // Extract YYYY-MM-DD
        } else {
            document.getElementById('etrial').value = '';
        }
        
        new bootstrap.Modal(document.getElementById('enrollModal')).show();
    }

    // Sidebar Mobile Menu Toggle Logic
    document.addEventListener("DOMContentLoaded", function() {
        const toggleBtn = document.getElementById('sidebarToggle');
        const sidebar = document.getElementById('sidebarMenu'); 
        
        if (toggleBtn) {
            toggleBtn.addEventListener('click', function(e) {
                e.preventDefault();
                if(sidebar) {
                    sidebar.classList.toggle('active');
                } else {
                    const fallbackSidebar = document.querySelector('.sidebar');
                    if(fallbackSidebar) fallbackSidebar.classList.toggle('active');
                }
            });
        }
    });
</script>

<?php include 'includes/footer.php'; ?>