<?php
session_start();
date_default_timezone_set('Asia/Jakarta');
include 'config.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

// Inisialisasi variabel global untuk sesi ini
$user_id = $_SESSION['user_id'];
$tanggal_hari_ini = date('Y-m-d');

/* ==================================
   PROSES ABSEN MASUK
================================== */
if (isset($_POST['absen_masuk'])) {
    $tanggal = date('Y-m-d');
    $jam = date('H:i:s');
    $lokasi = mysqli_real_escape_string($conn, $_POST['lokasi']);
    $foto_base64 = $_POST['foto_masuk'];

    // Cek apakah sudah absen hari ini
    $cek = mysqli_query($conn, "SELECT * FROM absensi WHERE user_id='$user_id' AND tanggal='$tanggal'");

    if (mysqli_num_rows($cek) > 0) {
        echo "<script>
            alert('Anda sudah absen masuk hari ini');
            window.location='dashboard.php';
        </script>";
        exit;
    }

    // Dekode Foto Base64
    $foto_base64 = str_replace('data:image/png;base64,', '', $foto_base64);
    $foto_base64 = str_replace(' ', '+', $foto_base64);
    $data = base64_decode($foto_base64);

    $nama_foto = 'masuk_' . time() . '.png';
    file_put_contents("uploads/" . $nama_foto, $data);

    // Insert ke Database
    mysqli_query($conn, "INSERT INTO absensi (user_id, tanggal, jam_masuk, status, lokasi, foto) VALUES ('$user_id', '$tanggal', '$jam', 'Hadir', '$lokasi', '$nama_foto')");

    echo "<script>
        alert('Absen masuk berhasil');
        window.location='dashboard.php';
    </script>";
    exit;
}

/* ==================================
   PROSES ABSEN PULANG
================================== */
if (isset($_POST['absen_pulang'])) {
    $jam = date('H:i:s');
    $foto_base64 = $_POST['foto_pulang'];

    // Dekode Foto Base64
    $foto_base64 = str_replace('data:image/png;base64,', '', $foto_base64);
    $foto_base64 = str_replace(' ', '+', $foto_base64);
    $data = base64_decode($foto_base64);

    $nama_foto = 'pulang_' . time() . '.png';
    file_put_contents("uploads/" . $nama_foto, $data);

    // Update Jam Pulang pada absensi hari ini yang belum pulang
    mysqli_query($conn, "UPDATE absensi SET jam_pulang='$jam', foto_pulang='$nama_foto' WHERE id = (SELECT id FROM (SELECT id FROM absensi WHERE user_id='$user_id' AND jam_pulang IS NULL ORDER BY id DESC LIMIT 1) as x)");

    echo "<script>
        alert('Absen pulang berhasil');
        window.location='dashboard.php';
    </script>";
    exit;
}

// Cek status absen untuk tampilan interface
$cek_absen = mysqli_query($conn, "SELECT * FROM absensi WHERE user_id='$user_id' AND tanggal='$tanggal_hari_ini'");
$sudah_absen = mysqli_num_rows($cek_absen) > 0;
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - Sistem Absensi</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background: #f5f7fb;
            font-size: 14px;
        }
        .navbar-brand {
            font-weight: bold;
            font-size: 16px;
        }
        .card {
            border-radius: 12px;
            border: none;
        }
        button {
            border-radius: 10px !important;
            font-size: 14px;
        }
        video, img {
            border-radius: 10px;
            object-fit: cover;
            background-color: #000;
        }
        .alert {
            font-size: 13px;
            border-radius: 10px;
        }
        a {
            text-decoration: none;
            font-weight: 500;
        }
        .nav-tabs .nav-link {
            color: #555;
            font-weight: 600;
        }
        .nav-tabs .nav-link.active {
            color: #0d6efd;
            border-bottom: 3px solid #0d6efd;
        }
        @media (max-width: 768px) {
            h4 { font-size: 18px; }
            .container { padding: 10px; }
            .card { padding: 12px !important; }
            .btn { font-size: 13px; padding: 10px; }
            video, img { height: 200px; }
        }
    </style>
</head>
<body>

<nav class="navbar navbar-dark bg-primary">
    <div class="container">
        <span class="navbar-brand">Sistem Absensi DMK Cargo</span>
        <a href="logout.php" class="btn btn-light btn-sm">Logout</a>
    </div>
</nav>


<div class="container mt-4">
    <center>
    <?php if (isset($_SESSION['role']) && $_SESSION['role'] == 'admin') : ?>
    <h4>Administrator</h4>
    <div class="row mb-3">
        <div class="col-md-4">
            <div class="card mb-3 shadow-sm">
                <div class="card-body text-center">
                    <h5 class="card-title">Laporan Absensi</h5>
                    <p class="card-text text-muted">Lihat rekap kehadiran karyawan</p>
                    <a href="laporan.php" class="btn btn-success w-100">Buka Laporan</a>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card mb-3 shadow-sm">
                <div class="card-body text-center">
                    <h5 class="card-title">Manajemen User</h5>
                    <p class="card-text text-muted">Tambahkan atau kelola akun baru</p>
                    <a href="tambah_user.php" class="btn btn-success w-100 mb-2">Tambah User</a>
                    <a href="data_user.php" class="btn btn-outline-danger w-100">Data User</a>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card mb-3 shadow-sm">
                <div class="card-body text-center">
                    <h5 class="card-title">Maintenance</h5>
                    <p class="card-text text-muted">-</p>
                    <a href="#" class="btn btn-success w-100 mb-2">-</a>
                    <a href="#" class="btn btn-outline-danger w-100">-</a>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <hr>

    <h4>Dashboard</h4>
    <div class="col-md-4">
            <div class="card mb-3 shadow-sm">
                <div class="card-body text-center">
                    <h5 class="card-title">Riwayat Absensi</h5>
                    <p class="card-text text-muted">Lihat rekap kehadiran Absensi</p>
                    <a href="riwayat_absensi.php" class="btn btn-success w-100">Riwayat Absensi Saya</a>
                </div>
            </div>
        </div>
    </center>
    <hr>

    <div class="card shadow">
        <div class="card-header bg-white">
            <ul class="nav nav-tabs card-header-tabs" id="absensiTab" role="tablist">
                <li class="nav-item">
                    <button class="nav-link active" id="tab-masuk-btn" data-bs-toggle="tab" data-bs-target="#tabMasuk" type="button">📥 Absen Masuk</button>
                </li>
                <li class="nav-item">
                    <button class="nav-link" id="tab-pulang-btn" data-bs-toggle="tab" data-bs-target="#tabPulang" type="button">📤 Absen Pulang</button>
                </li>
            </ul>
        </div>

        <div class="card-body">
            <div class="tab-content">
                
                <div class="tab-pane fade show active" id="tabMasuk" role="tabpanel">
                    <div class="p-2">
                        <h5>Absen Masuk</h5>
                        <?php if($sudah_absen) : ?>
                            <div class="alert alert-success mt-2">Anda sudah melakukan absen masuk hari ini.</div>
                        <?php endif; ?>

                        <div class="alert alert-info py-2 mt-2">
                            <strong>Jam Server Saat Ini:</strong><br>
                            <span id="jamServerMasuk" data-server-time="<?= date('Y-m-d H:i:s') ?>"></span>
                        </div>

                        <form method="post">
                            <label class="form-label mt-2">Lokasi Berada</label>
                            <select name="lokasi" class="form-select" required <?= $sudah_absen ? 'disabled' : '' ?>>
                                <option value="">-- Pilih Lokasi --</option>
                                <option value="Kantor Pusat">Kantor Pusat</option>
                                <option value="Gudang">Gudang</option>
                                <option value="Cabang A">Cabang A</option>
                                <option value="Cabang B">Cabang B</option>
                                <option value="WFH">WFH</option>
                            </select>

                            <label class="form-label mt-3">Foto Kamera Masuk</label>
                            <video id="videoMasuk" width="100%" autoplay></video>
                            <img id="previewMasuk" width="100%" class="mt-2 rounded border" style="display:none;">
                            <canvas id="canvasMasuk" style="display:none;"></canvas>

                            <input type="hidden" name="foto_masuk" id="fotoMasuk">
                            
                            <button type="button" class="btn btn-warning mt-2 w-100" onclick="takePhotoMasuk()" <?= $sudah_absen ? 'disabled' : '' ?>>Ambil Foto Masuk</button>
                            <button type="submit" name="absen_masuk" class="btn btn-success mt-3 w-100 py-2" <?= $sudah_absen ? 'disabled' : '' ?>>Simpan Absen Masuk</button>
                        </form>
                    </div>
                </div>    

                <div class="tab-pane fade" id="tabPulang" role="tabpanel">
                    <div class="p-2">
                        <h5>Absen Pulang</h5>
                        <div class="alert alert-warning py-2 mt-2">
                            <strong>Jam Server Saat Ini:</strong><br>
                            <span id="jamServerPulang" data-server-time="<?= date('Y-m-d H:i:s') ?>"></span>
                        </div>

                        <form method="post">
                            <label class="form-label mt-2">Foto Kamera Pulang</label>
                            <video id="videoPulang" width="100%" autoplay></video>
                            <img id="previewPulang" width="100%" class="mt-2 rounded border" style="display:none;">
                            <canvas id="canvasPulang" style="display:none;"></canvas>

                            <input type="hidden" name="foto_pulang" id="fotoPulang">

                            <button type="button" class="btn btn-warning mt-2 w-100" onclick="takePhotoPulang()">Ambil Foto Pulang</button>
                            <button type="submit" name="absen_pulang" class="btn btn-danger mt-3 w-100 py-2">Simpan Absen Pulang</button>
                        </form>
                    </div>
                </div>

            </div>
        </div>
    </div>
</div>

<script>
let streamMasuk = null;
let streamPulang = null;

// Fungsi menyalakan kamera Masuk
function startKameraMasuk() {
    if (streamMasuk) return;
    const videoMasuk = document.getElementById("videoMasuk");
    navigator.mediaDevices.getUserMedia({ video: true })
    .then(stream => {
        streamMasuk = stream;
        videoMasuk.srcObject = stream;
    }).catch(err => { alert("Kamera masuk tidak dapat diakses"); });
}

// Fungsi menyalakan kamera Pulang
function startKameraPulang() {
    if (streamPulang) return;
    const videoPulang = document.getElementById("videoPulang");
    navigator.mediaDevices.getUserMedia({ video: true })
    .then(stream => {
        streamPulang = stream;
        videoPulang.srcObject = stream;
    }).catch(err => { alert("Kamera pulang tidak dapat diakses"); });
}

// Deteksi perpindahan tab agar kamera tidak bentrok
document.getElementById('tab-masuk-btn').addEventListener('shown.bs.tab', function () {
    startKameraMasuk();
    if(streamPulang) { streamPulang.getTracks().forEach(t => t.stop()); streamPulang = null; document.getElementById("videoPulang").style.display="block"; document.getElementById("previewPulang").style.display="none"; }
});

document.getElementById('tab-pulang-btn').addEventListener('shown.bs.tab', function () {
    startKameraPulang();
    if(streamMasuk) { streamMasuk.getTracks().forEach(t => t.stop()); streamMasuk = null; document.getElementById("videoMasuk").style.display="block"; document.getElementById("previewMasuk").style.display="none"; }
});

// Load Kamera Masuk secara default saat pertama buka halaman
window.addEventListener('DOMContentLoaded', () => {
    <?php if(!$sudah_absen) { echo "startKameraMasuk();"; } ?>
});

function takePhotoMasuk() {
    const videoMasuk = document.getElementById("videoMasuk");
    const canvas = document.getElementById("canvasMasuk");
    canvas.width = videoMasuk.videoWidth;
    canvas.height = videoMasuk.videoHeight;
    
    const ctx = canvas.getContext("2d");
    ctx.drawImage(videoMasuk, 0, 0, canvas.width, canvas.height);
    
    const dataURL = canvas.toDataURL("image/png");
    document.getElementById("fotoMasuk").value = dataURL;

    const preview = document.getElementById("previewMasuk");
    preview.src = dataURL;
    preview.style.display = "block";
    videoMasuk.style.display = "none";

    alert("Foto masuk berhasil diambil");
}

function takePhotoPulang() {
    const videoPulang = document.getElementById("videoPulang");
    const canvas = document.getElementById("canvasPulang");
    canvas.width = videoPulang.videoWidth;
    canvas.height = videoPulang.videoHeight;
    
    const ctx = canvas.getContext("2d");
    ctx.drawImage(videoPulang, 0, 0, canvas.width, canvas.height);
    
    const dataURL = canvas.toDataURL("image/png");
    document.getElementById("fotoPulang").value = dataURL;

    const preview = document.getElementById("previewPulang");
    preview.src = dataURL;
    preview.style.display = "block";
    videoPulang.style.display = "none";

    alert("Foto pulang berhasil diambil");
}

/* ==================================
   JAM SERVER REALTIME
================================== */
function startServerClock(elementId) {
    const element = document.getElementById(elementId);
    if(!element) return;
    
    let serverTime = new Date(element.dataset.serverTime.replace(/-/g, '/'));

    function updateClock() {
        serverTime.setSeconds(serverTime.getSeconds() + 1);
        
        const tahun = serverTime.getFullYear();
        const bulan = String(serverTime.getMonth() + 1).padStart(2, '0');
        const tanggal = String(serverTime.getDate()).padStart(2, '0');
        const jam = String(serverTime.getHours()).padStart(2, '0');
        const menit = String(serverTime.getMinutes()).padStart(2, '0');
        const detik = String(serverTime.getSeconds()).padStart(2, '0');

        element.innerHTML = `${tanggal}-${bulan}-${tahun} ${jam}:${menit}:${detik}`;
    }
    updateClock();
    setInterval(updateClock, 1000);
}

startServerClock("jamServerMasuk");
startServerClock("jamServerPulang");
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>