<?php
$conn = new mysqli("localhost", "root", "", "espabsensi");
if ($conn->connect_error) {
    die("Koneksi gagal: " . $conn->connect_error);
}

// Fungsi untuk memutar gambar base64 sebanyak 180 derajat
function rotateBase64Image($base64String, $angle = 180) {
    $data = base64_decode($base64String);
    $image = imagecreatefromstring($data);
    if ($image === false) {
        return false;
    }

    $rotated = imagerotate($image, $angle, 0);
    ob_start();
    imagejpeg($rotated);
    $outputData = ob_get_clean();

    imagedestroy($image);
    imagedestroy($rotated);

    return base64_encode($outputData);
}

$rfid  = isset($_POST['rfid']) ? $_POST['rfid'] : null;
$image = isset($_POST['image']) ? str_replace(' ', '+', $_POST['image']) : null;

if (!$rfid || !$image) {
    echo "ERROR:DATA_TIDAK_LENGKAP";
    exit;
}

$image = rotateBase64Image($image); // Putar gambar 180 derajat

if (!$image) {
    echo "ERROR:ROTATE_GAGAL";
    exit;
}

$tanggal = (new DateTime("now", new DateTimeZone("Asia/Jakarta")))->format("Y-m-d");

$cek = $conn->query("SELECT * FROM absensi WHERE rfid='$rfid' AND tanggal='$tanggal' ORDER BY id DESC LIMIT 1");

if ($cek->num_rows == 0) {
    echo "ERROR:RFID_TIDAK_DITEMUKAN";
    exit;
}

$data = $cek->fetch_assoc();

if (!empty($data['jam_masuk']) && empty($data['jam_pulang'])) {
    $sql = "UPDATE absensi SET foto_kehadiran=? WHERE id=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("si", $image, $data['id']);
    $stmt->execute();
    echo $stmt->affected_rows > 0 ? "OK:FOTO_KEHADIRAN" : "ERROR:GAGAL_SIMPAN_KEHADIRAN";

} elseif (!empty($data['jam_masuk']) && !empty($data['jam_pulang'])) {
    $sql = "UPDATE absensi SET foto_kepulangan=? WHERE id=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("si", $image, $data['id']);
    $stmt->execute();
    echo $stmt->affected_rows > 0 ? "OK:FOTO_KEPULANGAN" : "ERROR:GAGAL_SIMPAN_KEPULANGAN";

} else {
    echo "ERROR:KONDISI_ABSEN_TIDAK_VALID";
}
?>
