<?php
require_once 'conexao.php';

$status = $_GET['status'] ?? '';
$usuario = $_GET['usuario'] ?? '';
$cliente = $_GET['cliente'] ?? '';
$data_inicio = $_GET['data_inicio'] ?? '';
$data_fim = $_GET['data_fim'] ?? '';

$where = " WHERE 1=1 ";

$params = [];
$types = '';

if ($status === 'concluida') {
    $where .= " AND concluida = 1 ";
} elseif ($status === 'pendente') {
    $where .= " AND concluida = 0 AND data_agendada >= NOW() ";
} elseif ($status === 'atrasada') {
    $where .= " AND concluida = 0 AND data_agendada < NOW() ";
}

if (!empty($usuario)) {
    $where .= " AND usuario_id = ? ";
    $types .= 'i';
    $params[] = $usuario;
}

if (!empty($cliente)) {
    $where .= " AND cliente_id = ? ";
    $types .= 'i';
    $params[] = $cliente;
}

if (!empty($data_inicio)) {
    $where .= " AND data_cadastro >= ? ";
    $types .= 's';
    $params[] = $data_inicio . " 00:00:00";
}

if (!empty($data_fim)) {
    $where .= " AND data_cadastro <= ? ";
    $types .= 's';
    $params[] = $data_fim . " 23:59:59";
}

// Query status geral
$sqlStatus = "SELECT 
                CASE 
                    WHEN concluida = 1 THEN 'Concluída'
                    WHEN data_agendada < NOW() AND concluida = 0 THEN 'Atrasada'
                    ELSE 'Pendente'
                END AS status,
                COUNT(*) AS total
              FROM atividades
              $where
              GROUP BY status";

// Query status por usuário
$sqlUserStatus = "SELECT u.nome AS usuario_nome,
                         CASE 
                            WHEN a.concluida = 1 THEN 'Concluída'
                            WHEN a.data_agendada < NOW() AND a.concluida = 0 THEN 'Atrasada'
                            ELSE 'Pendente'
                         END AS status,
                         COUNT(*) AS total
                  FROM atividades a
                  JOIN usuarios u ON a.usuario_id = u.id
                  $where
                  GROUP BY usuario_nome, status
                  ORDER BY usuario_nome";

$stmtStatus = $conn->prepare($sqlStatus);
$stmtUserStatus = $conn->prepare($sqlUserStatus);

if ($types !== '') {
    $stmtStatus->bind_param($types, ...$params);
    $stmtUserStatus->bind_param($types, ...$params);
}

$stmtStatus->execute();
$resultStatus = $stmtStatus->get_result()->fetch_all(MYSQLI_ASSOC);
$stmtStatus->close();

$stmtUserStatus->execute();
$resultUserStatus = $stmtUserStatus->get_result()->fetch_all(MYSQLI_ASSOC);
$stmtUserStatus->close();

header('Content-Type: application/json');
echo json_encode([
    'statusData' => $resultStatus,
    'userStatusData' => $resultUserStatus
]);
