<?php
session_start();
require("../dbconnect.php"); 

// ✅ Check if Admin is Logged in
if (!isset($_SESSION['ADMIN_LOGIN']) || $_SESSION['ADMIN_LOGIN'] != 'yes') {
    header("Location: index.php");
    exit;
}

// ✅ Handle Status Change (Activate/Deactivate)
if (isset($_GET['type']) && $_GET['type'] == 'status') {
    $id = mysqli_real_escape_string($con, $_GET['id']);
    $operation = mysqli_real_escape_string($con, $_GET['operation']);

    // Set status based on operation (active or inactive)
    $status = ($operation == 'active') ? 1 : 0;

    // Update the status in the database
    $update_sql = "UPDATE user_video_access SET status = ? WHERE id = ?";
    $stmt = $con->prepare($update_sql);
    $stmt->bind_param("ii", $status, $id);
    if ($stmt->execute()) {
        // Redirect to the same page after updating
        header("Location: manage_video_access.php");
        exit;
    } else {
        echo "Error: " . mysqli_error($con);
    }
}

// ✅ Handle Deactivate Selected Users
if (isset($_POST['deactivate_selected'])) {
    if (isset($_POST['user_ids'])) {
        $user_ids = $_POST['user_ids'];

        // Create a list of IDs to deactivate
        $ids = implode(",", $user_ids);
        $deactivate_sql = "UPDATE user_video_access SET status = 0 WHERE id IN ($ids)";
        if (mysqli_query($con, $deactivate_sql)) {
            header("Location: manage_video_access.php");
            exit;
        } else {
            echo "Error: " . mysqli_error($con);
        }
    }
}

// ✅ Handle Activate All Users
if (isset($_POST['activate_all'])) {
    // Update all users' status to active
    $activate_sql = "UPDATE user_video_access SET status = 1";
    if (mysqli_query($con, $activate_sql)) {
        header("Location: manage_video_access.php");
        exit;
    } else {
        echo "Error: " . mysqli_error($con);
    }
}

// ✅ Handle User Search
$search_term = '';
if (isset($_POST['search'])) {
    $search_term = mysqli_real_escape_string($con, $_POST['search_term']);
}

// ✅ Pagination
$limit = 10;  // Number of records per page
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;  // Current page
$offset = ($page - 1) * $limit;  // Calculate offset for SQL query

// ✅ Fetch Users based on Search Term with Pagination
$query = "SELECT user_video_access.id, user_register.username, course_video.video_title, user_video_access.status 
          FROM user_video_access
          JOIN user_register ON user_video_access.user_id = user_register.id
          JOIN course_video ON user_video_access.video_id = course_video.id
          WHERE user_register.username LIKE '%$search_term%'
          ORDER BY user_video_access.id DESC
          LIMIT $limit OFFSET $offset";

$result = mysqli_query($con, $query);

// ✅ Fetch Total Record Count for Pagination
$total_query = "SELECT COUNT(*) as total FROM user_video_access
                JOIN user_register ON user_video_access.user_id = user_register.id
                WHERE user_register.username LIKE '%$search_term%'";
$total_result = mysqli_query($con, $total_query);
$total_row = mysqli_fetch_assoc($total_result);
$total_records = $total_row['total'];
$total_pages = ceil($total_records / $limit);  // Calculate total pages

?>

<?php include('top.php'); ?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Video Access</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <h2 class="text-center text-primary">Manage Video Access</h2>

        <!-- Search Form -->
        <form method="POST" class="mb-4">
            <div class="input-group">
                <input type="text" name="search_term" class="form-control" placeholder="Search by Username" value="<?php echo htmlspecialchars($search_term); ?>">
                <button type="submit" name="search" class="btn btn-primary">Search</button>
            </div>
        </form>

        <!-- Form to Deactivate Selected Users and Activate All Users -->
        <form method="POST" action="">
            <!-- Button to Deactivate Selected Users -->
            <div class="text-center mb-4">
                <button type="submit" name="deactivate_selected" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to deactivate the selected users?')">
                    Deactivate Selected Users
                </button>
                <!-- Button to Activate All Users -->
                <button type="submit" name="activate_all" class="btn btn-success btn-sm" onclick="return confirm('Are you sure you want to activate all users?')">
                    Activate All Users
                </button>
            </div>

            <?php if (mysqli_num_rows($result) > 0): ?>
                <table class="table table-bordered table-striped mt-4">
                    <thead class="bg-dark text-white">
                        <tr>
                            <th><input type="checkbox" id="select_all"></th>
                            <th>#</th>
                            <th>User</th>
                            <th>Video</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $i = 1; while ($row = mysqli_fetch_assoc($result)): ?>
                            <tr>
                                <td><input type="checkbox" name="user_ids[]" value="<?php echo $row['id']; ?>"></td>
                                <td><?php echo $i++; ?></td>
                                <td><?php echo htmlspecialchars($row['username']); ?></td>
                                <td><?php echo htmlspecialchars($row['video_title']); ?></td>
                                <td>
                                    <?php if ($row['status'] == 1): ?>
                                        <span class="badge bg-success">Active</span>
                                    <?php else: ?>
                                        <span class="badge bg-danger">Inactive</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($row['status'] == 1): ?>
                                        <a href="?type=status&operation=inactive&id=<?php echo $row['id']; ?>" class="btn btn-warning btn-sm">Deactivate</a>
                                    <?php else: ?>
                                        <a href="?type=status&operation=active&id=<?php echo $row['id']; ?>" class="btn btn-success btn-sm">Activate</a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="alert alert-info text-center mt-4">No Data Found.</div>
            <?php endif; ?>
        </form>

        <!-- Pagination -->
        <nav aria-label="Page navigation" class="mt-4">
            <ul class="pagination justify-content-center">
                <li class="page-item <?php echo ($page == 1) ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?page=1<?php echo ($search_term) ? '&search_term=' . $search_term : ''; ?>">First</a>
                </li>
                <li class="page-item <?php echo ($page == 1) ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?page=<?php echo ($page - 1) ? $page - 1 : 1; ?><?php echo ($search_term) ? '&search_term=' . $search_term : ''; ?>">Previous</a>
                </li>

                <?php for ($p = 1; $p <= $total_pages; $p++): ?>
                    <li class="page-item <?php echo ($page == $p) ? 'active' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $p; ?><?php echo ($search_term) ? '&search_term=' . $search_term : ''; ?>"><?php echo $p; ?></a>
                    </li>
                <?php endfor; ?>

                <li class="page-item <?php echo ($page == $total_pages) ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?page=<?php echo ($page + 1 <= $total_pages) ? $page + 1 : $total_pages; ?><?php echo ($search_term) ? '&search_term=' . $search_term : ''; ?>">Next</a>
                </li>
                <li class="page-item <?php echo ($page == $total_pages) ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?page=<?php echo $total_pages; ?><?php echo ($search_term) ? '&search_term=' . $search_term : ''; ?>">Last</a>
                </li>
            </ul>
        </nav>

    </div>

    <!-- ✅ Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <script>
        // Select/Deselect all checkboxes
        document.getElementById('select_all').addEventListener('click', function() {
            var checkboxes = document.querySelectorAll('input[type="checkbox"]');
            var isChecked = this.checked;
            checkboxes.forEach(function(checkbox) {
                checkbox.checked = isChecked;
            });
        });
    </script>

    <style>
        body {
            background-color: #e3f2fd;
            font-family: 'Poppins', sans-serif;
        }

        .container {
            background: white;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0px 5px 15px rgba(0, 0, 0, 0.3);
            max-width: 900px;
        }

        h2 {
            font-weight: bold;
            color: #0275d8;
            text-transform: uppercase;
            letter-spacing: 1px;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
        }

        .table {
            border-radius: 10px;
            overflow: hidden;
        }

        .table thead {
            background: linear-gradient(to right, #007bff, #0056b3);
            color: white;
        }

        .table th {
            text-align: center;
            padding: 12px;
        }

        .table td {
            text-align: center;
            vertical-align: middle;
        }

        .badge {
            font-size: 14px;
            padding: 8px 12px;
            border-radius: 8px;
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 14px;
            border-radius: 6px;
            font-weight: 500;
            transition: all 0.3s ease-in-out;
        }

        .btn-sm:hover {
            transform: scale(1.1);
        }

        .alert {
            font-size: 16px;
            font-weight: bold;
            color: #333;
        }

        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }
            .btn-sm {
                font-size: 12px;
                padding: 4px 8px;
            }
        }
    </style>
</body>
</html>
