<?php
require_once "db.php";

header("Content-Type: application/json; charset=UTF-8");

// ================= GET DATA =================
$emp_id = isset($_POST['emp_id']) ? intval($_POST['emp_id']) : 0;
$att_date = $_POST['att_date'] ?? '';
$check_out_time = $_POST['check_out_time'] ?? '';
$remark = $_POST['remark'] ?? '';

$lat = isset($_POST['lat']) ? floatval($_POST['lat']) : 0;
$lng = isset($_POST['lng']) ? floatval($_POST['lng']) : 0;
$accuracy = isset($_POST['accuracy']) ? floatval($_POST['accuracy']) : 0;
$distance = isset($_POST['distance']) ? floatval($_POST['distance']) : 0;

// ================= VALIDATION =================
if ($emp_id <= 0) {
    echo json_encode([
        "success" => false,
        "error" => "Invalid or missing emp_id"
    ]);
    exit;
}

if (empty($att_date) || empty($check_out_time)) {
    echo json_encode([
        "success" => false,
        "error" => "Missing required fields"
    ]);
    exit;
}

// ================= FIX TIME FORMAT =================
// Convert "04:40 PM" ? "16:40:00"
$check_out_time = date("H:i:s", strtotime($check_out_time));

// ================= GET EXISTING REMARK =================
$stmt = $conn->prepare("SELECT remark FROM attendance_log WHERE emp_id=? AND att_date=? LIMIT 1");
$stmt->bind_param("is", $emp_id, $att_date);
$stmt->execute();
$result = $stmt->get_result();

$existingRemark = "";

if ($row = $result->fetch_assoc()) {
    $existingRemark = $row['remark'] ?? '';
}
$stmt->close();

// ================= MERGE REMARK =================
if (!empty($remark)) {
    if (!empty($existingRemark)) {
        $remark = $existingRemark . " | " . $remark;
    }
} else {
    $remark = $existingRemark;
}

// ================= UPDATE =================
$stmt = $conn->prepare("UPDATE attendance_log SET 
    check_out_time=?, 
    remark=?, 
    lat=?, 
    lng=?, 
    accuracy_m=?, 
    distance_m=? 
    WHERE emp_id=? AND att_date=?");

$stmt->bind_param(
    "ssddddis",
    $check_out_time,
    $remark,
    $lat,
    $lng,
    $accuracy,
    $distance,
    $emp_id,
    $att_date
);

if ($stmt->execute()) {
    echo json_encode(["success" => true]);
} else {
    echo json_encode([
        "success" => false,
        "error" => $stmt->error
    ]);
}

$stmt->close();
$conn->close();
?>