<?php
/**
 * IBVTE - All Courses / Categories Display
 */

require_once 'config.php';
require_once 'includes/db.php';

$db = DB();

$catSlug = $_GET['category'] ?? '';
$subSlug = $_GET['sub'] ?? '';

$pageTitle = 'All Courses | IBVTE';
$pageDesc  = 'Explore our wide range of courses including Vocational, Diploma, Short Term, and Certificate programs.';

include 'includes/header.php';

if ($catSlug) {
    $type = $_GET['type'] ?? '';

    // Fetch the Category
    $cat = $db->fetchOne("SELECT id, name FROM course_categories WHERE slug=?", [$catSlug]);
    if (!$cat) {
        echo "<div class='container py-5 text-center'><h3>Category not found</h3></div>";
        include 'includes/footer.php';
        exit;
    }
    
    if (!$type) {
        $allTypes = [
            'Vocational Course',
            'Diploma Course',
            'Short Term Course',
            'Certificate Course',
            'Other Course'
        ];
        
        $types = [];
        $isLiveSchema = false;
        try {
            $db->fetchOne("SELECT category_id FROM courses LIMIT 1");
            $isLiveSchema = true;
        } catch (Exception $e) {}

        foreach ($allTypes as $t) {
            $matchType = str_replace(' Course', '', $t);
            $matchCat = str_replace([' Education', ' Courses'], '', $cat['name']);
            
            if ($isLiveSchema) {
                $where = "category_id = {$cat['id']} AND (course_type LIKE ? OR course_type LIKE ?) AND is_active=1";
                $params = ['%' . $matchType . '%', '%' . $t . '%'];
                
                if ($t === 'Other Course') {
                    $where = "category_id = {$cat['id']} AND is_active=1 AND course_type NOT LIKE '%Vocational%' AND course_type NOT LIKE '%Diploma%' AND course_type NOT LIKE '%Short Term%' AND course_type NOT LIKE '%Certificate%'";
                    $params = [];
                }
            } else {
                $where = "short_name LIKE ? AND category LIKE ? AND is_active=1";
                $params = ['%' . $matchCat . '%', '%' . $t . '%'];
                
                if ($t === 'Other Course') {
                    $where = "short_name LIKE ? AND is_active=1 AND category NOT LIKE '%Vocational%' AND category NOT LIKE '%Diploma%' AND category NOT LIKE '%Short Term%' AND category NOT LIKE '%Certificate%'";
                    $params = ['%' . $matchCat . '%'];
                }
            }
            
            $count = $db->fetchOne("SELECT COUNT(id) as cnt FROM courses WHERE $where", $params);
            if ($count && $count['cnt'] > 0) {
                $types[] = $t;
            }
        }
        ?>
        <section class="py-5" style="background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);">
            <div class="container text-center">
                <h1 class="fw-bold mb-0 text-primary display-5" style="color: #2c3e50 !important; letter-spacing: 2px; text-transform: uppercase;">
                    <?= htmlspecialchars($cat['name']) ?> - COURSE TYPES
                </h1>
            </div>
        </section>
        
        <section class="py-5 bg-light" style="background-color: #f1f4f8 !important;">
            <div class="container">
                <div class="row justify-content-center g-4">
                    <?php if (empty($types)): ?>
                        <div class="col-12 text-center py-5">
                            <i class="far fa-folder-open fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">No courses available in this category yet.</h5>
                        </div>
                    <?php else: ?>
                        <?php foreach ($types as $t): ?>
                            <div class="col-lg-3 col-md-4 col-sm-6">
                                <a href="all-courses.php?category=<?= urlencode($catSlug) ?>&type=<?= urlencode($t) ?>" class="text-decoration-none">
                                    <div class="image-course-card bg-white h-100 shadow-sm border border-light text-center p-4" style="border-radius: 12px;">
                                        <div class="mb-3">
                                            <i class="fas fa-award fa-3x text-primary"></i>
                                        </div>
                                        <div class="card-title-wrapper px-2 pb-2">
                                            <h6 class="fw-bold text-dark mb-0" style="font-size: 1.1rem; letter-spacing: 0.5px; text-transform: uppercase;">
                                                <?= htmlspecialchars($t) ?>
                                            </h6>
                                        </div>
                                    </div>
                                </a>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                <div class="text-center mt-5">
                    <a href="all-courses.php" class="btn btn-outline-primary px-4 rounded-pill"><i class="fas fa-arrow-left me-2"></i>Back to Categories</a>
                </div>
            </div>
        </section>
        
        <style>
            .image-course-card {
                transition: all 0.3s ease;
                border-radius: 2px;
            }
            .image-course-card:hover {
                transform: translateY(-5px);
                box-shadow: 0 10px 20px rgba(0,0,0,0.1) !important;
                border-color: #0d6efd !important;
            }
            .image-course-card i {
                transition: transform 0.5s ease;
            }
            .image-course-card:hover i {
                transform: scale(1.15) !important;
            }
        </style>
        <?php
    } else {
        // Detect if we are on Localhost or Live by checking DB schema or just catching exception
        $matchType = str_replace(' Course', '', $type);
        $matchCat = str_replace([' Education', ' Courses'], '', $cat['name']);
        
        $isLiveSchema = false;
        try {
            // Check if category_id exists
            $db->fetchOne("SELECT category_id FROM courses LIMIT 1");
            $isLiveSchema = true;
        } catch (Exception $e) {
            $isLiveSchema = false;
        }

        if ($isLiveSchema) {
            $where = "c.category_id = {$cat['id']} AND (c.course_type LIKE ? OR c.course_type LIKE ?) AND c.is_active=1";
            $params = ['%' . $matchType . '%', '%' . $type . '%'];
            
            if ($type === 'Other Course') {
                $where = "c.category_id = {$cat['id']} AND c.is_active=1 AND c.course_type NOT LIKE '%Vocational%' AND c.course_type NOT LIKE '%Diploma%' AND c.course_type NOT LIKE '%Short Term%' AND c.course_type NOT LIKE '%Certificate%'";
                $params = [];
            }
        } else {
            $where = "c.short_name LIKE ? AND c.category LIKE ? AND c.is_active=1";
            $params = ['%' . $matchCat . '%', '%' . $type . '%'];
            
            if ($type === 'Other Course') {
                $where = "c.short_name LIKE ? AND c.is_active=1 AND c.category NOT LIKE '%Vocational%' AND c.category NOT LIKE '%Diploma%' AND c.category NOT LIKE '%Short Term%' AND c.category NOT LIKE '%Certificate%'";
                $params = ['%' . $matchCat . '%'];
            }
        }
        
        // Remove LEFT JOIN course_sub_categories since it doesn't exist, to prevent SQL errors
        $courses = $db->fetchAll("SELECT c.*, cf.total_fee 
            FROM courses c 
            LEFT JOIN course_fees cf ON c.id = cf.course_id AND cf.user_type='college' 
            WHERE $where 
            ORDER BY c.display_order, c.course_name", $params);
        ?>
        <section class="py-5" style="background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);">
            <div class="container text-center">
                <h1 class="fw-bold mb-0 text-primary display-5" style="color: #2c3e50 !important; letter-spacing: 2px; text-transform: uppercase;">
                    <?= htmlspecialchars($cat['name']) ?> - <?= htmlspecialchars($type) ?>
                </h1>
            </div>
        </section>
        
        <section class="py-5 bg-light" style="background-color: #f1f4f8 !important;">
            <div class="container">
                <div class="row">
                    <div class="col-12">
                        <?php if ($courses): ?>
                            <div class="card shadow-sm border-0 rounded-4 overflow-hidden">
                                <div class="table-responsive">
                                    <table class="table table-hover align-middle mb-0 bg-white">
                                        <thead class="bg-light">
                                            <tr>
                                                <th class="py-3 px-4 text-muted small text-uppercase fw-bold border-bottom-0">Code</th>
                                                <th class="py-3 text-muted small text-uppercase fw-bold border-bottom-0">Course Name</th>
                                                <th class="py-3 text-muted small text-uppercase fw-bold border-bottom-0">Type</th>
                                                <th class="py-3 text-muted small text-uppercase fw-bold border-bottom-0">Duration</th>
                                                <th class="py-3 text-muted small text-uppercase fw-bold border-bottom-0">Eligibility</th>
                                                <th class="py-3 px-4 text-end text-muted small text-uppercase fw-bold border-bottom-0">Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($courses as $c): ?>
                                            <tr class="align-middle course-table-row">
                                                <td class="px-4 py-3">
                                                    <span style="background-color: #f8f9fa; color: #495057; padding: 5px 10px; border-radius: 6px; font-weight: 600; font-size: 0.8rem; border: 1px solid #dee2e6; white-space: nowrap;">
                                                        <i class="fas fa-hashtag me-1 opacity-50"></i><?= htmlspecialchars($c['course_code'] ?? '') ?>
                                                    </span>
                                                </td>
                                                <td class="fw-bold text-dark fs-6 py-3"><?= htmlspecialchars($c['course_name'] ?? '') ?></td>
                                                <td class="py-3">
                                                    <span style="background-color: #e0e8ff; color: #0d6efd; padding: 5px 10px; border-radius: 6px; font-weight: 600; font-size: 0.8rem; border: 1px solid #b6ccfe; white-space: nowrap;">
                                                        <?= htmlspecialchars($c['course_type'] ?? '') ?>
                                                    </span>
                                                </td>
                                                <td class="text-muted py-3" style="font-size: 0.9rem; white-space: nowrap;">
                                                    <i class="fas fa-clock me-1 text-primary opacity-75"></i> <?= htmlspecialchars($c['duration_text'] ?? $c['duration'] ?? '') ?>
                                                </td>
                                                <td class="text-muted py-3" style="font-size: 0.9rem; white-space: nowrap;">
                                                    <i class="fas fa-graduation-cap me-1 text-primary opacity-75"></i> <?= htmlspecialchars($c['eligibility'] ?: '10th/12th Pass') ?>
                                                </td>
                                                <td class="px-4 text-end py-3">
                                                    <a href="course-detail.php?id=<?= $c['id'] ?>" class="btn btn-sm rounded-pill px-4 fw-bold shadow-sm text-white" style="background: linear-gradient(135deg, #6610f2, #0d6efd); border: none; letter-spacing: 0.5px;">View <i class="fas fa-arrow-right ms-1"></i></a>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        <?php else: ?>
                            <div class="text-center py-5 bg-white shadow-sm rounded-4">
                                <i class="fas fa-box-open fa-3x text-muted mb-3"></i>
                                <h4 class="text-muted">No courses available in this category yet.</h4>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </section>
        
        <style>
            .course-list-item {
                transition: all 0.2s ease;
            }
            .course-list-item:hover {
                background-color: #f8f9fa;
                transform: translateX(5px);
                border-left: 4px solid #0d6efd !important;
            }
        </style>
    <?php
    }
} else {
    // Show All Categories
    $isLive = false; try { $db->fetchOne("SELECT category_id FROM courses LIMIT 1"); $isLive = true; } catch(Exception $e) {}
    if ($isLive) {
        $categories = $db->fetchAll("SELECT * FROM course_categories WHERE is_active=1 AND EXISTS (SELECT 1 FROM courses c WHERE c.category_id = course_categories.id AND c.is_active = 1) ORDER BY display_order, name");
    } else {
        $categories = $db->fetchAll("SELECT * FROM course_categories WHERE is_active=1 AND EXISTS (SELECT 1 FROM courses c WHERE c.short_name COLLATE utf8mb4_unicode_ci = course_categories.name COLLATE utf8mb4_unicode_ci AND c.is_active = 1) ORDER BY display_order, name");
    }
?>
    <section class="py-5" style="background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);">
        <div class="container text-center">
            <h1 class="fw-bold mb-0 text-primary display-5" style="color: #2c3e50 !important; letter-spacing: 2px;">OUR DEPARTMENTS</h1>
        </div>
    </section>

    <section class="py-5 bg-light" style="background-color: #f1f4f8 !important;">
        <div class="container">
            <div class="row justify-content-center g-4">
                <?php foreach ($categories as $cat): 
                    $img = $cat['image'];
                    if (empty($img)) {
                        // Fallback image
                        $img = 'https://images.unsplash.com/photo-1513258496099-48168024adb0?w=600&q=80';
                    }
                ?>
                    <div class="col-lg-3 col-md-4 col-sm-6">
                        <a href="all-courses.php?category=<?= urlencode($cat['slug']) ?>" class="text-decoration-none">
                            <div class="image-course-card bg-white h-100 shadow-sm border border-light text-center p-2">
                                <div class="image-wrapper mb-3" style="height: 140px; overflow: hidden; background: #e9ecef;">
                                    <img src="<?= $img ?>" class="w-100 h-100 object-fit-cover" alt="<?= htmlspecialchars($cat['name']) ?>" style="clip-path: polygon(10% 0, 100% 0, 90% 100%, 0% 100%); transform: scale(1.1);">
                                </div>
                                <div class="card-title-wrapper px-2 pb-2">
                                    <h6 class="fw-bold text-dark mb-0" style="font-size: 0.85rem; letter-spacing: 0.5px; text-transform: uppercase;"><?= htmlspecialchars($cat['name']) ?></h6>
                                </div>
                            </div>
                        </a>
                    </div>
                <?php endforeach; ?>
                <?php if(!$categories): ?>
                    <div class="col-12 text-center py-5">
                        <h4 class="text-muted">No categories available yet.</h4>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </section>

    <style>
        .image-course-card {
            transition: all 0.3s ease;
            border-radius: 2px;
        }
        .image-course-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1) !important;
            border-color: #0d6efd !important;
        }
        .image-course-card img {
            transition: transform 0.5s ease;
        }
        .image-course-card:hover img {
            transform: scale(1.15) !important;
        }
    </style>
<?php
}

include 'includes/footer.php'; 
?>
