<?php

declare(strict_types=1);

require_once __DIR__ . '/../../includes/bootstrap.php';

$config = require __DIR__ . '/../../config/config.php';

auth_start_session();
auth_require_role(['admin']);

$user = auth_user();
$title = 'Staff Locations';

$rows = [];
$error = '';

try {
    $pdo = Database::pdo();
    $rows = $pdo->query(
        "SELECT u.user_id, u.full_name, u.email, u.phone,
                sd.employee_code, sd.current_latitude, sd.current_longitude, sd.last_location_update, sd.is_available
         FROM users u
         JOIN staff_details sd ON sd.user_id = u.user_id
         WHERE u.user_type = 'staff'
         ORDER BY sd.last_location_update DESC"
    )->fetchAll();
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$nav = [
    ['label' => 'Overview', 'href' => '/pest/public/admin/index.php', 'active' => false],
    ['label' => 'Customers', 'href' => '/pest/public/admin/customers.php', 'active' => false],
    ['label' => 'Staff', 'href' => '/pest/public/admin/staff.php', 'active' => false],
    ['label' => 'Staff Locations', 'href' => '/pest/public/admin/staff_locations.php', 'active' => true],
    ['label' => 'Services', 'href' => '/pest/public/admin/services.php', 'active' => false],
    ['label' => 'Task Assignment', 'href' => '/pest/public/admin/task_assignment.php', 'active' => false],
    ['label' => 'Payments', 'href' => '/pest/public/admin/payments.php', 'active' => false],
    ['label' => 'Complaints', 'href' => '/pest/public/admin/complaints.php', 'active' => false],
    ['label' => 'Reports', 'href' => '/pest/public/admin/reports.php', 'active' => false],
];

ob_start();
?>
<?php if ($error !== ''): ?>
    <div class="rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">
        <?= e($error) ?>
    </div>
<?php endif; ?>

<div class="rounded-xl border bg-white p-6">
    <div class="flex items-start justify-between gap-4">
        <div>
            <h1 class="text-xl font-semibold">Staff Locations</h1>
            <p class="mt-1 text-sm text-slate-600">Latest known location of each staff member.</p>
        </div>
        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/admin/index.php">Back</a>
    </div>

    <div class="mt-5 overflow-x-auto">
        <table class="min-w-full text-sm">
            <thead class="text-left text-slate-600">
                <tr class="border-b">
                    <th class="py-2 pr-4">Staff</th>
                    <th class="py-2 pr-4">Employee</th>
                    <th class="py-2 pr-4">Latitude</th>
                    <th class="py-2 pr-4">Longitude</th>
                    <th class="py-2 pr-4">Updated</th>
                    <th class="py-2 pr-4">Available</th>
                    <th class="py-2 pr-4">Map</th>
                    <th class="py-2">History</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!$rows): ?>
                    <tr class="border-b">
                        <td class="py-3 text-slate-500" colspan="8">No staff locations found.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($rows as $r): ?>
                        <?php
                            $lat = $r['current_latitude'];
                            $lng = $r['current_longitude'];
                            $hasCoords = ($lat !== null && $lng !== null && $lat !== '' && $lng !== '');
                            $mapUrl = $hasCoords
                                ? 'https://www.google.com/maps?q=' . rawurlencode((string)$lat . ',' . (string)$lng)
                                : '';
                            $historyUrl = '/pest/public/admin/staff_location_history.php?staff_id=' . (int)$r['user_id'];
                        ?>
                        <tr class="border-b last:border-0">
                            <td class="py-3 pr-4">
                                <div class="font-medium"><?= e((string)$r['full_name']) ?></div>
                                <div class="text-xs text-slate-500"><?= e((string)$r['email']) ?></div>
                            </td>
                            <td class="py-3 pr-4"><?= e((string)$r['employee_code']) ?></td>
                            <td class="py-3 pr-4"><?= e((string)($lat ?? '')) ?></td>
                            <td class="py-3 pr-4"><?= e((string)($lng ?? '')) ?></td>
                            <td class="py-3 pr-4"><?= e((string)($r['last_location_update'] ?? '')) ?></td>
                            <td class="py-3 pr-4"><?= ((int)($r['is_available'] ?? 0) === 1) ? 'Yes' : 'No' ?></td>
                            <td class="py-3">
                                <?php if ($hasCoords): ?>
                                    <a class="rounded-lg border px-3 py-1.5 text-xs hover:bg-slate-50" href="<?= e($mapUrl) ?>" target="_blank" rel="noopener">Open</a>
                                <?php else: ?>
                                    <span class="text-xs text-slate-500">-</span>
                                <?php endif; ?>
                            </td>
                            <td class="py-3">
                                <a class="rounded-lg border px-3 py-1.5 text-xs hover:bg-slate-50" href="<?= e($historyUrl) ?>">View</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?php
$content = ob_get_clean();

require __DIR__ . '/../../includes/dashboard_layout.php';
