<?php 
/**
 * Courses Management - Full CRUD Operations
 * Location: /public_html/college/mum_unu/course.php
 * Table: mum_courese (Mumbai University table)
 * DB: ../db.php (parent folder)
 * FIXED: Proper link paths and yellow active sidebar
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();

// Database connection from parent college folder
require_once '../db.php';

// Authentication check
if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit;
}

$college_id = isset($_SESSION['college_id']) ? (int)$_SESSION['college_id'] : 3;
$admin_name = isset($_SESSION['username']) ? $_SESSION['username'] : 'Admin';
$page_title = "Courses Management";
$current_page = basename($_SERVER['PHP_SELF']);

// ==================== CREATE - ADD NEW COURSE ====================
if (isset($_POST['add_course'])) {
    $course_name = mysqli_real_escape_string($db, $_POST['course_name']);
    $course_code = mysqli_real_escape_string($db, $_POST['course_code']);
    $course_type = mysqli_real_escape_string($db, $_POST['course_type']);
    $duration = mysqli_real_escape_string($db, $_POST['duration']);
    $fees = (float)$_POST['fees'];
    $fee_type = mysqli_real_escape_string($db, $_POST['fee_type']);
    $eligibility = mysqli_real_escape_string($db, $_POST['eligibility']);
    $description = mysqli_real_escape_string($db, $_POST['description']);
    $category = mysqli_real_escape_string($db, $_POST['category']);
    $department = mysqli_real_escape_string($db, $_POST['department']);
    $seats = (int)$_POST['seats'];
    $intake_year = mysqli_real_escape_string($db, $_POST['intake_year']);
    $status = mysqli_real_escape_string($db, $_POST['status']);
    $featured = isset($_POST['featured']) ? 1 : 0;

    // Handle course image upload
    $course_image = '';
    if (isset($_FILES['course_image']) && $_FILES['course_image']['error'] == 0) {
        $upload_dir = 'uploads/courses/';
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }

        $file_extension = pathinfo($_FILES['course_image']['name'], PATHINFO_EXTENSION);
        $file_name = 'course_' . time() . '_' . rand(1000, 9999) . '.' . $file_extension;
        $target_file = $upload_dir . $file_name;

        if (move_uploaded_file($_FILES['course_image']['tmp_name'], $target_file)) {
            $course_image = $target_file;
        }
    }

    // Handle syllabus PDF upload
    $syllabus_pdf = '';
    if (isset($_FILES['syllabus_pdf']) && $_FILES['syllabus_pdf']['error'] == 0) {
        $upload_dir = 'uploads/courses/pdfs/';
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }

        $file_extension = pathinfo($_FILES['syllabus_pdf']['name'], PATHINFO_EXTENSION);
        if (strtolower($file_extension) == 'pdf') {
            $file_name = 'syllabus_' . time() . '_' . rand(1000, 9999) . '.pdf';
            $target_file = $upload_dir . $file_name;

            if (move_uploaded_file($_FILES['syllabus_pdf']['tmp_name'], $target_file)) {
                $syllabus_pdf = $target_file;
            }
        }
    }

    $insert_query = "INSERT INTO mum_courese 
                     (course_name, course_code, course_type, duration, fees, fee_type, 
                      eligibility, description, category, department, seats, intake_year, 
                      course_image, syllabus_pdf, status, featured, created_at) 
                     VALUES 
                     ('$course_name', '$course_code', '$course_type', '$duration', $fees, '$fee_type',
                      '$eligibility', '$description', '$category', '$department', $seats, '$intake_year',
                      '$course_image', '$syllabus_pdf', '$status', $featured, NOW())";

    if (mysqli_query($db, $insert_query)) {
        header("Location: course.php?success=added");
        exit;
    } else {
        $error_message = "Error: " . mysqli_error($db);
    }
}

// ==================== UPDATE - EDIT COURSE ====================
if (isset($_POST['update_course'])) {
    $course_id = (int)$_POST['course_id'];
    $course_name = mysqli_real_escape_string($db, $_POST['course_name']);
    $course_code = mysqli_real_escape_string($db, $_POST['course_code']);
    $course_type = mysqli_real_escape_string($db, $_POST['course_type']);
    $duration = mysqli_real_escape_string($db, $_POST['duration']);
    $fees = (float)$_POST['fees'];
    $fee_type = mysqli_real_escape_string($db, $_POST['fee_type']);
    $eligibility = mysqli_real_escape_string($db, $_POST['eligibility']);
    $description = mysqli_real_escape_string($db, $_POST['description']);
    $category = mysqli_real_escape_string($db, $_POST['category']);
    $department = mysqli_real_escape_string($db, $_POST['department']);
    $seats = (int)$_POST['seats'];
    $intake_year = mysqli_real_escape_string($db, $_POST['intake_year']);
    $status = mysqli_real_escape_string($db, $_POST['status']);
    $featured = isset($_POST['featured']) ? 1 : 0;

    $update_query = "UPDATE mum_courese 
                     SET course_name = '$course_name',
                         course_code = '$course_code',
                         course_type = '$course_type',
                         duration = '$duration',
                         fees = $fees,
                         fee_type = '$fee_type',
                         eligibility = '$eligibility',
                         description = '$description',
                         category = '$category',
                         department = '$department',
                         seats = $seats,
                         intake_year = '$intake_year',
                         status = '$status',
                         featured = $featured";

    // Handle new image upload
    if (isset($_FILES['course_image']) && $_FILES['course_image']['error'] == 0) {
        $upload_dir = 'uploads/courses/';
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }

        $file_extension = pathinfo($_FILES['course_image']['name'], PATHINFO_EXTENSION);
        $file_name = 'course_' . time() . '_' . rand(1000, 9999) . '.' . $file_extension;
        $target_file = $upload_dir . $file_name;

        if (move_uploaded_file($_FILES['course_image']['tmp_name'], $target_file)) {
            // Delete old image
            $old_query = mysqli_query($db, "SELECT course_image FROM mum_courese WHERE id = $course_id");
            if ($old_row = mysqli_fetch_assoc($old_query)) {
                if (!empty($old_row['course_image']) && file_exists($old_row['course_image'])) {
                    unlink($old_row['course_image']);
                }
            }
            $update_query .= ", course_image = '$target_file'";
        }
    }

    // Handle new PDF upload
    if (isset($_FILES['syllabus_pdf']) && $_FILES['syllabus_pdf']['error'] == 0) {
        $upload_dir = 'uploads/courses/pdfs/';
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }

        $file_extension = pathinfo($_FILES['syllabus_pdf']['name'], PATHINFO_EXTENSION);
        if (strtolower($file_extension) == 'pdf') {
            $file_name = 'syllabus_' . time() . '_' . rand(1000, 9999) . '.pdf';
            $target_file = $upload_dir . $file_name;

            if (move_uploaded_file($_FILES['syllabus_pdf']['tmp_name'], $target_file)) {
                // Delete old PDF
                $old_query = mysqli_query($db, "SELECT syllabus_pdf FROM mum_courese WHERE id = $course_id");
                if ($old_row = mysqli_fetch_assoc($old_query)) {
                    if (!empty($old_row['syllabus_pdf']) && file_exists($old_row['syllabus_pdf'])) {
                        unlink($old_row['syllabus_pdf']);
                    }
                }
                $update_query .= ", syllabus_pdf = '$target_file'";
            }
        }
    }

    $update_query .= " WHERE id = $course_id";

    if (mysqli_query($db, $update_query)) {
        header("Location: course.php?success=updated");
        exit;
    } else {
        $error_message = "Error: " . mysqli_error($db);
    }
}

// ==================== DELETE - REMOVE COURSE ====================
if (isset($_GET['delete_id'])) {
    $delete_id = (int)$_GET['delete_id'];

    // Get files before deleting
    $get_files = mysqli_query($db, "SELECT course_image, syllabus_pdf FROM mum_courese WHERE id = $delete_id");
    if ($row = mysqli_fetch_assoc($get_files)) {
        if (!empty($row['course_image']) && file_exists($row['course_image'])) {
            unlink($row['course_image']);
        }
        if (!empty($row['syllabus_pdf']) && file_exists($row['syllabus_pdf'])) {
            unlink($row['syllabus_pdf']);
        }
    }

    $delete_query = "DELETE FROM mum_courese WHERE id = $delete_id";
    if (mysqli_query($db, $delete_query)) {
        header("Location: course.php?success=deleted");
        exit;
    } else {
        header("Location: course.php?error=delete_failed");
        exit;
    }
}

// ==================== TOGGLE FEATURED ====================
if (isset($_GET['toggle_featured'])) {
    $course_id = (int)$_GET['toggle_featured'];
    $toggle_query = "UPDATE mum_courese SET featured = IF(featured = 1, 0, 1) WHERE id = $course_id";
    mysqli_query($db, $toggle_query);
    header("Location: course.php");
    exit;
}

// ==================== READ - GET ALL COURSES ====================
$filter = isset($_GET['filter']) ? $_GET['filter'] : 'all';
$search = isset($_GET['search']) ? mysqli_real_escape_string($db, $_GET['search']) : '';

$where_clause = "WHERE 1=1";

if ($filter != 'all') {
    $where_clause .= " AND category = '$filter'";
}

if (!empty($search)) {
    $where_clause .= " AND (course_name LIKE '%$search%' OR course_code LIKE '%$search%' OR department LIKE '%$search%')";
}

$courses_query = "SELECT * FROM mum_courese $where_clause ORDER BY featured DESC, id DESC";
$courses_result = mysqli_query($db, $courses_query);
$total_courses = $courses_result ? mysqli_num_rows($courses_result) : 0;

// Get course for editing
$edit_course = null;
if (isset($_GET['edit_id'])) {
    $edit_id = (int)$_GET['edit_id'];
    $edit_query = "SELECT * FROM mum_courese WHERE id = $edit_id";
    $edit_result = mysqli_query($db, $edit_query);
    $edit_course = mysqli_fetch_assoc($edit_result);
}

// Get categories for filter
$categories_query = "SELECT DISTINCT category FROM mum_courese WHERE category IS NOT NULL AND category != '' ORDER BY category";
$categories_result = mysqli_query($db, $categories_query);

// Success/Error messages
$success_message = '';
$error_message = '';

if (isset($_GET['success'])) {
    switch ($_GET['success']) {
        case 'added':
            $success_message = "Course added successfully!";
            break;
        case 'updated':
            $success_message = "Course updated successfully!";
            break;
        case 'deleted':
            $success_message = "Course deleted successfully!";
            break;
    }
}

if (isset($_GET['error'])) {
    $error_message = "An error occurred. Please try again.";
}

// Include header if exists
if (file_exists('header.php')) {
    require_once 'header.php';
} else {
    echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Courses Management - Mumbai University</title></head><body>';
}
?>

<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #f5f6fa; color: #2c3e50; }
.sidebar { position: fixed; left: 0; top: 0; width: 260px; height: 100vh; background: linear-gradient(180deg, #2c3e50 0%, #34495e 100%); color: white; padding: 20px 0; overflow-y: auto; z-index: 1000; box-shadow: 2px 0 10px rgba(0,0,0,0.1); }
.sidebar-header { padding: 20px; border-bottom: 1px solid rgba(255,255,255,0.1); margin-bottom: 20px; }
.sidebar-header h2 { font-size: 1.3em; font-weight: 600; }
.sidebar-menu { padding: 0 10px; }
.menu-item { display: block; padding: 12px 20px; color: #ecf0f1; text-decoration: none; border-radius: 8px; margin-bottom: 5px; transition: all 0.3s ease; font-size: 0.95em; }
.menu-item:hover { background: rgba(255,255,255,0.1); padding-left: 25px; }
.menu-item.active { background: linear-gradient(135deg, #f39c12 0%, #f1c40f 100%); font-weight: 600; color: #000; box-shadow: 0 4px 15px rgba(243, 156, 18, 0.4); }
.main-content-area { margin-left: 260px; padding: 30px; min-height: 100vh; }
.page-header { background: white; padding: 25px 30px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 30px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px; }
.page-header h2 { color: #2c3e50; font-size: 1.8em; }
.btn-add { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px 25px; border-radius: 8px; text-decoration: none; font-weight: 600; transition: all 0.3s ease; border: none; cursor: pointer; }
.btn-add:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.2); }
.search-filter-bar { background: white; padding: 20px 30px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 30px; display: flex; gap: 15px; flex-wrap: wrap; }
.search-box { flex: 1; min-width: 250px; }
.search-box input { width: 100%; padding: 10px 15px; border: 1px solid #ddd; border-radius: 8px; font-size: 0.95em; }
.filter-box select { padding: 10px 15px; border: 1px solid #ddd; border-radius: 8px; font-size: 0.95em; min-width: 180px; }
.btn-search { background: #3498db; color: white; padding: 10px 25px; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; }
.alert { padding: 15px 20px; border-radius: 8px; margin-bottom: 20px; font-weight: 500; }
.alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
.alert-error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
.form-container { background: white; padding: 30px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 30px; display: none; }
.form-container.show { display: block; }
.form-container h3 { margin-bottom: 25px; color: #2c3e50; font-size: 1.4em; }
.form-row { display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; margin-bottom: 20px; }
.form-row-3 { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-bottom: 20px; }
.form-group { margin-bottom: 20px; }
.form-group.full-width { grid-column: 1 / -1; }
.form-group label { display: block; margin-bottom: 8px; font-weight: 600; color: #2c3e50; font-size: 0.95em; }
.form-control { width: 100%; padding: 12px 15px; border: 1px solid #ddd; border-radius: 8px; font-size: 1em; transition: border 0.3s ease; }
.form-control:focus { outline: none; border-color: #667eea; box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); }
textarea.form-control { resize: vertical; min-height: 100px; }
.checkbox-label { display: flex; align-items: center; gap: 10px; font-weight: normal; cursor: pointer; }
.checkbox-label input[type="checkbox"] { width: 20px; height: 20px; cursor: pointer; }
.btn-submit { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white; padding: 12px 30px; border: none; border-radius: 8px; font-size: 1em; font-weight: 600; cursor: pointer; transition: all 0.3s ease; }
.btn-submit:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.2); }
.btn-cancel { background: #95a5a6; color: white; padding: 12px 30px; border: none; border-radius: 8px; font-size: 1em; font-weight: 600; cursor: pointer; transition: all 0.3s ease; text-decoration: none; display: inline-block; margin-left: 10px; }
.btn-cancel:hover { background: #7f8c8d; }
.courses-container { background: white; padding: 30px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
.courses-container h3 { margin-bottom: 25px; color: #2c3e50; font-size: 1.4em; }
.courses-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(350px, 1fr)); gap: 25px; }
.course-card { background: white; border: 1px solid #e9ecef; border-radius: 12px; overflow: hidden; transition: all 0.3s ease; position: relative; }
.course-card:hover { transform: translateY(-5px); box-shadow: 0 5px 20px rgba(0,0,0,0.1); }
.course-image { width: 100%; height: 200px; object-fit: cover; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.course-badge { position: absolute; top: 15px; right: 15px; background: #ffc107; color: #000; padding: 5px 15px; border-radius: 20px; font-size: 0.85em; font-weight: 600; }
.course-content { padding: 20px; }
.course-type { display: inline-block; background: #e3f2fd; color: #1976d2; padding: 4px 12px; border-radius: 15px; font-size: 0.8em; font-weight: 600; margin-bottom: 10px; }
.course-title { font-size: 1.2em; color: #2c3e50; margin-bottom: 5px; font-weight: 600; }
.course-code { color: #7f8c8d; font-size: 0.9em; margin-bottom: 15px; }
.course-details { margin: 15px 0; padding: 15px 0; border-top: 1px solid #e9ecef; border-bottom: 1px solid #e9ecef; }
.course-detail-item { display: flex; justify-content: space-between; margin-bottom: 10px; font-size: 0.9em; }
.course-detail-item:last-child { margin-bottom: 0; }
.detail-label { color: #7f8c8d; }
.detail-value { font-weight: 600; color: #2c3e50; }
.course-description { color: #555; font-size: 0.9em; line-height: 1.6; margin: 15px 0; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
.course-footer { display: flex; justify-content: space-between; align-items: center; padding-top: 15px; border-top: 1px solid #e9ecef; }
.course-status { padding: 5px 12px; border-radius: 15px; font-size: 0.85em; font-weight: 600; }
.status-active { background: #d4edda; color: #155724; }
.status-inactive { background: #f8d7da; color: #721c24; }
.course-actions { display: flex; gap: 8px; }
.btn-action { padding: 6px 12px; border-radius: 6px; text-decoration: none; font-size: 0.85em; font-weight: 500; transition: all 0.3s ease; }
.btn-view { background: #17a2b8; color: white; }
.btn-edit { background: #3498db; color: white; }
.btn-delete { background: #e74c3c; color: white; }
.btn-featured { background: #ffc107; color: #000; }
.btn-action:hover { transform: translateY(-2px); box-shadow: 0 3px 10px rgba(0,0,0,0.2); }
.no-data { text-align: center; padding: 60px 20px; color: #7f8c8d; }
.no-data-icon { font-size: 4em; margin-bottom: 20px; }
@media (max-width: 768px) {
    .sidebar { width: 100%; height: auto; position: relative; }
    .main-content-area { margin-left: 0; padding: 15px; }
    .page-header { flex-direction: column; text-align: center; }
    .search-filter-bar { flex-direction: column; }
    .form-row, .form-row-3 { grid-template-columns: 1fr; }
    .courses-grid { grid-template-columns: 1fr; }
}
</style>

<!-- SIDEBAR -->
<div class="sidebar">
    <div class="sidebar-header">
        <h2>🎓 Mumbai University</h2>
    </div>
    <nav class="sidebar-menu">
        <a href="dashboard1.php" class="menu-item <?php echo $current_page == 'dashboard1.php' ? 'active' : ''; ?>">🏠 Dashboard</a>
        <a href="course.php" class="menu-item <?php echo $current_page == 'course.php' ? 'active' : ''; ?>">📚 Courses</a>
        <a href="teacher.php" class="menu-item <?php echo $current_page == 'teacher.php' ? 'active' : ''; ?>">👨‍🏫 Teachers</a>
        <a href="complaint.php" class="menu-item <?php echo ($current_page == 'complaint.php') ? 'active' : ''; ?>">📝 Complaints</a>
        <a href="Gallery.php" class="menu-item <?php echo $current_page == 'Gallery.php' ? 'active' : ''; ?>">🖼️ Gallery</a>
        <a href="Contact.php" class="menu-item <?php echo $current_page == 'Contact.php' ? 'active' : ''; ?>">📧 Contact</a>
        <a href="../logout.php" class="menu-item <?php echo ($current_page == 'logout.php') ? 'active' : ''; ?>">🚪 Logout</a>
    </nav>
</div>

<!-- MAIN CONTENT -->
<div class="main-content-area">

    <div class="page-header">
        <h2>📚 Courses Management (<?php echo $total_courses; ?>)</h2>
        <?php if (!isset($_GET['edit_id'])): ?>
            <button class="btn-add" onclick="toggleForm('add-form')">➕ Add New Course</button>
        <?php endif; ?>
    </div>

    <?php if (!empty($success_message)): ?>
        <div class="alert alert-success">✓ <?php echo $success_message; ?></div>
    <?php endif; ?>

    <?php if (!empty($error_message)): ?>
        <div class="alert alert-error">✗ <?php echo $error_message; ?></div>
    <?php endif; ?>

    <?php if (!$edit_course && !isset($_GET['edit_id'])): ?>
    <div class="search-filter-bar">
        <form method="GET" style="display: flex; gap: 15px; flex: 1; flex-wrap: wrap;">
            <div class="search-box">
                <input type="text" name="search" placeholder="🔍 Search courses..." value="<?php echo htmlspecialchars($search); ?>">
            </div>
            <div class="filter-box">
                <select name="filter" onchange="this.form.submit()">
                    <option value="all">All Categories</option>
                    <?php 
                    if ($categories_result && mysqli_num_rows($categories_result) > 0):
                        mysqli_data_seek($categories_result, 0);
                        while ($cat = mysqli_fetch_assoc($categories_result)): 
                            if (!empty($cat['category'])):
                    ?>
                        <option value="<?php echo htmlspecialchars($cat['category']); ?>" <?php echo $filter == $cat['category'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($cat['category']); ?>
                        </option>
                    <?php 
                            endif;
                        endwhile;
                    endif;
                    ?>
                </select>
            </div>
            <button type="submit" class="btn-search">Search</button>
            <?php if (!empty($search) || $filter != 'all'): ?>
                <a href="course.php" class="btn-cancel" style="padding: 10px 20px; margin: 0;">Clear</a>
            <?php endif; ?>
        </form>
    </div>
    <?php endif; ?>

    <div class="form-container <?php echo $edit_course ? 'show' : ''; ?>" id="add-form">
        <h3><?php echo $edit_course ? '✏️ Edit Course' : '➕ Add New Course'; ?></h3>
        <form method="POST" enctype="multipart/form-data">

            <?php if ($edit_course): ?>
                <input type="hidden" name="course_id" value="<?php echo $edit_course['id']; ?>">
            <?php endif; ?>

            <div class="form-row">
                <div class="form-group">
                    <label>Course Name *</label>
                    <input type="text" name="course_name" class="form-control" required 
                           value="<?php echo $edit_course ? htmlspecialchars($edit_course['course_name']) : ''; ?>" 
                           placeholder="e.g. Bachelor of Computer Applications">
                </div>

                <div class="form-group">
                    <label>Course Code</label>
                    <input type="text" name="course_code" class="form-control" 
                           value="<?php echo $edit_course ? htmlspecialchars($edit_course['course_code']) : ''; ?>" 
                           placeholder="e.g. BCA-001">
                </div>
            </div>

            <div class="form-row-3">
                <div class="form-group">
                    <label>Course Type *</label>
                    <select name="course_type" class="form-control" required>
                        <option value="UG" <?php echo ($edit_course && $edit_course['course_type'] == 'UG') ? 'selected' : ''; ?>>Under Graduate (UG)</option>
                        <option value="PG" <?php echo ($edit_course && $edit_course['course_type'] == 'PG') ? 'selected' : ''; ?>>Post Graduate (PG)</option>
                        <option value="Diploma" <?php echo ($edit_course && $edit_course['course_type'] == 'Diploma') ? 'selected' : ''; ?>>Diploma</option>
                        <option value="Certificate" <?php echo ($edit_course && $edit_course['course_type'] == 'Certificate') ? 'selected' : ''; ?>>Certificate</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>Duration</label>
                    <input type="text" name="duration" class="form-control" 
                           value="<?php echo $edit_course ? htmlspecialchars($edit_course['duration']) : ''; ?>" 
                           placeholder="e.g. 3 Years">
                </div>

                <div class="form-group">
                    <label>Intake Year</label>
                    <input type="text" name="intake_year" class="form-control" 
                           value="<?php echo $edit_course ? htmlspecialchars($edit_course['intake_year']) : date('Y'); ?>" 
                           placeholder="e.g. 2026">
                </div>
            </div>

            <div class="form-row-3">
                <div class="form-group">
                    <label>Fees (₹)</label>
                    <input type="number" name="fees" class="form-control" step="0.01"
                           value="<?php echo $edit_course ? $edit_course['fees'] : ''; ?>" 
                           placeholder="e.g. 85000">
                </div>

                <div class="form-group">
                    <label>Fee Type</label>
                    <select name="fee_type" class="form-control">
                        <option value="Per Year" <?php echo ($edit_course && $edit_course['fee_type'] == 'Per Year') ? 'selected' : ''; ?>>Per Year</option>
                        <option value="Per Semester" <?php echo ($edit_course && $edit_course['fee_type'] == 'Per Semester') ? 'selected' : ''; ?>>Per Semester</option>
                        <option value="Total" <?php echo ($edit_course && $edit_course['fee_type'] == 'Total') ? 'selected' : ''; ?>>Total Course Fee</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>Available Seats</label>
                    <input type="number" name="seats" class="form-control" 
                           value="<?php echo $edit_course ? $edit_course['seats'] : ''; ?>" 
                           placeholder="e.g. 60">
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label>Category *</label>
                    <input type="text" name="category" class="form-control" required 
                           value="<?php echo $edit_course ? htmlspecialchars($edit_course['category']) : ''; ?>" 
                           placeholder="e.g. Computer Science">
                </div>

                <div class="form-group">
                    <label>Department</label>
                    <input type="text" name="department" class="form-control" 
                           value="<?php echo $edit_course ? htmlspecialchars($edit_course['department']) : ''; ?>" 
                           placeholder="e.g. IT Department">
                </div>
            </div>

            <div class="form-group full-width">
                <label>Eligibility Criteria</label>
                <textarea name="eligibility" class="form-control" placeholder="Enter eligibility requirements..."><?php echo $edit_course ? htmlspecialchars($edit_course['eligibility']) : ''; ?></textarea>
            </div>

            <div class="form-group full-width">
                <label>Course Description</label>
                <textarea name="description" class="form-control" rows="4" placeholder="Enter detailed course description..."><?php echo $edit_course ? htmlspecialchars($edit_course['description']) : ''; ?></textarea>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label>Course Image</label>
                    <input type="file" name="course_image" class="form-control" accept="image/*">
                    <small style="color: #7f8c8d;">Recommended: 800x600 pixels</small>
                    <?php if ($edit_course && !empty($edit_course['course_image'])): ?>
                        <div style="margin-top: 10px;">
                            <img src="<?php echo htmlspecialchars($edit_course['course_image']); ?>" 
                                 style="width: 120px; height: 80px; object-fit: cover; border-radius: 8px;">
                        </div>
                    <?php endif; ?>
                </div>

                <div class="form-group">
                    <label>Syllabus PDF</label>
                    <input type="file" name="syllabus_pdf" class="form-control" accept=".pdf">
                    <small style="color: #7f8c8d;">Upload course syllabus (PDF only)</small>
                    <?php if ($edit_course && !empty($edit_course['syllabus_pdf'])): ?>
                        <div style="margin-top: 10px;">
                            <a href="<?php echo htmlspecialchars($edit_course['syllabus_pdf']); ?>" target="_blank" 
                               style="color: #3498db;">📄 View Current Syllabus</a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label>Status</label>
                    <select name="status" class="form-control">
                        <option value="active" <?php echo ($edit_course && $edit_course['status'] == 'active') ? 'selected' : ''; ?>>Active</option>
                        <option value="inactive" <?php echo ($edit_course && $edit_course['status'] == 'inactive') ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                </div>

                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="featured" value="1" <?php echo ($edit_course && $edit_course['featured']) ? 'checked' : ''; ?>>
                        <span>⭐ Mark as Featured Course</span>
                    </label>
                </div>
            </div>

            <div style="margin-top: 30px;">
                <button type="submit" name="<?php echo $edit_course ? 'update_course' : 'add_course'; ?>" class="btn-submit">
                    <?php echo $edit_course ? '💾 Update Course' : '➕ Add Course'; ?>
                </button>
                <?php if ($edit_course): ?>
                    <a href="course.php" class="btn-cancel">✕ Cancel</a>
                <?php else: ?>
                    <button type="button" class="btn-cancel" onclick="toggleForm('add-form')">✕ Cancel</button>
                <?php endif; ?>
            </div>
        </form>
    </div>

    <div class="courses-container">
        <h3>📋 All Courses</h3>

        <?php if ($total_courses > 0): ?>
            <div class="courses-grid">
                <?php 
                mysqli_data_seek($courses_result, 0);
                while ($course = mysqli_fetch_assoc($courses_result)): 
                ?>
                    <div class="course-card">
                        <?php if (!empty($course['course_image']) && file_exists($course['course_image'])): ?>
                            <img src="<?php echo htmlspecialchars($course['course_image']); ?>" 
                                 alt="Course" class="course-image">
                        <?php else: ?>
                            <div class="course-image" style="display: flex; align-items: center; justify-content: center; color: white; font-size: 3em;">
                                📚
                            </div>
                        <?php endif; ?>

                        <?php if ($course['featured']): ?>
                            <div class="course-badge">⭐ Featured</div>
                        <?php endif; ?>

                        <div class="course-content">
                            <span class="course-type"><?php echo htmlspecialchars($course['course_type']); ?></span>
                            <h4 class="course-title"><?php echo htmlspecialchars($course['course_name']); ?></h4>
                            <?php if (!empty($course['course_code'])): ?>
                                <div class="course-code">Code: <?php echo htmlspecialchars($course['course_code']); ?></div>
                            <?php endif; ?>

                            <div class="course-details">
                                <?php if (!empty($course['duration'])): ?>
                                <div class="course-detail-item">
                                    <span class="detail-label">Duration:</span>
                                    <span class="detail-value"><?php echo htmlspecialchars($course['duration']); ?></span>
                                </div>
                                <?php endif; ?>

                                <?php if (!empty($course['fees'])): ?>
                                <div class="course-detail-item">
                                    <span class="detail-label">Fees:</span>
                                    <span class="detail-value">₹<?php echo number_format($course['fees'], 0); ?> <?php echo $course['fee_type']; ?></span>
                                </div>
                                <?php endif; ?>

                                <?php if (!empty($course['seats'])): ?>
                                <div class="course-detail-item">
                                    <span class="detail-label">Seats:</span>
                                    <span class="detail-value"><?php echo $course['seats']; ?> Available</span>
                                </div>
                                <?php endif; ?>

                                <?php if (!empty($course['category'])): ?>
                                <div class="course-detail-item">
                                    <span class="detail-label">Category:</span>
                                    <span class="detail-value"><?php echo htmlspecialchars($course['category']); ?></span>
                                </div>
                                <?php endif; ?>
                            </div>

                            <?php if (!empty($course['description'])): ?>
                                <div class="course-description">
                                    <?php echo htmlspecialchars($course['description']); ?>
                                </div>
                            <?php endif; ?>

                            <div class="course-footer">
                                <span class="course-status status-<?php echo $course['status']; ?>">
                                    <?php echo ucfirst($course['status']); ?>
                                </span>
                                <div class="course-actions">
                                    <?php if (!empty($course['syllabus_pdf']) && file_exists($course['syllabus_pdf'])): ?>
                                        <a href="<?php echo htmlspecialchars($course['syllabus_pdf']); ?>" 
                                           target="_blank" class="btn-action btn-view" title="View Syllabus">
                                            📄
                                        </a>
                                    <?php endif; ?>
                                    <a href="?toggle_featured=<?php echo $course['id']; ?>" 
                                       class="btn-action btn-featured" title="Toggle Featured">
                                        ⭐
                                    </a>
                                    <a href="?edit_id=<?php echo $course['id']; ?>" 
                                       class="btn-action btn-edit" title="Edit Course">
                                        ✏️
                                    </a>
                                    <a href="?delete_id=<?php echo $course['id']; ?>" 
                                       class="btn-action btn-delete"
                                       onclick="return confirm('Are you sure you want to delete this course?')"
                                       title="Delete Course">
                                        🗑️
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endwhile; ?>
            </div>
        <?php else: ?>
            <div class="no-data">
                <div class="no-data-icon">📚</div>
                <p style="font-size: 1.2em; font-weight: 600;">No courses found</p>
                <p style="margin-top: 10px;">Click "Add New Course" button above to create your first course!</p>
            </div>
        <?php endif; ?>

    </div>

</div>

<script>
function toggleForm(formId) {
    const form = document.getElementById(formId);
    if (form) {
        if (form.classList.contains('show')) {
            form.classList.remove('show');
        } else {
            form.classList.add('show');
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    }
}

setTimeout(function() {
    const alerts = document.querySelectorAll('.alert');
    alerts.forEach(function(alert) {
        alert.style.transition = 'opacity 0.5s ease';
        alert.style.opacity = '0';
        setTimeout(function() {
            alert.remove();
        }, 500);
    });
}, 5000);
</script>

<?php 
if (file_exists('footer.php')) {
    require_once 'footer.php';
} else {
    echo '</body></html>';
}
?>
