<?php
ob_start();
include 'config.php';
checkLogin();

// ─── Buat tabel absensi DULU sebelum apapun ───
$conn->query("
    CREATE TABLE IF NOT EXISTS `absensi` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `user_id` INT NOT NULL,
        `username` VARCHAR(100) NOT NULL,
        `tanggal` DATE NOT NULL,
        `jam_masuk` DATETIME DEFAULT NULL,
        `jam_keluar` DATETIME DEFAULT NULL,
        `durasi_menit` INT DEFAULT 0,
        `status` ENUM('hadir','izin','alpha') DEFAULT 'hadir',
        `catatan` VARCHAR(255) DEFAULT '',
        `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY `user_tanggal` (`user_id`, `tanggal`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

$page_title  = "Absensi Online";
$active_page = "absensi";
include 'layout.php';

$uid      = (int)($_SESSION['user_id'] ?? 0);
$uname    = $_SESSION['username'] ?? '';
$today    = date('Y-m-d');
$now      = date('Y-m-d H:i:s');
$msg      = '';
$msg_type = '';

// ─── Cek kolom full_name di users ───
$has_fullname = false;
$chk = $conn->query("SHOW COLUMNS FROM users LIKE 'full_name'");
if ($chk && $chk->num_rows > 0) $has_fullname = true;

// ─── Cek absensi hari ini ───
function cek_absen_hari_ini($conn, $uid, $today) {
    $s = $conn->prepare("SELECT * FROM absensi WHERE user_id=? AND tanggal=? LIMIT 1");
    if (!$s) return null;
    $s->bind_param("is", $uid, $today);
    $s->execute();
    $r = $s->get_result();
    $data = $r ? $r->fetch_assoc() : null;
    $s->close();
    return $data;
}

$absen_hari_ini = cek_absen_hari_ini($conn, $uid, $today);

// ─── Absen Masuk ───
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['absen_masuk'])) {
    if ($absen_hari_ini) {
        $msg = "Kamu sudah absen masuk hari ini!";
        $msg_type = 'warn';
    } else {
        $stmt_in = $conn->prepare("INSERT INTO absensi (user_id, username, tanggal, jam_masuk, status) VALUES (?,?,?,?,?)");
        if ($stmt_in) {
            $stat = 'hadir';
            $stmt_in->bind_param("issss", $uid, $uname, $today, $now, $stat);
            $stmt_in->execute();
            $stmt_in->close();
        }
        write_log($conn, 'ABSEN_MASUK', "Absen masuk: $now");
        $msg = "✅ Absen masuk berhasil! Jam: " . date('H:i:s');
        $msg_type = 'ok';
        $absen_hari_ini = cek_absen_hari_ini($conn, $uid, $today);
    }
}

// ─── Absen Keluar ───
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['absen_keluar'])) {
    if (!$absen_hari_ini) {
        $msg = "Kamu belum absen masuk hari ini!";
        $msg_type = 'err';
    } elseif (!empty($absen_hari_ini['jam_keluar'])) {
        $msg = "Kamu sudah absen keluar hari ini!";
        $msg_type = 'warn';
    } else {
        $masuk  = strtotime($absen_hari_ini['jam_masuk']);
        $durasi = (int)round((time() - $masuk) / 60);
        $stmt_out = $conn->prepare("UPDATE absensi SET jam_keluar=?, durasi_menit=? WHERE user_id=? AND tanggal=?");
        if ($stmt_out) {
            $stmt_out->bind_param("siis", $now, $durasi, $uid, $today);
            $stmt_out->execute();
            $stmt_out->close();
        }
        write_log($conn, 'ABSEN_KELUAR', "Absen keluar: $now, durasi: $durasi menit");
        $jam_kerja = floor($durasi / 60) . 'j ' . ($durasi % 60) . 'm';
        $msg = "🏠 Absen keluar berhasil! Total kerja: $jam_kerja";
        $msg_type = 'ok';
        $absen_hari_ini = cek_absen_hari_ini($conn, $uid, $today);
    }
}

// ─── Admin: Rekap semua staff hari ini ───
$rekap_hari_ini = [];
if (($_SESSION['role'] ?? '') === 'admin') {
    $name_col = $has_fullname ? "COALESCE(u.full_name, a.username)" : "a.username";
    $rq = $conn->query("SELECT a.*, $name_col AS display_name FROM absensi a LEFT JOIN users u ON a.user_id=u.id WHERE a.tanggal='$today' ORDER BY a.jam_masuk ASC");
    if ($rq) {
        while ($row = $rq->fetch_assoc()) {
            $rekap_hari_ini[] = $row;
        }
    }
}

// ─── Riwayat 14 hari terakhir ───
$riwayat = [];
$stmt_rw = $conn->prepare("SELECT * FROM absensi WHERE user_id=? AND tanggal >= DATE_SUB(CURDATE(), INTERVAL 14 DAY) ORDER BY tanggal DESC");
if ($stmt_rw) {
    $stmt_rw->bind_param("i", $uid);
    $stmt_rw->execute();
    $riwayat_res = $stmt_rw->get_result();
    if ($riwayat_res) {
        while ($row = $riwayat_res->fetch_assoc()) {
            $riwayat[] = $row;
        }
    }
    $stmt_rw->close();
}

// ─── Statistik bulan ini ───
$total_hadir = 0;
$total_menit = 0;
$stmt_stat = $conn->prepare("SELECT COUNT(*) AS hadir, COALESCE(SUM(durasi_menit),0) AS total_menit FROM absensi WHERE user_id=? AND status='hadir' AND MONTH(tanggal)=MONTH(CURDATE()) AND YEAR(tanggal)=YEAR(CURDATE())");
if ($stmt_stat) {
    $stmt_stat->bind_param("i", $uid);
    $stmt_stat->execute();
    $stat_res = $stmt_stat->get_result();
    if ($stat_res) {
        $row_stat    = $stat_res->fetch_assoc();
        $total_hadir = (int)($row_stat['hadir'] ?? 0);
        $total_menit = (int)($row_stat['total_menit'] ?? 0);
    }
    $stmt_stat->close();
}
$total_jam_str = floor($total_menit / 60) . 'j ' . ($total_menit % 60) . 'm';
?>

<style>
.abs-wrap { display:flex; flex-direction:column; gap:28px; max-width:1000px; }
.abs-card { background:var(--card-bg); border:1px solid var(--border); border-radius:20px; padding:32px; }
.abs-card h3 { font-size:1.1rem; font-weight:800; color:#fff; display:flex; align-items:center; gap:10px; margin-bottom:22px; }
.abs-card h3 i { color:var(--primary); font-size:1.4rem; }

.checkin-zone { display:flex; flex-direction:column; align-items:center; gap:24px; padding:10px 0; }
.big-clock { font-family:'JetBrains Mono',monospace; font-size:3rem; font-weight:800; color:var(--primary); letter-spacing:2px; text-shadow:0 0 20px rgba(6,182,212,.3); }
.big-date { font-size:.9rem; color:var(--text-muted); font-weight:600; }

.status-ring {
    width:140px; height:140px; border-radius:50%;
    border:4px solid var(--border);
    display:flex; flex-direction:column; align-items:center; justify-content:center;
    gap:4px; font-size:.82rem; color:var(--text-muted); font-weight:700;
    text-transform:uppercase; letter-spacing:.5px;
    background:rgba(15,23,42,.5); transition:.5s;
}
.status-ring.masuk  { border-color:#10b981; box-shadow:0 0 30px rgba(16,185,129,.3); }
.status-ring.keluar { border-color:#06b6d4; box-shadow:0 0 30px rgba(6,182,212,.3); }
.status-ring i { font-size:2.5rem; margin-bottom:4px; }
.status-ring.masuk  i { color:#10b981; }
.status-ring.keluar i { color:#06b6d4; }
.status-ring .jam-val { font-size:.95rem; font-family:'JetBrains Mono',monospace; color:#fff; }
.status-ring .jam-label { font-size:.70rem; }

.btn-row { display:flex; gap:16px; justify-content:center; flex-wrap:wrap; }
.btn-masuk    { background:linear-gradient(135deg,#10b981,#059669)!important; color:#fff!important; padding:16px 36px!important; font-size:1rem!important; border-radius:14px!important; }
.btn-masuk:hover { box-shadow:0 6px 20px rgba(16,185,129,.4)!important; transform:translateY(-2px); }
.btn-keluar   { background:linear-gradient(135deg,#06b6d4,#0891b2)!important; color:#fff!important; padding:16px 36px!important; font-size:1rem!important; border-radius:14px!important; }
.btn-keluar:hover { box-shadow:0 6px 20px rgba(6,182,212,.4)!important; transform:translateY(-2px); }
.btn-disabled { background:#334155!important; color:#64748b!important; cursor:not-allowed!important; transform:none!important; box-shadow:none!important; }

.stat-row { display:grid; grid-template-columns:repeat(auto-fit,minmax(150px,1fr)); gap:16px; }
.stat-box { background:rgba(6,182,212,0.06); border:1px solid rgba(6,182,212,0.18); border-radius:14px; padding:18px; text-align:center; }
.stat-box .val { font-size:1.6rem; font-weight:800; color:var(--primary); font-family:'JetBrains Mono',monospace; }
.stat-box .lbl { font-size:0.72rem; color:var(--text-muted); text-transform:uppercase; margin-top:4px; font-weight:600; }

.riwayat-table { width:100%; border-collapse:collapse; }
.riwayat-table th { text-align:left; padding:12px 16px; font-size:.75rem; text-transform:uppercase; color:var(--text-muted); font-weight:700; border-bottom:1px solid var(--border); }
.riwayat-table td { padding:14px 16px; font-size:.88rem; border-bottom:1px solid rgba(255,255,255,.04); }
.riwayat-table tr:last-child td { border-bottom:none; }
.riwayat-table tr:hover td { background:rgba(6,182,212,.03); }

.badge-hadir { background:rgba(16,185,129,.15); color:#10b981; padding:4px 10px; border-radius:6px; font-size:.72rem; font-weight:700; }
.badge-izin  { background:rgba(245,158,11,.15);  color:#f59e0b; padding:4px 10px; border-radius:6px; font-size:.72rem; font-weight:700; }
.badge-alpha { background:rgba(239,68,68,.15);   color:#ef4444; padding:4px 10px; border-radius:6px; font-size:.72rem; font-weight:700; }

.alert-ok   { background:rgba(16,185,129,.12); border:1px solid rgba(16,185,129,.25); color:#10b981; border-radius:12px; padding:14px 18px; font-weight:600; font-size:.9rem; margin-bottom:4px; display:flex; align-items:center; gap:10px; }
.alert-warn { background:rgba(245,158,11,.12);  border:1px solid rgba(245,158,11,.25); color:#f59e0b; border-radius:12px; padding:14px 18px; font-weight:600; font-size:.9rem; margin-bottom:4px; display:flex; align-items:center; gap:10px; }
.alert-err  { background:rgba(239,68,68,.12);   border:1px solid rgba(239,68,68,.25);  color:#ef4444; border-radius:12px; padding:14px 18px; font-weight:600; font-size:.9rem; margin-bottom:4px; display:flex; align-items:center; gap:10px; }
</style>

<div class="abs-wrap">

<?php if (!empty($msg)): ?>
<div class="alert-<?= $msg_type ?>">
    <i class='bx bx-<?= $msg_type === 'ok' ? 'check-circle' : ($msg_type === 'warn' ? 'error' : 'x-circle') ?>'></i>
    <?= htmlspecialchars($msg) ?>
</div>
<?php endif; ?>

<!-- CARD: Absen Hari Ini -->
<div class="abs-card">
    <h3><i class='bx bx-time-five'></i> Absensi Hari Ini</h3>
    <div class="checkin-zone">
        <div style="text-align:center;">
            <div class="big-clock" id="live-clock">--:--:--</div>
            <div class="big-date"><?= date('l, d F Y') ?></div>
        </div>

        <?php
        $sudah_masuk  = !empty($absen_hari_ini);
        $sudah_keluar = $sudah_masuk && !empty($absen_hari_ini['jam_keluar']);
        $ring_class   = $sudah_keluar ? 'keluar' : ($sudah_masuk ? 'masuk' : '');
        ?>
        <div class="status-ring <?= $ring_class ?>">
            <?php if ($sudah_keluar): ?>
                <i class='bx bx-home-check'></i>
                <span>Selesai</span>
                <span class="jam-label">Jam Keluar</span>
                <span class="jam-val"><?= date('H:i', strtotime($absen_hari_ini['jam_keluar'])) ?></span>
            <?php elseif ($sudah_masuk): ?>
                <i class='bx bx-log-in-circle'></i>
                <span>Sedang Kerja</span>
                <span class="jam-label">Masuk Jam</span>
                <span class="jam-val"><?= date('H:i', strtotime($absen_hari_ini['jam_masuk'])) ?></span>
            <?php else: ?>
                <i class='bx bx-door-open'></i>
                <span>Belum Absen</span>
            <?php endif; ?>
        </div>

        <div class="btn-row">
            <?php if (!$sudah_masuk): ?>
            <form method="POST">
                <input type="hidden" name="absen_masuk" value="1">
                <button type="submit" class="btn btn-masuk"><i class='bx bx-log-in'></i> Absen Masuk</button>
            </form>
            <?php else: ?>
            <button class="btn btn-masuk btn-disabled" disabled><i class='bx bx-check'></i> Sudah Absen Masuk</button>
            <?php endif; ?>

            <?php if ($sudah_masuk && !$sudah_keluar): ?>
            <form method="POST" onsubmit="return confirm('Konfirmasi absen keluar sekarang?')">
                <input type="hidden" name="absen_keluar" value="1">
                <button type="submit" class="btn btn-keluar"><i class='bx bx-log-out'></i> Absen Keluar</button>
            </form>
            <?php elseif ($sudah_keluar): ?>
            <button class="btn btn-keluar btn-disabled" disabled><i class='bx bx-check'></i> Sudah Absen Keluar</button>
            <?php else: ?>
            <button class="btn btn-keluar btn-disabled" disabled><i class='bx bx-log-out'></i> Absen Keluar</button>
            <?php endif; ?>
        </div>

        <?php if ($sudah_masuk && !$sudah_keluar): ?>
        <div style="font-size:.82rem;color:var(--text-muted);text-align:center;">
            Durasi kerja berjalan: <strong id="durasi-live" style="color:var(--primary);">menghitung...</strong>
        </div>
        <script>
        (function() {
            const masukTs = <?= strtotime($absen_hari_ini['jam_masuk']) ?> * 1000;
            function updateDurasi() {
                const diff = Math.floor((Date.now() - masukTs) / 1000);
                const jam = Math.floor(diff / 3600);
                const mnt = Math.floor((diff % 3600) / 60);
                const dtk = diff % 60;
                const el = document.getElementById('durasi-live');
                if (el) el.textContent = String(jam).padStart(2,'0') + 'j ' + String(mnt).padStart(2,'0') + 'm ' + String(dtk).padStart(2,'0') + 'd';
            }
            setInterval(updateDurasi, 1000);
            updateDurasi();
        })();
        </script>
        <?php endif; ?>
    </div>
</div>

<!-- CARD: Statistik Bulan Ini -->
<div class="abs-card">
    <h3><i class='bx bx-bar-chart'></i> Statistik Bulan Ini — <?= date('F Y') ?></h3>
    <div class="stat-row">
        <div class="stat-box">
            <div class="val"><?= $total_hadir ?></div>
            <div class="lbl">Hari Hadir</div>
        </div>
        <div class="stat-box">
            <div class="val"><?= $total_menit > 0 ? $total_jam_str : '0j' ?></div>
            <div class="lbl">Total Jam Kerja</div>
        </div>
        <div class="stat-box">
            <div class="val"><?= date('t') ?></div>
            <div class="lbl">Hari di Bulan Ini</div>
        </div>
        <div class="stat-box">
            <div class="val"><?= $total_hadir > 0 ? round($total_menit / $total_hadir / 60, 1) : 0 ?>j</div>
            <div class="lbl">Rata-rata/Hari</div>
        </div>
    </div>
</div>

<!-- CARD: Riwayat Absensi -->
<div class="abs-card">
    <h3><i class='bx bx-calendar-check'></i> Riwayat Absensi (14 Hari Terakhir)</h3>
    <?php if (!empty($riwayat)): ?>
    <div style="overflow-x:auto;">
        <table class="riwayat-table">
            <thead>
                <tr>
                    <th>Tanggal</th>
                    <th>Jam Masuk</th>
                    <th>Jam Keluar</th>
                    <th>Durasi Kerja</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($riwayat as $r): ?>
                <tr>
                    <td>
                        <strong><?= date('d/m/Y', strtotime($r['tanggal'])) ?></strong><br>
                        <small style="color:var(--text-muted);"><?= date('l', strtotime($r['tanggal'])) ?></small>
                    </td>
                    <td>
                        <?= !empty($r['jam_masuk'])
                            ? '<span style="color:var(--primary);font-family:JetBrains Mono,monospace;">' . date('H:i', strtotime($r['jam_masuk'])) . '</span>'
                            : '–' ?>
                    </td>
                    <td>
                        <?= !empty($r['jam_keluar'])
                            ? '<span style="color:#94a3b8;font-family:JetBrains Mono,monospace;">' . date('H:i', strtotime($r['jam_keluar'])) . '</span>'
                            : '<span style="color:#f59e0b;">Belum Keluar</span>' ?>
                    </td>
                    <td>
                        <?php if ($r['durasi_menit'] > 0):
                            $jm = floor($r['durasi_menit'] / 60);
                            $mn = $r['durasi_menit'] % 60;
                            echo "<span style='font-family:JetBrains Mono,monospace;'>{$jm}j {$mn}m</span>";
                        else: echo '–';
                        endif; ?>
                    </td>
                    <td><span class="badge-<?= htmlspecialchars($r['status']) ?>"><?= ucfirst($r['status']) ?></span></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div style="text-align:center;padding:40px;color:var(--text-muted);">
        <i class='bx bx-calendar-x' style="font-size:3rem;display:block;margin-bottom:10px;"></i>
        Belum ada riwayat absensi.
    </div>
    <?php endif; ?>
</div>

<?php if (($_SESSION['role'] ?? '') === 'admin'): ?>
<!-- CARD: Admin Rekap Hari Ini -->
<div class="abs-card">
    <h3><i class='bx bxs-user-check'></i> Rekap Staff Hari Ini (Admin)</h3>
    <?php if (!empty($rekap_hari_ini)): ?>
    <div style="overflow-x:auto;">
        <table class="riwayat-table">
            <thead>
                <tr>
                    <th>Nama / Username</th>
                    <th>Jam Masuk</th>
                    <th>Jam Keluar</th>
                    <th>Durasi</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($rekap_hari_ini as $r): ?>
                <tr>
                    <td><strong><?= htmlspecialchars($r['display_name'] ?? $r['username']) ?></strong></td>
                    <td><?= !empty($r['jam_masuk']) ? date('H:i', strtotime($r['jam_masuk'])) : '–' ?></td>
                    <td>
                        <?= !empty($r['jam_keluar'])
                            ? date('H:i', strtotime($r['jam_keluar']))
                            : '<span style="color:#f59e0b;">Masih Aktif</span>' ?>
                    </td>
                    <td>
                        <?php
                        if ($r['durasi_menit'] > 0) {
                            echo floor($r['durasi_menit']/60) . 'j ' . ($r['durasi_menit']%60) . 'm';
                        } elseif (!empty($r['jam_masuk']) && empty($r['jam_keluar'])) {
                            $dur = round((time() - strtotime($r['jam_masuk'])) / 60);
                            echo '<span style="color:#f59e0b;">' . floor($dur/60) . 'j ' . ($dur%60) . 'm ▶</span>';
                        } else { echo '–'; }
                        ?>
                    </td>
                    <td><span class="badge-hadir">Hadir</span></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div style="text-align:center;padding:30px;color:var(--text-muted);">
        <i class='bx bx-group' style="font-size:2.5rem;display:block;margin-bottom:8px;"></i>
        Belum ada staff yang absen hari ini.
    </div>
    <?php endif; ?>
</div>
<?php endif; ?>

</div>

<script>
(function() {
    function tick() {
        const now = new Date();
        const h = String(now.getHours()).padStart(2,'0');
        const m = String(now.getMinutes()).padStart(2,'0');
        const s = String(now.getSeconds()).padStart(2,'0');
        const el = document.getElementById('live-clock');
        if (el) el.textContent = h + ':' + m + ':' + s;
    }
    setInterval(tick, 1000);
    tick();
})();
</script>
