<?php 
ini_set('display_errors', 1); error_reporting(E_ALL);
require_once '../db_connect.php'; 
include 'includes/header.php'; 
include 'includes/sidebar.php'; 

$limit = 50; 
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

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

if (isset($_GET['delete_id'])) {
    $delete_id = $_GET['delete_id'];
    try {
        $stmt = $pdo->prepare("DELETE FROM courses WHERE id = ?");
        $stmt->execute([$delete_id]);
        $success_msg = "Course deleted successfully!";
    } catch (PDOException $e) {
        $error_msg = "Failed to delete the course.";
    }
}

if(isset($_GET['msg']) && $_GET['msg'] == 'updated') {
    $success_msg = "Course updated successfully!";
}

$total_rows = $pdo->query("SELECT COUNT(*) FROM courses")->fetchColumn();
$total_pages = ceil($total_rows / $limit);

// Update Query: JOIN with teachers table to get teacher's name
$stmt = $pdo->prepare("
    SELECT c.*, t.name as teacher_name 
    FROM courses c 
    LEFT JOIN teachers t ON c.teacher_id = t.id 
    ORDER BY c.id DESC LIMIT $offset, $limit
");
$stmt->execute();
$courses = $stmt->fetchAll(PDO::FETCH_ASSOC);

$sn = $offset + 1;
?>

<style>
    /* Premium Theme Colors */
    :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; }
    
    .btn-theme { background: var(--theme-green); color: #fff; border-radius: 12px; padding: 12px 24px; font-weight: 700; border: none; transition: 0.3s; display: inline-flex; align-items: center; justify-content: center; text-decoration: none; }
    .btn-theme:hover { background: var(--theme-dark); color: var(--theme-gold); transform: translateY(-2px); box-shadow: 0 8px 15px rgba(6, 78, 59, 0.2); }

    /* Desktop Table */
    .desktop-table-card { background: #fff; border-radius: 20px; border: 1px solid #e2e8f0; box-shadow: 0 10px 40px rgba(0,0,0,0.02); overflow: hidden; border-top: 5px solid var(--theme-green); }
    .table thead th { background-color: #f1f5f9; color: #64748b; font-size: 11px; text-transform: uppercase; font-weight: 800; padding: 18px 20px; border: none; letter-spacing: 0.5px; }
    .table tbody tr:hover { background-color: #f8fafc; }
    .table td { padding: 15px 20px; vertical-align: middle; font-size: 14px; color: #334155; border-bottom: 1px solid #f1f5f9; }
    
    .course-thumb { width: 45px; height: 45px; background: rgba(6, 78, 59, 0.05); border: 1px solid rgba(6, 78, 59, 0.1); border-radius: 10px; display: flex; align-items: center; justify-content: center; padding: 5px; flex-shrink: 0; }
    
    /* Badges */
    .status-badge { padding: 6px 14px; border-radius: 8px; font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.5px; }
    .status-active { background: #ecfdf5; color: #059669; border: 1px solid #d1fae5; }
    .status-inactive { background: #fef2f2; color: #ef4444; border: 1px solid #ffe4e6; }
    .fee-badge { color: var(--theme-green); font-weight: 800; font-size: 15px; background: rgba(6, 78, 59, 0.08); padding: 5px 12px; border-radius: 8px; border: 1px solid rgba(6, 78, 59, 0.15); display: inline-block;}

    /* Action Buttons */
    .act-btn { width: 34px; height: 34px; border-radius: 10px; display: inline-flex; align-items: center; justify-content: center; transition: 0.3s; margin: 0 3px; text-decoration: none; cursor: pointer; border: none; }
    .act-edit { background: rgba(212, 175, 55, 0.15); color: var(--theme-dark); }
    .act-edit:hover { background: var(--theme-gold); color: #fff; transform: translateY(-2px); }
    .act-delete { background: #fef2f2; color: #ef4444; }
    .act-delete:hover { background: #ef4444; color: #fff; transform: translateY(-2px); }

    /* Pagination */
    .pagination .page-item.active .page-link { background-color: var(--theme-green); border-color: var(--theme-green); color: #fff; }
    .pagination .page-link { color: var(--theme-green); font-weight: 600; border-radius: 8px; margin: 0 3px; border: 1px solid #e2e8f0; }
    .pagination .page-link:hover { background-color: rgba(6, 78, 59, 0.1); color: var(--theme-dark); }

    /* Animations */
    .fade-up { animation: fadeInUp 0.4s ease-out forwards; }
    @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(15px); } 100% { opacity: 1; transform: translateY(0); } }

    /* 📱 Mobile Specific Styles (Card View) */
    .course-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; }
        .dashboard-header .btn-theme { width: 100%; }
        .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"><i class="fas fa-book-open me-2" style="color: var(--theme-green);"></i> Course Library</h4>
                <p class="text-muted fw-semibold mb-0 d-none d-md-block" style="font-size: 13px;">Manage and organize all your academy courses</p>
            </div>
        </div>
        <a href="add_course.php" class="btn-theme shadow-sm">
            <i class="fas fa-plus-circle me-2"></i> Add New Course
        </a>
    </div>

    <?php if($success_msg): ?> 
        <div class="alert alert-success d-flex align-items-center mb-4 rounded-4 border-0 shadow-sm fade-up" style="border-left: 5px solid #10b981 !important;">
            <i class="fas fa-check-circle me-3 fa-2x text-success"></i> 
            <div><strong class="d-block text-success">Success!</strong><span class="text-muted small"><?= $success_msg ?></span></div>
        </div>
    <?php endif; ?>
    
    <?php if($error_msg): ?> 
        <div class="alert alert-danger d-flex align-items-center mb-4 rounded-4 border-0 shadow-sm fade-up" style="border-left: 5px solid #ef4444 !important;">
            <i class="fas fa-exclamation-triangle me-3 fa-2x text-danger"></i> 
            <div><strong class="d-block text-danger">Error!</strong><span class="text-muted small"><?= $error_msg ?></span></div>
        </div>
    <?php endif; ?>

    <div class="desktop-table-card d-none d-lg-block fade-up" style="animation-delay: 0.1s;">
        <div class="table-responsive">
            <table class="table align-middle mb-0 border-0">
                <thead>
                    <tr>
                        <th class="ps-4">No.</th>
                        <th>Course Details</th>
                        <th>Duration</th>
                        <th>Course Fee</th>
                        <th>Status</th>
                        <th class="text-end pe-4">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(!empty($courses)): foreach($courses as $course): ?>
                    <tr>
                        <td class="ps-4 text-muted small fw-bold"><?= str_pad($sn++, 2, "0", STR_PAD_LEFT); ?></td>
                        <td class="py-3">
                            <div class="d-flex align-items-center gap-3">
                                <div class="course-thumb shadow-sm">
                                    <img src="../<?= htmlspecialchars($course['image_url'] ?? 'assets/images/logo.png') ?>" style="max-width: 100%; max-height: 100%; object-fit: contain;" alt="Logo" onerror="this.src='../assets/images/default.png'">
                                </div>
                                <div>
                                    <div class="fw-bold text-dark" style="font-size: 15px;"><?= htmlspecialchars($course['title']); ?></div>
                                    <div class="mt-1">
                                        <?php if(!empty($course['teacher_name'])): ?>
                                            <span class="badge bg-light text-dark border fw-bold" style="font-size: 10px;">
                                                <i class="fas fa-chalkboard-teacher me-1 text-primary"></i> <?= htmlspecialchars($course['teacher_name']) ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="badge bg-light text-danger border fw-bold" style="font-size: 10px;">
                                                <i class="fas fa-exclamation-circle me-1"></i> Not Assigned
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </td>
                        <td>
                            <span class="badge bg-light text-muted border px-3 py-2 rounded-pill"><i class="far fa-clock me-1 text-primary"></i> <?= htmlspecialchars($course['duration']); ?></span>
                        </td>
                        <td><span class="fee-badge shadow-sm">$<?= number_format($course['fee'], 2); ?></span></td>
                        <td>
                            <span class="status-badge <?= $course['status'] == 'active' ? 'status-active' : 'bg-light text-muted border' ?>">
                                <?= ucfirst($course['status']); ?>
                            </span>
                        </td>
                        <td class="text-end pe-4">
                            <a href="edit_course.php?id=<?= $course['id']; ?>" class="act-btn act-edit shadow-sm" title="Edit"><i class="fas fa-pen"></i></a>
                            <a href="?delete_id=<?= $course['id']; ?>" class="act-btn act-delete shadow-sm" onclick="return confirm('Are you sure you want to delete this course?')" title="Delete"><i class="fas fa-trash-alt"></i></a>
                        </td>
                    </tr>
                    <?php endforeach; else: ?>
                        <tr><td colspan="6" class="text-center py-5 fw-bold text-muted"><i class="fas fa-folder-open fa-2x mb-3 d-block opacity-25"></i> No courses found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="d-block d-lg-none fade-up" style="animation-delay: 0.1s;">
        <div class="row g-3">
            <?php if(!empty($courses)): foreach($courses as $course): ?>
            <div class="col-12">
                <div class="course-mobile-card p-3">
                    <div class="d-flex align-items-center gap-3 mb-3 pb-3 border-bottom">
                        <div class="course-thumb shadow-sm" style="width: 55px; height: 55px;">
                            <img src="../<?= htmlspecialchars($course['image_url'] ?? 'assets/images/logo.png') ?>" style="max-width: 100%; max-height: 100%; object-fit: contain;" alt="Logo" onerror="this.src='../assets/images/default.png'">
                        </div>
                        <div class="w-100">
                            <div class="d-flex justify-content-between align-items-start">
                                <h6 class="fw-bold text-dark mb-1" style="font-size: 15px;"><?= htmlspecialchars($course['title']); ?></h6>
                            </div>
                            <?php if(!empty($course['teacher_name'])): ?>
                                <small class="text-muted fw-bold" style="font-size: 11px;"><i class="fas fa-chalkboard-teacher me-1 text-primary"></i> <?= htmlspecialchars($course['teacher_name']) ?></small>
                            <?php else: ?>
                                <small class="text-danger fw-bold" style="font-size: 11px;"><i class="fas fa-exclamation-circle me-1"></i> No Teacher Assigned</small>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="mb-3 d-flex justify-content-between align-items-center bg-light p-3 rounded-3 border">
                        <div>
                            <small class="text-muted text-uppercase fw-bold d-block mb-1" style="font-size: 9px;">Duration</small>
                            <span class="text-dark fw-bold" style="font-size: 13px;"><i class="far fa-clock me-1 text-primary"></i> <?= htmlspecialchars($course['duration']); ?></span>
                        </div>
                        <div class="text-end">
                            <small class="text-muted text-uppercase fw-bold d-block mb-1" style="font-size: 9px;">Course Fee</small>
                            <span class="fee-badge px-2 py-1" style="font-size: 13px;">$<?= number_format($course['fee'], 2); ?></span>
                        </div>
                    </div>
                    
                    <div class="d-flex align-items-center justify-content-between">
                        <span class="status-badge <?= $course['status'] == 'active' ? 'status-active' : 'bg-light text-muted border' ?>" style="font-size: 9px; padding: 4px 8px;">
                            <?= ucfirst($course['status']); ?>
                        </span>
                        <div class="d-flex gap-2">
                            <a href="edit_course.php?id=<?= $course['id']; ?>" class="btn btn-light border fw-bold text-warning" style="font-size: 12px; padding: 6px 12px; border-radius: 8px;"><i class="fas fa-pen"></i> Edit</a>
                            <a href="?delete_id=<?= $course['id']; ?>" class="btn btn-light border fw-bold text-danger" style="font-size: 12px; padding: 6px 12px; border-radius: 8px;" onclick="return confirm('Delete this course?');"><i class="fas fa-trash-alt"></i></a>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; else: ?>
                <div class="col-12 text-center py-5 bg-white rounded-4 border shadow-sm">
                    <i class="fas fa-folder-open fa-3x text-muted opacity-25 mb-3 d-block"></i>
                    <h6 class="fw-bold text-muted">No courses found!</h6>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <?php if($total_pages > 1): ?>
    <nav class="mt-4 fade-up" style="animation-delay: 0.2s;">
        <ul class="pagination justify-content-center">
            <?php for($i=1; $i<=$total_pages; $i++): ?>
                <li class="page-item <?= ($page == $i) ? 'active' : '' ?>">
                    <a class="page-link shadow-sm border-0 mx-1 rounded-3" href="?page=<?= $i ?>"><?= $i ?></a>
                </li>
            <?php endfor; ?>
        </ul>
    </nav>
    <?php endif; ?>
</div>

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

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<?php include 'includes/footer.php'; ?>