<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/yoga/includes/config.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/yoga/includes/functions.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/yoga/includes/header.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/yoga/includes/sidebar.php';

// Cek login
cek_login();

// Cek akses
if (!cek_akses('absensi', 'scan')) {
    header("Location: " . BASE_URL . "/index.php?access=denied");
    exit();
}

$tanggal = date('Y-m-d');
$jam = date('H:i:s');
$pengaturan = get_pengaturan();
$karyawan = null;
$absensi = null;

if ($_SESSION['role'] == 'karyawan') {
    $user_id = $_SESSION['user_id'];
    $karyawan = get_karyawan_by_user($user_id);
    
    if ($karyawan) {
        $karyawan_id = $karyawan['id'];
        $query_absen = "SELECT * FROM absensi WHERE karyawan_id = $karyawan_id AND tanggal = '$tanggal'";
        $result_absen = mysqli_query($conn, $query_absen);
        $absensi = mysqli_fetch_assoc($result_absen);
    }
}

$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['qr_data'])) {
    $qr_data = $_POST['qr_data'];
    
    try {
        $data = json_decode($qr_data, true);
        if (json_last_error() !== JSON_ERROR_NONE) throw new Exception("Format QR Code tidak valid!");
        if (!isset($data['id']) || !isset($data['nik'])) throw new Exception("Data QR Code tidak lengkap!");
        
        $scanned_id = $data['id'];
        
        if ($_SESSION['role'] == 'karyawan' && $scanned_id != $karyawan_id) {
            throw new Exception("Anda hanya bisa scan QR Code Anda sendiri!");
        }
        
        $query_karyawan = "SELECT * FROM karyawan WHERE id = $scanned_id AND status = 'aktif'";
        $result_karyawan = mysqli_query($conn, $query_karyawan);
        if (mysqli_num_rows($result_karyawan) == 0) throw new Exception("Karyawan tidak aktif atau tidak ditemukan!");
        
        $query_absen = "SELECT * FROM absensi WHERE karyawan_id = $scanned_id AND tanggal = '$tanggal'";
        $result_absen = mysqli_query($conn, $query_absen);
        
        mysqli_begin_transaction($conn);
        
        if (mysqli_num_rows($result_absen) > 0) {
            $absen = mysqli_fetch_assoc($result_absen);
            if (!empty($absen['jam_keluar'])) throw new Exception("Anda sudah melakukan absensi keluar hari ini!");
            
            $update_query = "UPDATE absensi SET jam_keluar = '$jam', updated_at = NOW() WHERE id = {$absen['id']}";
            if (mysqli_query($conn, $update_query)) {
                mysqli_commit($conn);
                $success = "Absensi KELUAR berhasil pada jam $jam";
            } else throw new Exception("Gagal melakukan absensi keluar!");
        } else {
            $insert_query = "INSERT INTO absensi (karyawan_id, tanggal, jam_masuk, status) VALUES ($scanned_id, '$tanggal', '$jam', 'hadir')";
            if (mysqli_query($conn, $insert_query)) {
                mysqli_commit($conn);
                $success = "Absensi MASUK berhasil pada jam $jam";
                if ($jam > $pengaturan['jam_masuk']) {
                    $telat_menit = hitung_keterlambatan($jam, $pengaturan['jam_masuk']);
                    $success .= ". Anda tercatat terlambat $telat_menit menit.";
                }
            } else throw new Exception("Gagal melakukan absensi masuk!");
        }
    } catch (Exception $e) {
        mysqli_rollback($conn);
        $error = $e->getMessage();
    }
    
    if ($_SESSION['role'] == 'karyawan' && $karyawan) {
        $query_absen = "SELECT * FROM absensi WHERE karyawan_id = $karyawan_id AND tanggal = '$tanggal'";
        $result_absen = mysqli_query($conn, $query_absen);
        $absensi = mysqli_fetch_assoc($result_absen);
    }
}
?>

<div class="main-content flex-1 p-8">
    <div class="flex justify-between items-center mb-6">
        <div>
            <h2 class="text-3xl font-bold text-white">Scan QR Code Absensi</h2>
            <p class="text-slate-400">Gunakan kamera untuk melakukan absensi masuk atau pulang.</p>
        </div>
        <a href="<?php echo BASE_URL; ?>/index.php" class="bg-slate-700 hover:bg-slate-600 text-white font-bold py-2.5 px-6 rounded-lg transition-colors">
            Kembali
        </a>
    </div>
    
    <?php if (!empty($success)): ?>
    <div class="bg-green-500/20 border border-green-500/30 text-green-300 px-4 py-3 rounded-lg relative mb-6 text-sm flex items-center gap-3" role="alert">
        <i class="fas fa-check-circle"></i><span><?php echo $success; ?></span>
    </div>
    <?php endif; ?>
    
    <?php if (!empty($error)): ?>
    <div class="bg-red-500/20 border border-red-500/30 text-red-300 px-4 py-3 rounded-lg relative mb-6 text-sm flex items-center gap-3" role="alert">
        <i class="fas fa-exclamation-circle"></i><span><?php echo $error; ?></span>
    </div>
    <?php endif; ?>
    
    <?php if ($_SESSION['role'] == 'karyawan' && $karyawan): ?>
    <div class="glass-effect p-6 rounded-xl shadow-lg mb-8">
        <h3 class="text-lg font-semibold text-white mb-4">Absensi Anda Hari Ini (<?php echo tanggal_indo($tanggal); ?>)</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div class="bg-slate-700/50 p-4 rounded-lg border border-slate-600">
                <h4 class="text-md font-medium text-slate-300 mb-2">Jam Masuk</h4>
                <p class="text-3xl font-bold <?php echo ($absensi && $absensi['jam_masuk'] > $pengaturan['jam_masuk']) ? 'text-red-400' : 'text-green-400'; ?>">
                    <?php echo ($absensi && $absensi['jam_masuk']) ? $absensi['jam_masuk'] : '-'; ?>
                </p>
                <?php if ($absensi && $absensi['jam_masuk'] > $pengaturan['jam_masuk']): ?>
                <p class="text-sm text-red-500">Terlambat <?php echo hitung_keterlambatan($absensi['jam_masuk'], $pengaturan['jam_masuk']); ?> menit</p>
                <?php endif; ?>
            </div>
            <div class="bg-slate-700/50 p-4 rounded-lg border border-slate-600">
                <h4 class="text-md font-medium text-slate-300 mb-2">Jam Pulang</h4>
                <p class="text-3xl font-bold <?php echo ($absensi && $absensi['jam_keluar']) ? 'text-sky-400' : ''; ?>">
                    <?php echo ($absensi && $absensi['jam_keluar']) ? $absensi['jam_keluar'] : '-'; ?>
                </p>
            </div>
        </div>
        
        <div class="mt-4 p-3 rounded-lg text-center <?php echo (!$absensi || ($absensi && empty($absensi['jam_keluar']))) ? 'bg-sky-500/20' : 'bg-green-500/20'; ?>">
            <p class="text-sm <?php echo (!$absensi || ($absensi && empty($absensi['jam_keluar']))) ? 'text-sky-300' : 'text-green-300'; ?>">
                <?php if (!$absensi): ?> Silakan scan QR Code untuk Absensi Masuk.
                <?php elseif (empty($absensi['jam_keluar'])): ?> Silakan scan QR Code untuk Absensi Pulang.
                <?php else: ?> Anda telah menyelesaikan absensi hari ini.
                <?php endif; ?>
            </p>
        </div>
    </div>
    <?php endif; ?>
    
    <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
        <div class="glass-effect p-6 rounded-xl shadow-lg">
            <h3 class="text-xl font-semibold text-white mb-4 border-b border-slate-700/50 pb-3">Scanner</h3>
            <div id="reader" class="w-full rounded-lg overflow-hidden"></div>
            <p class="text-sm text-slate-400 text-center mt-4">Arahkan kamera ke QR Code.</p>
            <form id="scanForm" method="POST" action="" class="hidden"><input type="hidden" name="qr_data" id="qr_data"></form>
        </div>
        
        <div class="glass-effect p-6 rounded-xl shadow-lg">
            <h3 class="text-xl font-semibold text-white mb-4 border-b border-slate-700/50 pb-3">Informasi</h3>
            <div class="space-y-4 text-slate-300">
                <div>
                    <h4 class="font-semibold text-slate-100 mb-1">Jam Kerja</h4>
                    <p>Masuk: <span class="font-medium text-white"><?php echo $pengaturan['jam_masuk']; ?></span></p>
                    <p>Pulang: <span class="font-medium text-white"><?php echo $pengaturan['jam_keluar']; ?></span></p>
                </div>
                <div>
                    <h4 class="font-semibold text-slate-100 mb-1">Ketentuan Absensi</h4>
                    <ul class="list-disc list-inside space-y-1 text-sm">
                        <li>Absensi masuk sebelum jam <?php echo $pengaturan['jam_masuk']; ?></li>
                        <li>Toleransi keterlambatan <?php echo $pengaturan['toleransi_keterlambatan']; ?> menit</li>
                        <li>Absensi pulang setelah jam <?php echo $pengaturan['jam_keluar']; ?></li>
                    </ul>
                </div>
                <div>
                    <h4 class="font-semibold text-slate-100 mb-1">Waktu Saat Ini</h4>
                    <p>Tanggal: <span class="font-medium text-white"><?php echo tanggal_indo($tanggal); ?></span></p>
                    <p>Jam: <span class="font-medium text-white" id="current-time"><?php echo $jam; ?></span></p>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
<script>
    function updateTime() {
        const timeEl = document.getElementById('current-time');
        if (timeEl) {
            const now = new Date();
            timeEl.textContent = now.toTimeString().split(' ')[0];
        }
    }
    setInterval(updateTime, 1000);
    
    function onScanSuccess(decodedText, decodedResult) {
        document.getElementById('qr_data').value = decodedText;
        document.getElementById('scanForm').submit();
        html5QrcodeScanner.clear();
    }
    
    const html5QrcodeScanner = new Html5QrcodeScanner("reader", { fps: 10, qrbox: { width: 250, height: 250 } });
    html5QrcodeScanner.render(onScanSuccess);
</script>

<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/yoga/includes/footer.php';
?>