<?php
// Tampilkan semua error untuk debugging.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Judul halaman
$page_title = 'Absensi Karyawan';
// Memulai session dan memuat file yang diperlukan.
// Asumsi 'load.php' juga memulai session_start()
require_once('includes/load.php');

// Hak akses level 4 atau lebih tinggi diperlukan
page_require_level(4);

// Ambil data pengguna saat ini
$user = current_user();

// Alihkan ke halaman login jika pengguna tidak login
if (!$user) {
    redirect('login.php', false);
}

// Cek apakah tabel absensi ada
$table_check = $db->query("SHOW TABLES LIKE 'absensi'");
if ($table_check && $db->num_rows($table_check) == 0) {
    die("Tabel absensi tidak ditemukan!");
}

// Ambil data lokasi yang diizinkan dari database
$allowed_locations = array();
$locations_query = "SELECT * FROM locations WHERE status = 'active'";
$result = $db->query($locations_query);
if ($result) {
    if ($db->num_rows($result) > 0) {
        while ($row = $db->fetch_assoc($result)) {
            $allowed_locations[] = $row;
        }
    }
} else {
    // Gunakan session untuk menyimpan pesan kesalahan
    $_SESSION['msg'] = array('type' => 'danger', 'text' => 'Gagal mengambil data lokasi dari database.');
    redirect('absen.php', false);
}

// --- LOGIKA PEMROSESAN ABSENSI (DIKIRIM DARI FORMULIR) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $employee_id = $_POST['employee_id'] ?? null;
    $lokasi_terdekat = $_POST['lokasi_terdekat'] ?? null;
    $action = $_POST['action_type'] ?? null;

    $msg = array();

    // Validasi data input
    if (!$employee_id || !$lokasi_terdekat || !$action) {
        $msg = array('type' => 'danger', 'text' => 'Data tidak lengkap. Pastikan semua kolom terisi.');
    } elseif (!is_numeric($employee_id) || $employee_id <= 0) {
        $msg = array('type' => 'danger', 'text' => 'ID Karyawan tidak valid.');
    } else {
        $employee_id = (int)$employee_id;
        $current_time = date('Y-m-d H:i:s');
        $current_date = date('Y-m-d');

        if ($action === 'masuk') {
            $stmt = $db->prepare("SELECT id FROM absensi WHERE employee_id = ? AND DATE(time) = ? AND status = 'masuk'");
            $stmt->bind_param("is", $employee_id, $current_date);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows > 0) {
                $msg = array('type' => 'warning', 'text' => 'Anda sudah melakukan absensi masuk hari ini.');
            } else {
                $stmt = $db->prepare("INSERT INTO absensi (employee_id, time, status, lokasi_terdekat) VALUES (?, ?, ?, ?)");
                $stmt->bind_param("isss", $employee_id, $current_time, $action, $lokasi_terdekat);

                if ($stmt->execute()) {
                    $msg = array('type' => 'success', 'text' => 'Absensi masuk berhasil direkam.');
                } else {
                    $msg = array('type' => 'danger', 'text' => 'Gagal merekam absensi masuk. Error: ' . $stmt->error);
                }
                $stmt->close();
            }

        } elseif ($action === 'pulang') {
            $stmt = $db->prepare("SELECT id FROM absensi WHERE employee_id = ? AND DATE(time) = ? AND status = 'masuk'");
            $stmt->bind_param("is", $employee_id, $current_date);
            $stmt->execute();
            $result_masuk = $stmt->get_result();

            if ($result_masuk->num_rows === 0) {
                $msg = array('type' => 'danger', 'text' => 'Anda belum melakukan absensi masuk hari ini.');
            } else {
                $stmt_pulang = $db->prepare("SELECT id FROM absensi WHERE employee_id = ? AND DATE(time) = ? AND status = 'pulang'");
                $stmt_pulang->bind_param("is", $employee_id, $current_date);
                $stmt_pulang->execute();
                $result_pulang = $stmt_pulang->get_result();

                if ($result_pulang->num_rows > 0) {
                    $msg = array('type' => 'warning', 'text' => 'Anda sudah melakukan absensi pulang hari ini.');
                } else {
                    $stmt = $db->prepare("INSERT INTO absensi (employee_id, time, status, lokasi_terdekat) VALUES (?, ?, ?, ?)");
                    $stmt->bind_param("isss", $employee_id, $current_time, $action, $lokasi_terdekat);

                    if ($stmt->execute()) {
                        $msg = array('type' => 'success', 'text' => 'Absensi pulang berhasil direkam.');
                    } else {
                        $msg = array('type' => 'danger', 'text' => 'Gagal merekam absensi pulang. Error: ' . $stmt->error);
                    }
                    $stmt->close();
                }
            }
        }
    }
    
    // Simpan pesan ke Session sebelum redirect
    $_SESSION['msg'] = $msg;
    redirect('absen.php', false);
}

// Cek dan tampilkan pesan dari Session
$msg = array();
if (isset($_SESSION['msg'])) {
    $msg = $_SESSION['msg'];
    // Hapus pesan dari session setelah diambil agar tidak muncul lagi
    unset($_SESSION['msg']); 
}
?>

<?php include_once('layouts/header.php'); ?>

<div class="row">
    <div class="col-md-12">
        <?php
        if (!empty($msg)) {
            $alert_class = '';
            switch ($msg['type']) {
                case 'success':
                    $alert_class = 'alert-success';
                    break;
                case 'danger':
                    $alert_class = 'alert-danger';
                    break;
                case 'warning':
                    $alert_class = 'alert-warning';
                    break;
                default:
                    $alert_class = 'alert-info';
            }

            echo '<div class="alert ' . $alert_class . ' alert-dismissible fade show" role="alert">
                      ' . htmlspecialchars($msg['text']) . '
                      <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                          <span aria-hidden="true">&times;</span>
                      </button>
                  </div>';
        }
        ?>
    </div>
</div>

<div class="row">
    <div class="col-md-8 col-md-offset-2">
        <div class="panel panel-default">
            <div class="panel-heading">
                <strong><span class="glyphicon glyphicon-time"></span>
                <span>Absensi Harian</span></strong>
            </div>
            <div class="panel-body">
                <form method="post" action="" class="clearfix" id="attendance-form">
                    <div class="form-group">
                        <label for="employee_id">ID Karyawan</label>
                        <input type="number" class="form-control" name="employee_id" id="employee_id"
                               placeholder="Masukkan ID Karyawan" required min="1" autofocus>
                        <input type="hidden" name="lokasi_terdekat" id="lokasi_terdekat" required>
                        <input type="hidden" name="action_type" id="action_type">
                    </div>
                    <div class="form-group text-center mt-3">
                        <button type="submit" name="mark_checkin" class="btn btn-success btn-lg" id="checkin-btn" disabled>
                            <span class="glyphicon glyphicon-check"></span> Masuk
                        </button>
                        <button type="submit" name="mark_checkout" class="btn btn-danger btn-lg" id="checkout-btn" disabled>
                            <span class="glyphicon glyphicon-log-out"></span> Pulang
                        </button>
                    </div>
                </form>
            </div>
        </div>
        <div class="panel panel-info">
            <div class="panel-heading">
                <strong><span class="glyphicon glyphicon-globe"></span>
                <span>Informasi Lokasi</span></strong>
            </div>
            <div class="panel-body">
                <p><strong>Status Lokasi:</strong> <span id="location-status">Mencari lokasi...</span></p>
                <p><strong>Lokasi Terdekat:</strong> <span id="closest-location"></span></p>
                <p><strong>ID Karyawan:</strong> <span id="employee-status">Belum diisi</span></p>
            </div>
        </div>
    </div>
</div>

<style>
.spinner-border-sm {
    width: 1rem;
    height: 1rem;
    vertical-align: -0.125em;
    border: 0.125em solid currentColor;
    border-right-color: transparent;
    border-radius: 50%;
    animation: .75s linear infinite spinner-border;
    display: inline-block;
}
@keyframes spinner-border {
    to { transform: rotate(360deg); }
}
#location-status {
    font-weight: bold;
}
.panel {
    margin-top: 20px;
}
.btn-lg {
    margin: 0 10px;
    padding: 10px 20px;
    font-size: 16px;
}
.alert {
    margin: 20px 0;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const lokasiTerdekatInput = document.getElementById('lokasi_terdekat');
    const locationStatus = document.getElementById('location-status');
    const closestLocationEl = document.getElementById('closest-location');
    const employeeStatusEl = document.getElementById('employee-status');
    const checkinBtn = document.getElementById('checkin-btn');
    const checkoutBtn = document.getElementById('checkout-btn');
    const form = document.getElementById('attendance-form');
    const employeeIdInput = document.getElementById('employee_id');
    const actionTypeInput = document.getElementById('action_type');

    employeeIdInput.focus();

    const allowedLocations = <?php echo json_encode($allowed_locations); ?>;

    function haversineGreatCircleDistance(lat1, lon1, lat2, lon2, earthRadius = 6371) {
        const dLat = (lat2 - lat1) * Math.PI / 180;
        const dLon = (lon2 - lon1) * Math.PI / 180;
        const a =
            Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
            Math.sin(dLon / 2) * Math.sin(dLon / 2);
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        return earthRadius * c;
    }

    function processLocation(latitude, longitude) {
        let closestDistance = Infinity;
        let closestLocation = null;
        let is_location_valid = false;

        allowedLocations.forEach(location => {
            const distance = haversineGreatCircleDistance(
                latitude,
                longitude,
                parseFloat(location.latitude),
                parseFloat(location.longitude)
            );

            if (distance < closestDistance) {
                closestDistance = distance;
                closestLocation = location;
            }

            // Memeriksa apakah berada di dalam radius salah satu lokasi yang diizinkan
            if (distance <= parseFloat(location.radius_km)) {
                is_location_valid = true;
            }
        });

        if (closestLocation) {
            closestLocationEl.textContent = closestLocation.name;
            lokasiTerdekatInput.value = closestLocation.name;
        } else {
            closestLocationEl.textContent = 'Tidak Ditemukan';
            lokasiTerdekatInput.value = 'Tidak Ditemukan';
        }

        const hasEmployeeId = employeeIdInput.value.trim() !== '';
        employeeStatusEl.textContent = hasEmployeeId ? 'Terdeteksi' : 'Belum diisi';
        employeeStatusEl.style.color = hasEmployeeId ? 'green' : 'red';

        if (is_location_valid) {
            locationStatus.textContent = 'Lokasi berhasil didapatkan. Anda bisa absen.';
            locationStatus.style.color = 'green';
            checkinBtn.disabled = !hasEmployeeId;
            checkoutBtn.disabled = !hasEmployeeId;
        } else {
            locationStatus.textContent = 'Anda berada di luar lokasi proyek.';
            locationStatus.style.color = 'red';
            checkinBtn.disabled = true;
            checkoutBtn.disabled = true;
        }
    }

    function onGeolocationSuccess(position) {
        processLocation(position.coords.latitude, position.coords.longitude);
    }

    function onGeolocationError(error) {
        let errorMessage = "Gagal mendapatkan lokasi: ";
        switch(error.code) {
            case error.PERMISSION_DENIED:
                errorMessage += "Izin lokasi ditolak. Aktifkan di browser Anda.";
                break;
            case error.POSITION_UNAVAILABLE:
                errorMessage += "Informasi lokasi tidak tersedia.";
                break;
            case error.TIMEOUT:
                errorMessage += "Permintaan lokasi timeout.";
                break;
            default:
                errorMessage += "Error tidak diketahui.";
        }
        locationStatus.textContent = errorMessage;
        locationStatus.style.color = 'red';
        checkinBtn.disabled = true;
        checkoutBtn.disabled = true;
    }

    employeeIdInput.addEventListener('input', function() {
        const hasLocation = lokasiTerdekatInput.value.trim() !== '';
        const hasEmployeeId = this.value.trim() !== '';
        const isLocationValid = locationStatus.style.color === 'green';
        const canSubmit = hasLocation && hasEmployeeId && isLocationValid;

        employeeStatusEl.textContent = hasEmployeeId ? 'Terdeteksi' : 'Belum diisi';
        employeeStatusEl.style.color = hasEmployeeId ? 'green' : 'red';

        checkinBtn.disabled = !canSubmit;
        checkoutBtn.disabled = !canSubmit;
    });

    form.addEventListener('submit', function(e) {
        const submitBtn = e.submitter;
        if (submitBtn) {
            // Isi nilai input hidden dengan action yang sesuai
            if (submitBtn.id === 'checkin-btn') {
                actionTypeInput.value = 'masuk';
            } else if (submitBtn.id === 'checkout-btn') {
                actionTypeInput.value = 'pulang';
            }

            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Memproses...';

            const otherBtn = submitBtn.id === 'checkin-btn' ? checkoutBtn : checkinBtn;
            otherBtn.disabled = true;
        }
    });

    if (navigator.geolocation) {
        const options = {
            enableHighAccuracy: true,
            timeout: 10000,
            maximumAge: 0
        };
        navigator.geolocation.getCurrentPosition(onGeolocationSuccess, onGeolocationError, options);
        navigator.geolocation.watchPosition(onGeolocationSuccess, onGeolocationError, options);
    } else {
        locationStatus.textContent = "Browser Anda tidak mendukung geolocation.";
        locationStatus.style.color = 'red';
        checkinBtn.disabled = true;
        checkoutBtn.disabled = true;
    }
});
</script>

<?php include_once('layouts/footer.php'); ?>