<?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 
            a.att_id,
            a.att_date,
            a.check_in_time,
            a.check_out_time,
            a.status,
            a.remark,
            e.emp_id,
            e.emp_name
        FROM attendance_log a
        LEFT JOIN employee e ON a.emp_id = e.emp_id
        WHERE 1=1";

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

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

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

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

$sql .= " ORDER BY a.att_date DESC, a.att_id DESC";

$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();
$data = [];

while ($row = $result->fetch_assoc()) {
    $data[] = $row;
}

echo json_encode([
    "success" => true,
    "data" => $data
]);