<?php
// init.php ko shaamil karein
require_once 'init.php';

// Suraksha jaanch
if (!userHasRole(['Admin', 'Manager'])) {
    header("Location: dashboard.php");
    exit();
}

// --- फिल्टर्स aur Pagination ---
$limit = 15;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;
$user_filter = $_GET['user_id'] ?? 'all';
$smm_filter = $_GET['smm_id'] ?? 'all';
$search_filter = $_GET['search'] ?? '';
$schedule_type_filter = $_GET['schedule_type'] ?? 'all'; // ===== NEW: Filter for cards =====

// --- DATA FETCHING ---
$params = [];
$param_types = '';

$sql = "SELECT SQL_CALC_FOUND_ROWS 
            ts.id, ts.schedule_type, ts.assign_day,
            c.name as client_name,
            u.name as user_name,
            smm.name as smm_name
        FROM task_schedules ts
        JOIN clients c ON ts.client_id = c.id
        JOIN users u ON ts.user_id = u.id
        JOIN users smm ON ts.smm_user_id = smm.id
        WHERE ts.is_active = TRUE";

if (!empty($search_filter)) {
    $sql .= " AND c.name LIKE ?";
    $params[] = "%" . $search_filter . "%";
    $param_types .= 's';
}

// ===== NEW: Logic to filter based on card clicks =====
if ($schedule_type_filter == 'Daily') {
    $sql .= " AND ts.schedule_type = 'Daily'";
} elseif ($schedule_type_filter == 'GroupA') {
    $sql .= " AND ts.schedule_type = 'Alternate' AND ts.assign_day = 'GroupA'";
} elseif ($schedule_type_filter == 'GroupB') {
    $sql .= " AND ts.schedule_type = 'Alternate' AND ts.assign_day = 'GroupB'";
}
// ===== END NEW =====

if ($user_filter != 'all' && is_numeric($user_filter)) {
    $sql .= " AND ts.user_id = ?";
    $params[] = $user_filter;
    $param_types .= 'i';
}
if ($smm_filter != 'all' && is_numeric($smm_filter)) {
    $sql .= " AND ts.smm_user_id = ?";
    $params[] = $smm_filter;
    $param_types .= 'i';
}

$sql .= " ORDER BY c.name ASC LIMIT ? OFFSET ?";
$params_with_pagination = $params;
$params_with_pagination[] = $limit;
$params_with_pagination[] = $offset;
$param_types_with_pagination = $param_types . 'ii';

$stmt = $conn->prepare($sql);
if (!empty($params_with_pagination)) {
    $stmt->bind_param($param_types_with_pagination, ...$params_with_pagination);
}
$stmt->execute();
$schedules_result = $stmt->get_result();
$all_schedules = $schedules_result->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$total_schedules_result = $conn->query("SELECT FOUND_ROWS()");
$total_schedules = $total_schedules_result->fetch_row()[0];
$total_pages = ceil($total_schedules / $limit);

// --- Stats Cards ke liye Data ---
$stats_sql = "SELECT schedule_type, assign_day, COUNT(DISTINCT client_id) as client_count FROM task_schedules WHERE is_active = TRUE GROUP BY schedule_type, assign_day";
$stats_result = $conn->query($stats_sql);
$schedule_stats = [
    'Daily' => 0, 'GroupA' => 0, 'GroupB' => 0, 'Weekly' => 0
];
while($row = $stats_result->fetch_assoc()){
    if ($row['schedule_type'] == 'Daily') { $schedule_stats['Daily'] += $row['client_count']; } 
    elseif ($row['schedule_type'] == 'Alternate' && $row['assign_day'] == 'GroupA') { $schedule_stats['GroupA'] = $row['client_count']; } 
    elseif ($row['schedule_type'] == 'Alternate' && $row['assign_day'] == 'GroupB') { $schedule_stats['GroupB'] = $row['client_count']; }
}

$all_users = $conn->query("SELECT id, name FROM users ORDER BY name ASC")->fetch_all(MYSQLI_ASSOC);

$conn->close();
require_once 'header.php';
?>

<title>Manage Schedules - Digify OS</title>
<h2 class="text-xl font-bold text-gray-800">Regular Task Schedules</h2>

<main class="p-6 md:p-10">
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <!-- ===== FIX: Cards are now clickable links ===== -->
        <a href="schedules.php?schedule_type=all" class="bg-white p-5 rounded-lg shadow-md hover:shadow-lg transition-shadow">
            <p class="text-sm font-medium text-gray-500">Selected Client Count</p>
            <p class="text-3xl font-bold text-blue-600"><?php echo $total_schedules; ?> Clients</p>
        </a>
        <a href="schedules.php?schedule_type=Daily" class="bg-white p-5 rounded-lg shadow-md hover:shadow-lg transition-shadow">
            <p class="text-sm font-medium text-gray-500">Daily Schedules</p>
            <p class="text-3xl font-bold text-gray-800"><?php echo $schedule_stats['Daily']; ?> Clients</p>
        </a>
        <a href="schedules.php?schedule_type=GroupA" class="bg-white p-5 rounded-lg shadow-md hover:shadow-lg transition-shadow">
            <p class="text-sm font-medium text-gray-500">Group A Clients</p>
            <p class="text-3xl font-bold text-purple-600"><?php echo $schedule_stats['GroupA']; ?> Clients</p>
        </a>
        <a href="schedules.php?schedule_type=GroupB" class="bg-white p-5 rounded-lg shadow-md hover:shadow-lg transition-shadow">
            <p class="text-sm font-medium text-gray-500">Group B Clients</p>
            <p class="text-3xl font-bold text-green-600"><?php echo $schedule_stats['GroupB']; ?> Clients</p>
        </a>
    </div>

    <div class="bg-white p-4 rounded-lg shadow-md mb-8">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold">Filter Schedules</h3>
             <a href="manage-schedule.php" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg shadow-sm">+ Add New Schedule</a>
        </div>
        <form method="GET" action="schedules.php">
             <!-- Hidden field to remember card filter when other filters are used -->
            <input type="hidden" name="schedule_type" value="<?php echo htmlspecialchars($schedule_type_filter); ?>">
            <div class="flex flex-col md:flex-row flex-wrap gap-4 items-end">
                <div class="flex-grow min-w-[200px]">
                    <label class="text-sm font-medium text-gray-700">Search Client</label>
                    <input type="text" name="search" value="<?php echo htmlspecialchars($search_filter); ?>" class="mt-1 w-full border-gray-300 rounded-md shadow-sm" placeholder="Enter client name...">
                </div>
                <div>
                    <label class="text-sm font-medium text-gray-700">Assigned To</label>
                    <select name="user_id" class="mt-1 w-full border-gray-300 rounded-md shadow-sm">
                        <option value="all">All Users</option>
                         <?php foreach($all_users as $user): ?>
                            <option value="<?php echo $user['id']; ?>" <?php if($user_filter == $user['id']) echo 'selected'; ?>><?php echo htmlspecialchars($user['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="text-sm font-medium text-gray-700">Reviewed By</label>
                    <select name="smm_id" class="mt-1 w-full border-gray-300 rounded-md shadow-sm">
                        <option value="all">All SMMs</option>
                         <?php foreach($all_users as $user): ?>
                            <option value="<?php echo $user['id']; ?>" <?php if($smm_filter == $user['id']) echo 'selected'; ?>><?php echo htmlspecialchars($user['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="flex items-center gap-2">
                    <button type="submit" class="px-6 py-2 bg-blue-600 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700">Filter</button>
                    <a href="schedules.php" class="px-6 py-2 bg-gray-200 text-gray-700 font-semibold rounded-lg hover:bg-gray-300">Reset</a>
                </div>
            </div>
        </form>
    </div>
    
    <div class="bg-white rounded-lg shadow-lg overflow-hidden">
        <div class="overflow-y-auto" style="max-height: 70vh;">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-100 sticky top-0">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Client</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Assigned To</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Reviewed By</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Schedule</th>
                        <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase">Actions</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if (empty($all_schedules)): ?>
                        <tr><td colspan="5" class="px-6 py-10 text-center text-gray-500">No schedules found.</td></tr>
                    <?php else: ?>
                        <?php foreach ($all_schedules as $schedule): ?>
                            <tr class="hover:bg-gray-50">
                                <td class="px-6 py-4 font-semibold text-gray-900"><?php echo htmlspecialchars($schedule['client_name']); ?></td>
                                <td class="px-6 py-4 text-gray-600"><?php echo htmlspecialchars($schedule['user_name']); ?></td>
                                <td class="px-6 py-4 text-gray-600"><?php echo htmlspecialchars($schedule['smm_name']); ?></td>
                                <td class="px-6 py-4">
                                    <span class="font-semibold"><?php echo htmlspecialchars($schedule['schedule_type']); ?></span>
                                    <?php if(!empty($schedule['assign_day'])): ?>
                                        <span class="text-gray-500">(<?php echo htmlspecialchars($schedule['assign_day']); ?>)</span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4"><a href="edit-schedule.php?id=<?php echo $schedule['id']; ?>" class="text-indigo-600 hover:text-indigo-900 font-medium">Edit</a></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <?php if ($total_pages > 1): ?>
        <div class="p-4 flex justify-between items-center">
            <div class="text-sm text-gray-600">
                Page <?php echo $page; ?> of <?php echo $total_pages; ?>
            </div>
            <div>
                <?php
                    // ===== FIX: Added schedule_type to pagination links =====
                    $pagination_params = [
                        'search' => $search_filter,
                        'user_id' => $user_filter,
                        'smm_id' => $smm_filter,
                        'schedule_type' => $schedule_type_filter
                    ];
                ?>
                <?php if ($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>&<?php echo http_build_query($pagination_params); ?>" class="px-4 py-2 bg-white border rounded-md text-sm hover:bg-gray-50">Previous</a>
                <?php endif; ?>
                <?php if ($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>&<?php echo http_build_query($pagination_params); ?>" class="ml-2 px-4 py-2 bg-white border rounded-md text-sm hover:bg-gray-50">Next</a>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</main>

<?php require_once 'footer.php'; ?>
