<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once '../config/database.php';

$username = isset($_GET['username']) ? $_GET['username'] : '';

if($username) {
    date_default_timezone_set('Asia/Jakarta');

    // Cari user_id dulu
    $stmtUser = $pdo->prepare("SELECT id FROM users WHERE username = ?");
    $stmtUser->execute([$username]);
    $user = $stmtUser->fetch();

    if ($user) {
        $user_id = $user['id'];

        // Cari Jam Masuk (type = 'in')
        $stmtIn = $pdo->prepare("SELECT attendance_time FROM attendance WHERE user_id = ? AND type = 'in' AND DATE(attendance_time) = CURDATE() LIMIT 1");
        $stmtIn->execute([$user_id]);
        $dataIn = $stmtIn->fetch();
        $masuk = $dataIn ? date('H:i', strtotime($dataIn['attendance_time'])) : 'Belum';

        // Cari Jam Pulang (type = 'out')
        $stmtOut = $pdo->prepare("SELECT attendance_time FROM attendance WHERE user_id = ? AND type = 'out' AND DATE(attendance_time) = CURDATE() LIMIT 1");
        $stmtOut->execute([$user_id]);
        $dataOut = $stmtOut->fetch();
        $pulang = $dataOut ? date('H:i', strtotime($dataOut['attendance_time'])) : 'Belum';

        echo json_encode(["status" => "success", "masuk" => $masuk, "pulang" => $pulang]);
    } else {
        echo json_encode(["status" => "error", "message" => "User tidak terdaftar"]);
    }
} else {
    echo json_encode(["status" => "error", "message" => "Username kosong"]);
}
?>