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

$emp_id = isset($_GET["emp_id"]) ? intval($_GET["emp_id"]) : 0;

if ($emp_id <= 0) {
    echo json_encode([
        "success" => false,
        "error" => "Missing emp_id"
    ]);
    exit();
}

$sql = "SELECT att_date, check_in_time, check_out_time, status, remark
        FROM attendance_log
        WHERE emp_id = ?
        ORDER BY att_date DESC, att_id DESC";

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

$stmt->bind_param("i", $emp_id);

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
]);