<?php
// api/api_check.php
header('Content-Type: application/json');
require_once __DIR__ . '/../config/db.php';

// ======== FIX PENTING: SET TIMEZONE WIB ========
date_default_timezone_set("Asia/Jakarta");
// ================================================

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'invalid_method']);
    exit;
}

$uid = isset($_POST['uid']) ? strtoupper(trim($_POST['uid'])) : '';
if (!$uid) {
    echo json_encode(['status' => 'invalid_uid']);
    exit;
}

// Cek apakah UID sudah dimiliki siswa
$stmt = $pdo->prepare("SELECT s.id AS siswa_id, s.nama FROM siswa s WHERE s.uid = :uid LIMIT 1");
$stmt->execute([':uid' => $uid]);
$siswa = $stmt->fetch();

if (!$siswa) {

    // Cek apakah UID ada di pool
    $stmt = $pdo->prepare("SELECT * FROM uid_pool WHERE uid = :uid LIMIT 1");
    $stmt->execute([':uid' => $uid]);
    $pool = $stmt->fetch();

    if (!$pool) {
        // Masukkan ke pool karena benar-benar UID baru
        $ins = $pdo->prepare("INSERT INTO uid_pool (uid) VALUES (:uid)");
        $ins->execute([':uid' => $uid]);
        echo json_encode(['status' => 'new_uid']);
        exit;
    } else {
        // UID sudah ada tapi belum diassign ke siswa
        echo json_encode(['status' => 'uid_unassigned']);
        exit;
    }
}

// Jika masuk sini = siswa ditemukan
$siswa_id = (int)$siswa['siswa_id'];

// Waktu berdasarkan WIB (fix masalah UTC)
$today = date('Y-m-d');
$now   = date('H:i:s');

// Cek presensi ganda
$stmt = $pdo->prepare("SELECT id FROM presensi WHERE siswa_id = :sid AND tanggal = :today LIMIT 1");
$stmt->execute([':sid' => $siswa_id, ':today' => $today]);
$exists = $stmt->fetch();

if ($exists) {
    echo json_encode(['status' => 'presensi_double']);
    exit;
}

// Cek hari libur
$stmt = $pdo->prepare("SELECT id FROM holidays WHERE tgl = :today LIMIT 1");
$stmt->execute([':today' => $today]);
$holiday = $stmt->fetch();

if ($holiday) {
    echo json_encode(['status' => 'libur_minggu']);
    exit;
}

// Ambil jam masuk dari settings
$stmt = $pdo->prepare("SELECT value_text FROM settings WHERE key_name = 'jam_masuk' LIMIT 1");
$stmt->execute();
$jm = $stmt->fetchColumn();
if (!$jm) $jm = '07:00';   // default fallback

// Tentukan keterangan Hadir / Terlambat
$keterangan = 'H';
$jam_masuk_ts = strtotime($today . ' ' . $jm);
$now_ts       = strtotime($today . ' ' . $now);

if ($now_ts > $jam_masuk_ts) {
    $keterangan = 'T';
}

// Simpan presensi
$ins = $pdo->prepare("INSERT INTO presensi (siswa_id, uid, tanggal, waktu, keterangan) 
                      VALUES (:sid, :uid, :today, :now, :ket)");
$ins->execute([
    ':sid'  => $siswa_id,
    ':uid'  => $uid,
    ':today'=> $today,
    ':now'  => $now,
    ':ket'  => $keterangan
]);

echo json_encode([
    'status'      => 'presensi_ok',
    'keterangan'  => $keterangan,
    'waktu_wib'   => $now   // tambahan info opsional
]);
exit;
