<?php
require_once "db.php";

error_reporting(0);
ini_set('display_errors', 0);

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

// ================= FACE IMAGE UPLOAD =================
$face_image_path = "";

if (isset($_FILES['face_image']) && $_FILES['face_image']['error'] === 0) {

    $upload_dir = "uploads/";

    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }

    $file_name = time() . "_" . basename($_FILES["face_image"]["name"]);
    $target_file = $upload_dir . $file_name;

    if (move_uploaded_file($_FILES["face_image"]["tmp_name"], $target_file)) {
        $face_image_path = $target_file;
    }
}

// ================= GET DATA =================
$emp_id = isset($_POST['emp_id']) ? intval($_POST['emp_id']) : 0;
$att_date = $_POST['att_date'] ?? '';
$check_in_time = $_POST['check_in_time'] ?? '';
$status = $_POST['status'] ?? 'On Time';
$remark = $_POST['remark'] ?? '';
$location_name = $_POST['location_name'] ?? '';

$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_in_time)) {
    echo json_encode([
        "success" => false,
        "error" => "Missing required fields"
    ]);
    exit;
}

// ================= FIX TIME FORMAT =================
$check_in_time = date("H:i:s", strtotime($check_in_time));

// ================= CHECK EXIST =================
$stmt = $conn->prepare("SELECT 1 FROM attendance_log WHERE emp_id=? AND att_date=? LIMIT 1");
$stmt->bind_param("is", $emp_id, $att_date);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows > 0) {
    echo json_encode([
        "success" => false,
        "error" => "Already checked in"
    ]);
    $stmt->close();
    exit;
}
$stmt->close();

// ================= INSERT =================
$stmt = $conn->prepare("INSERT INTO attendance_log 
    (emp_id, att_date, check_in_time, status, remark, location_name, lat, lng, accuracy_m, distance_m, face_image)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

$stmt->bind_param(
    "isssssdddds", // ?? FIXED (11 params now)
    $emp_id,
    $att_date,
    $check_in_time,
    $status,
    $remark,
    $location_name,
    $lat,
    $lng,
    $accuracy,
    $distance,
    $face_image_path // ?? ADDED
);

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

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