<?php
require_once "db.php";
header("Content-Type: application/json; charset=UTF-8");

$date = isset($_GET["date"]) ? trim($_GET["date"]) : "";
$emp_id = isset($_GET["emp_id"]) ? intval($_GET["emp_id"]) : -1;
$status = isset($_GET["status"]) ? trim($_GET["status"]) : "";

$sql = "SELECT status, COUNT(*) AS cnt
        FROM attendance_log
        WHERE 1=1";

$params = [];
$types = "";

if ($date !== "") {
    $sql .= " AND att_date = ?";
    $params[] = $date;
    $types .= "s";
}

if ($emp_id > 0) {
    $sql .= " AND emp_id = ?";
    $params[] = $emp_id;
    $types .= "i";
}

if ($status !== "") {
    $sql .= " AND status = ?";
    $params[] = $status;
    $types .= "s";
}

$sql .= " GROUP BY status";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    echo json_encode([
        "success" => false,
        "error" => "Prepare failed: " . $conn->error
    ]);
    exit();
}

if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}

if (!$stmt->execute()) {
    echo json_encode([
        "success" => false,
        "error" => "Execute failed: " . $stmt->error
    ]);
    exit();
}

$result = $stmt->get_result();

$total = 0;
$on_time = 0;
$late = 0;
$manual = 0;

while ($row = $result->fetch_assoc()) {
    $st = $row["status"];
    $cnt = intval($row["cnt"]);
    $total += $cnt;

    if ($st === "On Time") $on_time = $cnt;
    else if ($st === "Late") $late = $cnt;
    else if ($st === "Manual") $manual = $cnt;
}

echo json_encode([
    "success" => true,
    "data" => [
        "total" => $total,
        "on_time" => $on_time,
        "late" => $late,
        "manual" => $manual
    ]
]);