<?php
// manage_courses.php
// Course Management Page with Search, Pagination, Edit, and Delete options.

// Ensure session is started.
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Ensure user is logged in and has the necessary role (e.g., admin or instructor).
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_role'] !== 'instructor')) {
    header("Location: index.php?page=login");
    exit();
}

require_once 'config/database.php';

$message = '';
$is_error = false;

// --- Pagination & Search Logic ---
$records_per_page = 10;
$current_page = isset($_GET['p']) && is_numeric($_GET['p']) ? (int)$_GET['p'] : 1;
$offset = ($current_page - 1) * $records_per_page;

$search_query = isset($_GET['search']) ? trim($_GET['search']) : '';
$search_param = '%' . $search_query . '%';

$sql_count = "SELECT COUNT(*) FROM courses WHERE course_name LIKE ?";
$sql_courses = "SELECT id, course_name, created_at, image_path FROM courses WHERE course_name LIKE ? ORDER BY created_at DESC LIMIT ? OFFSET ?";

try {
    // Get total number of courses for pagination
    $stmt_count = $pdo->prepare($sql_count);
    $stmt_count->execute([$search_param]);
    $total_records = $stmt_count->fetchColumn();
    $total_pages = ceil($total_records / $records_per_page);

    // Fetch courses for the current page
    $stmt_courses = $pdo->prepare($sql_courses);
    $stmt_courses->bindValue(1, $search_param, PDO::PARAM_STR);
    $stmt_courses->bindValue(2, $records_per_page, PDO::PARAM_INT);
    $stmt_courses->bindValue(3, $offset, PDO::PARAM_INT);
    $stmt_courses->execute();
    $courses = $stmt_courses->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    $message = "Database error: " . $e->getMessage();
    $is_error = true;
    error_log("Course Management Fetch Error: " . $e->getMessage());
    $courses = [];
}

?>

<div class="w-full max-w-7xl mx-auto p-6 bg-white rounded-lg shadow-xl">
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-3xl font-extrabold text-gray-900">Manage Courses</h1>
        <a href="index.php?page=create_course" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition duration-300">
            <i class="fas fa-plus-circle mr-2"></i> Add New Course
        </a>
    </div>

    <?php if (!empty($message)): ?>
        <div class="mb-6 p-4 rounded-md text-center text-lg <?php echo $is_error ? 'bg-red-100 text-red-700' : 'bg-blue-50 text-blue-700'; ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>

    <div class="mb-6">
        <form action="index.php" method="GET" class="flex items-center space-x-2">
            <input type="hidden" name="page" value="manage_courses">
            <input type="text" name="search" placeholder="Search by course name..." value="<?php echo htmlspecialchars($search_query); ?>" class="flex-grow p-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            <button type="submit" class="bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300 transition duration-300">
                <i class="fas fa-search"></i> Search
            </button>
        </form>
    </div>

    <div class="overflow-x-auto shadow-lg rounded-lg">
        <table class="min-w-full bg-white border border-gray-200">
            <thead>
                <tr class="bg-gray-100 text-gray-600 uppercase text-sm leading-normal">
                    <th class="py-3 px-6 text-left">Course Name</th>
                    <th class="py-3 px-6 text-left">Image</th>
                    <th class="py-3 px-6 text-center">Created At</th>
                    <th class="py-3 px-6 text-center">Actions</th>
                </tr>
            </thead>
            <tbody class="text-gray-600 text-sm font-light">
                <?php if (!empty($courses)): ?>
                    <?php foreach ($courses as $course): ?>
                        <tr class="border-b border-gray-200 hover:bg-gray-50">
                            <td class="py-3 px-6 text-left whitespace-nowrap">
                                <span class="font-medium"><?php echo htmlspecialchars($course['course_name']); ?></span>
                            </td>
                            <td class="py-3 px-6 text-left">
                                <?php if (!empty($course['image_path'])): ?>
                                    <img src="<?php echo htmlspecialchars($course['image_path']); ?>" alt="Course Image" class="w-16 h-16 rounded object-cover">
                                <?php else: ?>
                                    <span class="text-gray-400">No Image</span>
                                <?php endif; ?>
                            </td>
                            <td class="py-3 px-6 text-center">
                                <?php echo date('M d, Y', strtotime($course['created_at'])); ?>
                            </td>
                            <td class="py-3 px-6 text-center">
                                <div class="flex item-center justify-center space-x-2">
                                    <a href="index.php?page=edit_course&id=<?php echo htmlspecialchars($course['id']); ?>" class="w-8 h-8 flex items-center justify-center rounded-full bg-yellow-100 text-yellow-600 hover:bg-yellow-200 transition duration-300" title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="delete_course.php?id=<?php echo htmlspecialchars($course['id']); ?>" onclick="return confirm('Are you sure you want to delete this course? This action is irreversible.');" class="w-8 h-8 flex items-center justify-center rounded-full bg-red-100 text-red-600 hover:bg-red-200 transition duration-300" title="Delete">
                                        <i class="fas fa-trash-alt"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="4" class="py-6 text-center text-gray-500">
                            No courses found.
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php if ($total_pages > 1): ?>
        <div class="flex justify-center mt-6 space-x-2">
            <?php if ($current_page > 1): ?>
                <a href="index.php?page=manage_courses&p=<?php echo $current_page - 1; ?><?php echo !empty($search_query) ? '&search=' . urlencode($search_query) : ''; ?>" class="bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300">Previous</a>
            <?php endif; ?>

            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                <a href="index.php?page=manage_courses&p=<?php echo $i; ?><?php echo !empty($search_query) ? '&search=' . urlencode($search_query) : ''; ?>" class="px-4 py-2 rounded-lg <?php echo ($i === $current_page) ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-700 hover:bg-gray-300'; ?>">
                    <?php echo $i; ?>
                </a>
            <?php endfor; ?>

            <?php if ($current_page < $total_pages): ?>
                <a href="index.php?page=manage_courses&p=<?php echo $current_page + 1; ?><?php echo !empty($search_query) ? '&search=' . urlencode($search_query) : ''; ?>" class="bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300">Next</a>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>