<?php
require("top.php");

// Handle Status Update (Active/Deactive)
if (isset($_GET['type']) && $_GET['type'] != '') {
    $type = mysqli_real_escape_string($con, $_GET['type']);
    if ($type == 'status') {
        $operation = mysqli_real_escape_string($con, $_GET['operation']);
        $id = mysqli_real_escape_string($con, $_GET['id']);
        $status = ($operation == 'active') ? '1' : '0';

        // Using prepared statement for status update
        $update_status_sql = "UPDATE course_title SET status = ? WHERE id = ?";
        if ($stmt = mysqli_prepare($con, $update_status_sql)) {
            mysqli_stmt_bind_param($stmt, "ii", $status, $id);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);
        }
    }

    // Handle Deletion of a Course
    if ($type == 'delete') { 
        $id = mysqli_real_escape_string($con, $_GET['id']);

        // Using prepared statement for course deletion
        $delete_sql = "DELETE FROM course_title WHERE id = ?";
        if ($stmt = mysqli_prepare($con, $delete_sql)) {
            mysqli_stmt_bind_param($stmt, "i", $id);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);
            echo "<script>alert('Course deleted successfully.');</script>";
            header("Location: course-title.php");
            exit();
        } else {
            echo "<script>alert('Error deleting course. Please try again.');</script>";
        }
    }
}

// Pagination logic
$limit = 10; // Number of courses per page
$page = isset($_GET['page']) ? $_GET['page'] : 1; // Get current page
$offset = ($page - 1) * $limit; // Calculate offset

// Initialize search query
$search_query = '';
if (isset($_GET['search']) && $_GET['search'] != '') {
    $search_query = mysqli_real_escape_string($con, $_GET['search']);
}

// Fetch total courses to calculate total pages
$sql = "SELECT COUNT(*) AS total FROM course_title WHERE title LIKE '%$search_query%'";
$result = mysqli_query($con, $sql);
$total_row = mysqli_fetch_assoc($result);
$total_courses = $total_row['total'];
$total_pages = ceil($total_courses / $limit);

// Fetch courses with pagination and search query
$sql = "SELECT * FROM course_title WHERE title LIKE '%$search_query%' ORDER BY id ASC LIMIT $limit OFFSET $offset";
$res = mysqli_prepare($con, $sql);
mysqli_stmt_execute($res);
$result = mysqli_stmt_get_result($res);
?>

<div class="container mt-4">
    <div class="card">
        <div class="card-body">
            <h4 class="text-center">Course List</h4>
            <h4 class="box-link"><a href="course_title_manage.php" class="btn btn-primary">Add Title</a></h4>

            <!-- Search Form -->
            <form method="get" class="mb-3">
                <div class="input-group">
                    <input type="text" name="search" class="form-control" placeholder="Search Courses" value="<?php echo htmlspecialchars($search_query); ?>">
                    <div class="input-group-append">
                        <button class="btn btn-primary" type="submit">Search</button>
                    </div>
                </div>
            </form>
        </div>

        <div class="table-responsive">
            <table class="table table-bordered table-striped">
                <thead>
                    <tr class="bg-primary text-white">
                        <th>#</th>
                        <th>Name</th>
                        <th>Status</th>
                        <th>Video Count</th>
                        <th>Date</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $i = $offset + 1; // Starting index for pagination
                    while ($row = mysqli_fetch_assoc($result)) { ?>
                    <tr>
                        <td><?php echo $i++ ?></td>
                        <td><?php echo $row['title'] ?></td>
                        <td>
                            <?php
                            if ($row['status'] == 1) {
                                echo "<a class='badge badge-success' href='?type=status&operation=deactive&id=".$row['id']."'>Active</a>&nbsp;";
                            } else {
                                echo "<a class='badge badge-warning' href='?type=status&operation=active&id=".$row['id']."'>Deactive</a>&nbsp;";
                            }
                            ?>
                        </td>
                        <td><?php echo $row['video_count'] ?></td>
                        <td><?php echo $row['created_at'] ?></td>
                        <td>
                            <a class='btn btn-info btn-sm text-white font-weight-bold' href='course_title_manage.php?id=<?php echo $row['id']; ?>'>
                                <i class='fa fa-edit'></i> Edit
                            </a> 
                            &nbsp;
                            <a class='btn btn-danger btn-sm text-white font-weight-bold' href="javascript:void(0);" onclick="confirmDelete(<?php echo $row['id']; ?>)">
                                <i class='fa fa-trash'></i> Delete
                            </a>
                        </td>
                    </tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination Links -->
        <div class="pagination">
            <?php if ($page > 1) { ?>
                <a href="?page=<?php echo $page - 1; ?>&search=<?php echo htmlspecialchars($search_query); ?>">Prev</a>
            <?php } ?>
            <?php for ($i = 1; $i <= $total_pages; $i++) { ?>
                <a href="?page=<?php echo $i; ?>&search=<?php echo htmlspecialchars($search_query); ?>" <?php if ($i == $page) echo 'style="background-color: #0066cc;"'; ?>>
                    <?php echo $i; ?>
                </a>
            <?php } ?>
            <?php if ($page < $total_pages) { ?>
                <a href="?page=<?php echo $page + 1; ?>&search=<?php echo htmlspecialchars($search_query); ?>">Next</a>
            <?php } ?>
        </div>
    </div>
</div>

<!-- Include Bootstrap and Font Awesome -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<script>
    // JavaScript function to confirm delete action
    function confirmDelete(id) {
        if (confirm("Are you sure you want to delete this course?")) {
            window.location.href = '?type=delete&id=' + id;
        }
    }
</script>

<style>
    /* Custom Styling */
    body {
        background-color: #f4f4f9;
        font-family: Arial, sans-serif;
    }

    .container {
        padding-left: 120px;
        padding-right: 5px;
        margin-left: auto;
        margin-right: auto;
    }

    .card {
        margin-top: 20px;
        max-width: 1200px; /* Optional: You can adjust this based on your content */
    }

    .box-link {
        text-align: center;
        margin-bottom: 20px;
    }

    .table th, .table td {
        text-align: center;
        vertical-align: middle;
    }

    .btn {
        margin-bottom: 15px;
    }

    .table-responsive {
        margin-top: 20px;
    }

    /* Pagination Styling */
    .pagination {
        text-align: center;
        margin-top: 20px;
    }

    .pagination a {
        margin: 0 5px;
        padding: 8px 12px;
        background-color: #0288d1;
        color: white;
        border-radius: 5px;
        text-decoration: none;
    }

    .pagination a:hover {
        background-color: #0066cc;
    }

    .pagination a[style="background-color: #0066cc;"] {
        background-color: #0066cc;
        color: white;
    }

    /* Make Table Responsive */
    @media (max-width: 768px) {
        .table-responsive {
            overflow-x: auto;
        }
    }

    /* Right to Left Adjustment */
    .container {
        direction: ltr;
    }
</style>

</body>
</html>
