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

// Accept POST or JSON
$raw = file_get_contents("php://input");
$data = json_decode($raw, true);
if (!is_array($data)) $data = $_POST;

$emp_id = isset($data["emp_id"]) ? intval($data["emp_id"]) : 0;
$att_date = isset($data["att_date"]) ? trim($data["att_date"]) : "";
$remark = isset($data["remark"]) ? trim($data["remark"]) : "";

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

// Check if attendance row exists first
$checkSql = "SELECT att_id FROM attendance_log WHERE emp_id = ? AND att_date = ? LIMIT 1";
$checkStmt = $conn->prepare($checkSql);

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

$checkStmt->bind_param("is", $emp_id, $att_date);

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

$checkResult = $checkStmt->get_result();
if ($checkResult->num_rows === 0) {
    echo json_encode([
        "success" => false,
        "error" => "No attendance row found for this emp_id and att_date"
    ]);
    exit();
}

// Update remark
$sql = "UPDATE attendance_log
        SET remark = ?
        WHERE emp_id = ? AND att_date = ?";

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

$stmt->bind_param("sis", $remark, $emp_id, $att_date);

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

// If row exists, treat as success even if affected_rows = 0
echo json_encode([
    "success" => true,
    "message" => "Remark updated"
]);