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

// Mulai sesi
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Sertakan file load.php untuk koneksi database dan fungsi lainnya
require_once('includes/load.php');

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Ambil data yang dikirimkan, gunakan null coalescing operator untuk keamanan
    $employee_id = $_POST['employee_id'] ?? null;
    $latitude = $_POST['latitude'] ?? null;
    $longitude = $_POST['longitude'] ?? null;
    $closest_location_name = $_POST['closest_location_name'] ?? null;
    $distance_meter = $_POST['distance_meter'] ?? null;
    $action = isset($_POST['mark_checkin']) ? 'checkin' : (isset($_POST['mark_checkout']) ? 'checkout' : null);

    // Validasi input awal
    if (!$employee_id || !$latitude || !$longitude || !$action) {
        $_SESSION['msg'] = array('type' => 'danger', 'text' => 'Data tidak lengkap. Pastikan semua kolom terisi.');
        redirect('absen.php');
    }

    $current_time = date('Y-m-d H:i:s');
    $current_date = date('Y-m-d');

    if ($action === 'checkin') {
        // Cek apakah karyawan sudah check-in hari ini
        $stmt = $db->prepare("SELECT id FROM absensi WHERE employee_id = ? AND DATE(checkin_time) = ?");
        $stmt->bind_param("is", $employee_id, $current_date);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            $_SESSION['msg'] = array('type' => 'warning', 'text' => 'Anda sudah melakukan absensi masuk hari ini.');
            redirect('absen.php');
        }

        // Hitung status absensi
        $start_of_shift = strtotime($current_date . ' 08:00:00');
        $status = (strtotime($current_time) > $start_of_shift) ? 'terlambat' : 'hadir';

        // Query untuk menyimpan data check-in
        $stmt = $db->prepare("INSERT INTO absensi (
            employee_id, checkin_time, checkin_latitude, checkin_longitude,
            checkin_location_name, checkin_distance_meter, status
        ) VALUES (?, ?, ?, ?, ?, ?, ?)");
        
        $stmt->bind_param("isdddsi", 
            $employee_id, $current_time, $latitude, $longitude, 
            $closest_location_name, $distance_meter, $status
        );

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

    } elseif ($action === 'checkout') {
        // Cek apakah karyawan sudah check-in hari ini dan belum checkout
        $stmt = $db->prepare("SELECT id FROM absensi WHERE employee_id = ? AND DATE(checkin_time) = ? AND checkout_time IS NULL");
        $stmt->bind_param("is", $employee_id, $current_date);
        $stmt->execute();
        $result = $stmt->get_result();
        $attendance = $result->fetch_assoc();

        if (!$attendance) {
            $_SESSION['msg'] = array('type' => 'danger', 'text' => 'Anda belum melakukan absensi masuk atau sudah pulang hari ini.');
            redirect('absen.php');
        }

        // Query untuk update data absensi pulang
        $stmt = $db->prepare("UPDATE absensi SET
            checkout_time = ?,
            checkout_latitude = ?,
            checkout_longitude = ?,
            checkout_location_name = ?,
            checkout_distance_meter = ?,
            status = 'pulang'
        WHERE id = ?");
        
        $stmt->bind_param("sdddsi", 
            $current_time, $latitude, $longitude, 
            $closest_location_name, $distance_meter, $attendance['id']
        );

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

} else {
    // Jika diakses langsung tanpa POST
    $_SESSION['msg'] = array('type' => 'danger', 'text' => 'Akses tidak sah.');
}

redirect('absen.php');

?>