<?php
// Is file ka kaam sirf data dena hai, isliye hum sirf zaroori files hi include karenge.
require_once 'init.php';

// Suraksha jaanch: Sirf login kiye hue user hi iska istemal kar sakte hain.
if (!isset($_SESSION['user_id'])) {
    http_response_code(403); // Forbidden
    echo json_encode(['error' => 'Authentication required.']);
    exit();
}

// Request se date prapt karein
$selected_date = $_GET['date'] ?? '';

if (empty($selected_date) || !preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $selected_date)) {
    http_response_code(400); // Bad Request
    echo json_encode(['error' => 'Invalid date format provided.']);
    exit();
}

// Chuni hui date ke liye din ka naam aur group nirdharit karein
$day_name = date('l', strtotime($selected_date));
$group_to_run = '';
if (in_array($day_name, ['Monday', 'Wednesday', 'Friday'])) {
    $group_to_run = 'GroupA';
} elseif (in_array($day_name, ['Tuesday', 'Thursday', 'Saturday'])) {
    $group_to_run = 'GroupB';
}

// Database se un clients ki list nikalein jinka schedule hai par task nahi bana hai
$sql = "SELECT DISTINCT c.id, c.name, ts.smm_user_id
        FROM clients c
        JOIN task_schedules ts ON c.id = ts.client_id
        WHERE c.is_active = TRUE AND ts.is_active = TRUE
        AND (
            ts.schedule_type = 'Daily' OR
            (ts.schedule_type = 'Weekly' AND FIND_IN_SET(?, ts.assign_day)) OR
            (ts.schedule_type = 'Alternate' AND ts.assign_day = ?)
        )
        AND c.id NOT IN (
            SELECT client_id FROM tasks WHERE task_type = 'Regular' AND assigned_date = ?
        )
        ORDER BY c.name ASC";

$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $day_name, $group_to_run, $selected_date);
$stmt->execute();
$available_clients = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
$conn->close();

// Result ko JSON format mein output karein
header('Content-Type: application/json');
echo json_encode($available_clients);
exit();
?>
