<?php
// pages/admin/manage_batches.php
// A dedicated page to view and manage all batches.

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

// Ensure user is logged in and has the necessary role (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';
$batches = [];
$message = '';
$is_error = false;
$user_role = $_SESSION['user_role'] ?? 'guest';
$user_id = $_SESSION['user_id'] ?? null;

// Handle messages from other pages (e.g., after a successful edit or delete)
if (isset($_SESSION['message'])) {
    $message = $_SESSION['message'];
    $is_error = $_SESSION['is_error'] ?? false;
    unset($_SESSION['message']);
    unset($_SESSION['is_error']);
}

// --- Pagination & Search/Filter 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']) : '';
$status_filter = isset($_GET['status']) ? $_GET['status'] : 'all'; // 'all', 'ongoing', 'finished'

// --- SQL Queries with dynamic WHERE clause ---
$sql_base = "
    FROM batches b
    JOIN courses c ON b.course_id = c.id
    JOIN users u ON b.instructor_id = u.id
";

$params = [];
$where_clauses = [];
$param_count = 1;

// 1. Add role-based filter for instructors
if ($user_role === 'instructor') {
    $where_clauses[] = "b.instructor_id = ?";
    $params[] = $user_id;
}

// 2. Add search filter
if (!empty($search_query)) {
    $where_clauses[] = "(b.batch_name LIKE ? OR c.course_name LIKE ?)";
    $params[] = '%' . $search_query . '%';
    $params[] = '%' . $search_query . '%';
}

// 3. Add status filter
$current_date = date('Y-m-d');
if ($status_filter === 'ongoing') {
    $where_clauses[] = "b.end_date >= ?";
    $params[] = $current_date;
} elseif ($status_filter === 'finished') {
    $where_clauses[] = "b.end_date < ?";
    $params[] = $current_date;
}

// Combine all WHERE clauses
$sql_where = !empty($where_clauses) ? " WHERE " . implode(" AND ", $where_clauses) : "";

// --- Execute Queries ---
try {
    // Get total number of batches for pagination
    $sql_count = "SELECT COUNT(*) " . $sql_base . $sql_where;
    $stmt_count = $pdo->prepare($sql_count);
    $stmt_count->execute($params);
    $total_records = $stmt_count->fetchColumn();
    $total_pages = ceil($total_records / $records_per_page);

    // Fetch batches for the current page with proper LIMIT/OFFSET binding
    $sql_batches = "
        SELECT
            b.id AS batch_id, b.batch_name, b.start_date, b.end_date,
            c.course_name, u.full_name AS instructor_name
        " . $sql_base . $sql_where . " ORDER BY b.start_date DESC LIMIT ? OFFSET ?";
    
    $stmt_batches = $pdo->prepare($sql_batches);

    // Bind parameters for WHERE clauses
    foreach ($params as $param_value) {
        $stmt_batches->bindValue($param_count, $param_value, PDO::PARAM_STR);
        $param_count++;
    }

    // Bind pagination parameters as integers
    $stmt_batches->bindValue($param_count, $records_per_page, PDO::PARAM_INT);
    $param_count++;
    $stmt_batches->bindValue($param_count, $offset, PDO::PARAM_INT);
    
    $stmt_batches->execute();
    $batches = $stmt_batches->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    $message = "Database error fetching batches: " . $e->getMessage();
    $is_error = true;
    error_log("Manage Batches Fetch Error: " . $e->getMessage());
}

?>

<div class="w-full max-w-7xl mx-auto p-6 bg-white rounded-lg shadow-xl">
    <div class="flex flex-col sm:flex-row justify-between items-center mb-6 pb-4 border-b border-gray-200">
        <h1 class="text-3xl font-extrabold text-gray-900 mb-2 sm:mb-0">
            <?php echo ($user_role === 'instructor') ? 'Your Managed Batches' : 'All Batches'; ?>
        </h1>
        <a href="index.php?page=create_batch" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
            <i class="fas fa-plus-circle mr-2"></i> New Batch
        </a>
    </div>

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

    <div class="flex flex-col md:flex-row justify-between items-center mb-6 space-y-4 md:space-y-0 md:space-x-4">
        <form action="index.php" method="GET" class="flex-grow flex items-center space-x-2 w-full md:w-auto">
            <input type="hidden" name="page" value="manage_batches">
            <input type="text" name="search" placeholder="Search by batch or course..." value="<?php echo htmlspecialchars($search_query); ?>" class="flex-grow p-2 border border-gray-300 rounded-md 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-md hover:bg-gray-300 transition duration-300">
                <i class="fas fa-search"></i>
            </button>
        </form>
        <div class="w-full md:w-auto">
            <select name="status" onchange="window.location.href='index.php?page=manage_batches&status='+this.value+'&search=<?php echo urlencode($search_query); ?>'" class="block w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                <option value="all" <?php echo $status_filter === 'all' ? 'selected' : ''; ?>>All Batches</option>
                <option value="ongoing" <?php echo $status_filter === 'ongoing' ? 'selected' : ''; ?>>Ongoing</option>
                <option value="finished" <?php echo $status_filter === 'finished' ? 'selected' : ''; ?>>Finished</option>
            </select>
        </div>
    </div>

    <?php if (!empty($batches)): ?>
        <div class="overflow-x-auto bg-white rounded-lg shadow-sm">
            <table class="min-w-full leading-normal">
                <thead>
                    <tr class="bg-gray-100 text-left text-gray-600 uppercase text-sm leading-normal">
                        <th class="py-3 px-6 text-left">Batch</th>
                        <th class="py-3 px-6 text-left">Course</th>
                        <th class="py-3 px-6 text-left">Instructor</th>
                        <th class="py-3 px-6 text-left">Dates</th>
                        <th class="py-3 px-6 text-center">Status</th>
                        <th class="py-3 px-6 text-center">Actions</th>
                    </tr>
                </thead>
                <tbody class="text-gray-600 text-sm font-light">
                    <?php foreach ($batches as $batch): ?>
                        <?php
                            $is_finished = strtotime($batch['end_date']) < strtotime(date('Y-m-d'));
                            $status_text = $is_finished ? 'Finished' : 'Ongoing';
                            $status_class = $is_finished ? 'bg-red-200 text-red-800' : 'bg-green-200 text-green-800';
                        ?>
                        <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 text-gray-800"><?php echo htmlspecialchars($batch['batch_name']); ?></span>
                            </td>
                            <td class="py-3 px-6 text-left"><?php echo htmlspecialchars($batch['course_name']); ?></td>
                            <td class="py-3 px-6 text-left"><?php echo htmlspecialchars($batch['instructor_name']); ?></td>
                            <td class="py-3 px-6 text-left">
                                <span class="block"><?php echo date('M d, Y', strtotime($batch['start_date'])); ?> -</span>
                                <span class="block"><?php echo date('M d, Y', strtotime($batch['end_date'])); ?></span>
                            </td>
                            <td class="py-3 px-6 text-center">
                                <span class="py-1 px-3 rounded-full text-xs font-semibold <?php echo $status_class; ?>">
                                    <?php echo $status_text; ?>
                                </span>
                            </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_batch&batch_id=<?php echo htmlspecialchars($batch['batch_id']); ?>" class="w-8 h-8 rounded-full bg-yellow-100 text-yellow-600 flex items-center justify-center hover:bg-yellow-200 transition duration-300" title="Edit Batch">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="index.php?page=delete_batch&batch_id=<?php echo htmlspecialchars($batch['batch_id']); ?>" onclick="return confirm('Are you sure you want to delete this batch? This action cannot be undone.');" class="w-8 h-8 rounded-full bg-red-100 text-red-600 flex items-center justify-center hover:bg-red-200 transition duration-300" title="Delete Batch">
                                        <i class="fas fa-trash-alt"></i>
                                    </a>
                                    <a href="index.php?page=manage_batch_schedule&batch_id=<?php echo htmlspecialchars($batch['batch_id']); ?>" class="w-8 h-8 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center hover:bg-blue-200 transition duration-300" title="Manage Schedule">
                                        <i class="fas fa-calendar-alt"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </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_batches&p=<?php echo $current_page - 1; ?>&search=<?php echo urlencode($search_query); ?>&status=<?php echo urlencode($status_filter); ?>" 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_batches&p=<?php echo $i; ?>&search=<?php echo urlencode($search_query); ?>&status=<?php echo urlencode($status_filter); ?>" 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_batches&p=<?php echo $current_page + 1; ?>&search=<?php echo urlencode($search_query); ?>&status=<?php echo urlencode($status_filter); ?>" class="bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300">Next</a>
                <?php endif; ?>
            </div>
        <?php endif; ?>

    <?php else: ?>
        <div class="mb-6 p-4 rounded-md text-center text-lg bg-gray-50 text-gray-700 border border-gray-200">
            No batches found.
        </div>
    <?php endif; ?>
</div>