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

// Check if user is logged in
if (!isset($_SESSION['token'])) {
    header('Location: login.php');
    exit;
}

$token = $_SESSION['token'];
$user_data = $_SESSION['user_data'] ?? [];

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

// Extract user info
$pegawai = $profile_data['pegawai'] ?? $profile_data['data']['pegawai'] ?? $profile_data['data'] ?? [];
$user_name = $pegawai['nama_lengkap'] ?? $pegawai['nama'] ?? $user_data['nama'] ?? $user_data['nama_lengkap'] ?? 'User';
$user_id = $pegawai['nip'] ?? $pegawai['id'] ?? $user_data['id'] ?? $user_data['nip'] ?? '';

// Extract kantor coordinates
$kantor_lat = $pegawai['kantor']['latitude'] ?? $pegawai['kantor']['lat'] ?? $user_data['kantor_lat'] ?? -6.2088;
$kantor_lng = $pegawai['kantor']['longitude'] ?? $pegawai['kantor']['lng'] ?? $user_data['kantor_lng'] ?? 106.8456;
$toleransi_meter = $pegawai['kantor']['toleransi'] ?? $pegawai['toleransi'] ?? $user_data['toleransi'] ?? 100;

$debug_results = [];
$test_coordinates = [
    ['lat' => -6.2088, 'lng' => 106.8456, 'name' => 'Jakarta (Kantor)'],
    ['lat' => -6.2090, 'lng' => 106.8458, 'name' => 'Jakarta (50m dari kantor)'],
    ['lat' => -6.2100, 'lng' => 106.8470, 'name' => 'Jakarta (200m dari kantor)'],
    ['lat' => -6.3000, 'lng' => 106.9000, 'name' => 'Jakarta (Jauh dari kantor)'],
];

// Test presensi untuk setiap koordinat
foreach ($test_coordinates as $coord) {
    $data = [
        'latitude' => $coord['lat'],
        'longitude' => $coord['lng'],
        'waktu' => date('Y-m-d H:i:s')
    ];

    // Test masuk
    $result_masuk = api_save_masuk($token, $data);

    // Test pulang
    $result_pulang = api_save_pulang($token, $data);

    // Test istirahat
    $result_istirahat = api_save_istirahat($token, $data);

    $debug_results[] = [
        'location' => $coord['name'],
        'coordinates' => $coord['lat'] . ', ' . $coord['lng'],
        'masuk' => $result_masuk,
        'pulang' => $result_pulang,
        'istirahat' => $result_istirahat
    ];
}
?>
<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Debug Presensi Submit - Sistem Presensi Bank BIJ</title>
    <link rel="stylesheet" href="<?php echo asset('css/tailwind-essential.css'); ?>">
    <style>
        @font-face {
            font-family: 'Outfit';
            font-style: normal;
            font-weight: 300;
            font-display: swap;
            src: url('assets/webfonts/Outfit-Light.woff2') format('woff2');
        }

        @font-face {
            font-family: 'Outfit';
            font-style: normal;
            font-weight: 400;
            font-display: swap;
            src: url('assets/webfonts/Outfit-Regular.woff2') format('woff2');
        }

        @font-face {
            font-family: 'Outfit';
            font-style: normal;
            font-weight: 500;
            font-display: swap;
            src: url('assets/webfonts/Outfit-Medium.woff2') format('woff2');
        }

        @font-face {
            font-family: 'Outfit';
            font-style: normal;
            font-weight: 600;
            font-display: swap;
            src: url('assets/webfonts/Outfit-SemiBold.woff2') format('woff2');
        }

        @font-face {
            font-family: 'Outfit';
            font-style: normal;
            font-weight: 700;
            font-display: swap;
            src: url('assets/webfonts/Outfit-Bold.woff2') format('woff2');
        }

        body {
            font-family: 'Outfit', sans-serif;
        }

        .code-block {
            background: #1e1e1e;
            color: #d4d4d4;
            padding: 1rem;
            border-radius: 0.5rem;
            font-family: 'Courier New', monospace;
            font-size: 0.875rem;
            overflow-x: auto;
        }

        .success {
            color: #10b981;
        }

        .error {
            color: #ef4444;
        }

        .warning {
            color: #f59e0b;
        }
    </style>
</head>

<body class="bg-gray-100 min-h-screen">
    <div class="container mx-auto px-4 py-8">
        <!-- Header -->
        <div class="bg-white rounded-lg shadow-lg p-6 mb-6">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-2xl font-bold text-gray-800">Debug Presensi Submit</h1>
                    <p class="text-gray-600">Test API response untuk berbagai koordinat</p>
                </div>
                <div class="text-right">
                    <p class="text-sm text-gray-500">User: <?php echo htmlspecialchars($user_name); ?></p>
                    <p class="text-sm text-gray-500">NIP: <?php echo htmlspecialchars($user_id); ?></p>
                </div>
            </div>
        </div>

        <!-- Kantor Info -->
        <div class="bg-white rounded-lg shadow-lg p-6 mb-6">
            <h2 class="text-xl font-bold text-gray-800 mb-4">Informasi Kantor</h2>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                    <p class="text-sm text-gray-500">Koordinat Kantor</p>
                    <p class="font-mono text-lg"><?php echo $kantor_lat; ?>, <?php echo $kantor_lng; ?></p>
                </div>
                <div>
                    <p class="text-sm text-gray-500">Toleransi</p>
                    <p class="font-mono text-lg"><?php echo $toleransi_meter; ?> meter</p>
                </div>
                <div>
                    <p class="text-sm text-gray-500">Token</p>
                    <p class="font-mono text-sm"><?php echo substr($token, 0, 20); ?>...</p>
                </div>
            </div>
        </div>

        <!-- Test Results -->
        <div class="space-y-6">
            <?php foreach ($debug_results as $index => $result): ?>
                <div class="bg-white rounded-lg shadow-lg p-6">
                    <h3 class="text-lg font-bold text-gray-800 mb-4">
                        Test <?php echo $index + 1; ?>: <?php echo htmlspecialchars($result['location']); ?>
                    </h3>
                    <p class="text-sm text-gray-600 mb-4">Koordinat: <?php echo $result['coordinates']; ?></p>

                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <!-- Masuk -->
                        <div class="border rounded-lg p-4">
                            <h4 class="font-semibold text-gray-700 mb-2">
                                <i class="fas fa-sign-in-alt mr-2"></i>Masuk
                            </h4>
                            <div class="space-y-2">
                                <p class="text-sm">
                                    <span class="font-medium">Status:</span>
                                    <span class="<?php echo $result['masuk']['success'] ? 'success' : 'error'; ?>">
                                        <?php echo $result['masuk']['success'] ? 'SUCCESS' : 'ERROR'; ?>
                                    </span>
                                </p>
                                <p class="text-sm">
                                    <span class="font-medium">HTTP Code:</span>
                                    <?php echo $result['masuk']['http_code']; ?>
                                </p>
                                <?php if (isset($result['masuk']['data']['pesan'])): ?>
                                    <p class="text-sm">
                                        <span class="font-medium">Pesan:</span>
                                        <span class="<?php echo $result['masuk']['success'] ? 'success' : 'error'; ?>">
                                            <?php echo htmlspecialchars($result['masuk']['data']['pesan']); ?>
                                        </span>
                                    </p>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Pulang -->
                        <div class="border rounded-lg p-4">
                            <h4 class="font-semibold text-gray-700 mb-2">
                                <i class="fas fa-sign-out-alt mr-2"></i>Pulang
                            </h4>
                            <div class="space-y-2">
                                <p class="text-sm">
                                    <span class="font-medium">Status:</span>
                                    <span class="<?php echo $result['pulang']['success'] ? 'success' : 'error'; ?>">
                                        <?php echo $result['pulang']['success'] ? 'SUCCESS' : 'ERROR'; ?>
                                    </span>
                                </p>
                                <p class="text-sm">
                                    <span class="font-medium">HTTP Code:</span>
                                    <?php echo $result['pulang']['http_code']; ?>
                                </p>
                                <?php if (isset($result['pulang']['data']['pesan'])): ?>
                                    <p class="text-sm">
                                        <span class="font-medium">Pesan:</span>
                                        <span class="<?php echo $result['pulang']['success'] ? 'success' : 'error'; ?>">
                                            <?php echo htmlspecialchars($result['pulang']['data']['pesan']); ?>
                                        </span>
                                    </p>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Istirahat -->
                        <div class="border rounded-lg p-4">
                            <h4 class="font-semibold text-gray-700 mb-2">
                                <i class="fas fa-coffee mr-2"></i>Istirahat
                            </h4>
                            <div class="space-y-2">
                                <p class="text-sm">
                                    <span class="font-medium">Status:</span>
                                    <span class="<?php echo $result['istirahat']['success'] ? 'success' : 'error'; ?>">
                                        <?php echo $result['istirahat']['success'] ? 'SUCCESS' : 'ERROR'; ?>
                                    </span>
                                </p>
                                <p class="text-sm">
                                    <span class="font-medium">HTTP Code:</span>
                                    <?php echo $result['istirahat']['http_code']; ?>
                                </p>
                                <?php if (isset($result['istirahat']['data']['pesan'])): ?>
                                    <p class="text-sm">
                                        <span class="font-medium">Pesan:</span>
                                        <span class="<?php echo $result['istirahat']['success'] ? 'success' : 'error'; ?>">
                                            <?php echo htmlspecialchars($result['istirahat']['data']['pesan']); ?>
                                        </span>
                                    </p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Raw Response -->
                    <div class="mt-4">
                        <h5 class="font-semibold text-gray-700 mb-2">Raw Response (Masuk):</h5>
                        <div class="code-block">
                            <?php echo htmlspecialchars(json_encode($result['masuk'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- Manual Test Form -->
        <div class="bg-white rounded-lg shadow-lg p-6 mt-6">
            <h2 class="text-xl font-bold text-gray-800 mb-4">Manual Test</h2>
            <form method="POST" class="space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Latitude</label>
                        <input type="number" name="test_lat" step="any" value="-6.2088"
                            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Longitude</label>
                        <input type="number" name="test_lng" step="any" value="106.8456"
                            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Action</label>
                    <select name="test_action" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        <option value="masuk">Masuk</option>
                        <option value="pulang">Pulang</option>
                        <option value="istirahat">Istirahat</option>
                    </select>
                </div>
                <button type="submit" name="manual_test"
                    class="w-full bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700 transition-colors">
                    <i class="fas fa-play mr-2"></i>Test Manual
                </button>
            </form>

            <?php if (isset($_POST['manual_test'])): ?>
                <div class="mt-6 p-4 bg-gray-50 rounded-lg">
                    <h3 class="font-semibold text-gray-700 mb-2">Manual Test Result:</h3>
                    <?php
                    $manual_data = [
                        'latitude' => $_POST['test_lat'],
                        'longitude' => $_POST['test_lng'],
                        'waktu' => date('Y-m-d H:i:s')
                    ];

                    $manual_result = null;
                    switch ($_POST['test_action']) {
                        case 'masuk':
                            $manual_result = api_save_masuk($token, $manual_data);
                            break;
                        case 'pulang':
                            $manual_result = api_save_pulang($token, $manual_data);
                            break;
                        case 'istirahat':
                            $manual_result = api_save_istirahat($token, $manual_data);
                            break;
                    }
                    ?>
                    <div class="space-y-2">
                        <p class="text-sm">
                            <span class="font-medium">Status:</span>
                            <span class="<?php echo $manual_result['success'] ? 'success' : 'error'; ?>">
                                <?php echo $manual_result['success'] ? 'SUCCESS' : 'ERROR'; ?>
                            </span>
                        </p>
                        <p class="text-sm">
                            <span class="font-medium">HTTP Code:</span>
                            <?php echo $manual_result['http_code']; ?>
                        </p>
                        <?php if (isset($manual_result['data']['pesan'])): ?>
                            <p class="text-sm">
                                <span class="font-medium">Pesan:</span>
                                <span class="<?php echo $manual_result['success'] ? 'success' : 'error'; ?>">
                                    <?php echo htmlspecialchars($manual_result['data']['pesan']); ?>
                                </span>
                            </p>
                        <?php endif; ?>
                    </div>
                    <div class="mt-4">
                        <h5 class="font-semibold text-gray-700 mb-2">Raw Response:</h5>
                        <div class="code-block">
                            <?php echo htmlspecialchars(json_encode($manual_result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); ?>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <!-- Navigation -->
        <div class="mt-6 text-center">
            <a href="rekam.php" class="inline-flex items-center text-blue-600 hover:text-blue-800">
                <i class="fas fa-arrow-left mr-2"></i> Kembali ke Rekam Presensi
            </a>
        </div>
    </div>
</body>

</html>