<?php
require_once 'init.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    http_response_code(403);
    echo json_encode(['error' => 'Auth required']);
    exit();
}

$user_id = $_GET['user_id'] ?? '';
$type_filter = $_GET['type'] ?? ''; 

if (empty($user_id) || empty($type_filter)) {
    echo json_encode([]);
    exit();
}

// Logic: User aur Group ke basis par clients nikalna
// Note: 'assigned_date' aur 'assigned_user_id' aapke SQL schema ke hisab se hain
$sql = "SELECT DISTINCT c.id, c.name 
        FROM clients c
        JOIN task_schedules ts ON c.id = ts.client_id
        WHERE ts.user_id = ? 
        AND c.is_active = TRUE 
        AND ts.is_active = TRUE";

if ($type_filter === 'Daily') {
    $sql .= " AND ts.schedule_type = 'Daily'";
} elseif ($type_filter === 'GroupA') {
    $sql .= " AND ts.schedule_type = 'Alternate' AND ts.assign_day = 'GroupA'";
} elseif ($type_filter === 'GroupB') {
    $sql .= " AND ts.schedule_type = 'Alternate' AND ts.assign_day = 'GroupB'";
}

$sql .= " ORDER BY c.name ASC";

$stmt = $conn->prepare($sql);
if ($stmt) {
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    echo json_encode($result);
    $stmt->close();
} else {
    echo json_encode(['error' => $conn->error]);
}
$conn->close();
?>