<?php
session_start();
require_once __DIR__ . '/../config.php';

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

$token = $_SESSION['token'];

// Get user profile data
$profile_result = api_get_profil($token);
$profile_data = $profile_result['success'] ? $profile_result['data'] : [];

// Get today's attendance data
$presensi_today_result = api_get_presensi_today($token);
$presensi_today = $presensi_today_result['success'] ? $presensi_today_result['data'] : [];

// Extract user info
$pegawai = $profile_data['pegawai'] ?? $profile_data['data']['pegawai'] ?? $profile_data['data'] ?? [];
$user_name = $pegawai['nama_lengkap'] ?? $pegawai['nama'] ?? 'User';
$user_jabatan = $pegawai['jabatan']['nama_jabatan'] ?? $pegawai['jabatan'] ?? 'Karyawan';
$user_id = $pegawai['nip'] ?? $pegawai['id'] ?? '';
$user_photo = $pegawai['photo'] ?? $pegawai['foto'] ?? '';

// Extract work schedule info
$jam_masuk = $pegawai['jam_masuk'] ?? '08:00';
$jam_pulang = $pegawai['jam_pulang'] ?? '17:00';
$jam_istirahat = $pegawai['jam_istirahat'] ?? '12:00';
$kantor_nama = $pegawai['kantor']['nama_kantor'] ?? 'Kantor Pusat';
$alamat_kantor = $pegawai['kantor']['alamat_kantor'] ?? '';

echo "<h1>Debug Rekam Error</h1>";
echo "<p><strong>User Name:</strong> " . htmlspecialchars($user_name) . "</p>";
echo "<p><strong>Kantor Nama:</strong> " . htmlspecialchars($kantor_nama) . "</p>";
echo "<p><strong>Alamat Kantor:</strong> " . htmlspecialchars($alamat_kantor) . "</p>";

// Test koordinat extraction
$kantor_lat = null;
$kantor_lng = null;
$toleransi_meter = 100;

if (isset($pegawai['kantor'])) {
    $kantor = $pegawai['kantor'];
    echo "<h2>Kantor Data:</h2>";
    echo "<pre>" . print_r($kantor, true) . "</pre>";

    $kantor_lat = $kantor['latitude'] ?? $kantor['lat'] ?? $kantor['koordinat_lat'] ?? $kantor['lat_kantor'] ?? null;
    $kantor_lng = $kantor['longitude'] ?? $kantor['lng'] ?? $kantor['koordinat_lng'] ?? $kantor['lng_kantor'] ?? null;
    $toleransi_meter = $kantor['jarak_rekam_presensi'] ?? $kantor['toleransi'] ?? $kantor['radius'] ?? $kantor['jarak_toleransi'] ?? 100;

    echo "<p><strong>Kantor Lat:</strong> $kantor_lat</p>";
    echo "<p><strong>Kantor Lng:</strong> $kantor_lng</p>";
    echo "<p><strong>Toleransi:</strong> $toleransi_meter</p>";
}

// Test htmlspecialchars
echo "<h2>Test htmlspecialchars:</h2>";
echo "<p>Kantor Nama (string): " . htmlspecialchars($kantor_nama) . "</p>";
echo "<p>Alamat Kantor (string): " . htmlspecialchars($alamat_kantor) . "</p>";

echo "<hr>";
echo "<p><a href='rekam.php'>← Kembali ke Rekam Presensi</a></p>";
