<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");

require_once '../config/koneksi.php';

$input    = json_decode(file_get_contents("php://input"), true);
$nomor    = $input['nomor']    ?? '';
$tanggal  = $input['tanggal']  ?? '';
$tipe     = $input['tipe']     ?? ''; // masuk | ist1 | ist2 | pulang
$waktu    = $input['waktu']    ?? '';
$shift    = $input['shift']    ?? '';
$sumber   = $input['sumber']   ?? 'mobile';
$maps     = $input['maps']     ?? '';
$lat      = $input['lat']      ?? 0;
$lng      = $input['lng']      ?? 0;

if (!$nomor || !$tanggal || !$tipe || !$waktu) {
    echo json_encode(["status" => "error", "message" => "Parameter tidak lengkap"]);
    exit;
}

// --- VALIDASI GEOFENCING JARAK (SERVER SIDE) ---
$kantorLat = -7.0466699;
$kantorLng = 109.1424846;
$maxRadius = 1500000000; // dalam meter

function hitungJarakMeter($lat1, $lon1, $lat2, $lon2) {
    $earth_radius = 6371000;
    $dLat = deg2rad($lat2 - $lat1);
    $dLon = deg2rad($lon2 - $lon1);
    $a = sin($dLat/2) * sin($dLat/2) + 
         cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * 
         sin($dLon/2) * sin($dLon/2);
    $c = 2 * atan2(sqrt($a), sqrt(1-$a));
    return $earth_radius * $c;
}

$jarakUser = hitungJarakMeter($lat, $lng, $kantorLat, $kantorLng);

if ($jarakUser > $maxRadius) {
    echo json_encode([
        "status" => "error", 
        "message" => "Validasi Gagal: Jarak Anda " . round($jarakUser) . " meter dari kantor (Maksimal " . $maxRadius . "m)"
    ]);
    exit;
}

// Cek apakah rekap hari ini sudah ada
$cek = $conn->prepare("SELECT id FROM rekap WHERE nomor = ? AND tanggal = ?");
$cek->bind_param("ss", $nomor, $tanggal);
$cek->execute();
$cek->store_result();

if ($cek->num_rows === 0) {
    if ($tipe !== 'masuk') {
        echo json_encode(["status" => "error", "message" => "Belum ada data masuk untuk hari ini"]);
        exit;
    }
    // Simpan jam masuk dan maps1
    $ins = $conn->prepare(
        "INSERT INTO rekap (nomor, tanggal, shift, jam, sumber, maps1) VALUES (?, ?, ?, ?, ?, ?)"
    );
    $ins->bind_param("ssssss", $nomor, $tanggal, $shift, $waktu, $sumber, $maps);
    $ins->execute();
    echo json_encode(["status" => "success", "message" => "Jam masuk berhasil disimpan"]);
} else {
    // Tentukan kolom jam dan kolom maps berdasarkan tipe
    $kolomJam = match($tipe) {
        'ist1'   => 'ist1',
        'ist2'   => 'ist2',
        'pulang' => 'pulang',
        default  => null,
    };

    $kolomMaps = match($tipe) {
        'ist1'   => 'maps2',
        'ist2'   => 'maps3',
        'pulang' => 'maps4',
        default  => null,
    };

    if (!$kolomJam || !$kolomMaps) {
        echo json_encode(["status" => "error", "message" => "Tipe tidak valid"]);
        exit;
    }

    $upd = $conn->prepare(
        "UPDATE rekap SET $kolomJam = ?, sumber = ?, $kolomMaps = ? WHERE nomor = ? AND tanggal = ?"
    );
    $upd->bind_param("sssss", $waktu, $sumber, $maps, $nomor, $tanggal);
    $upd->execute();
    echo json_encode(["status" => "success", "message" => "Data $tipe berhasil disimpan"]);
}

$conn->close();
?>