<?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 Location History';

$staffId = (int)($_GET['staff_id'] ?? 0);
$sessionId = (int)($_GET['session_id'] ?? 0);

$staff = null;
$sessions = [];
$points = [];
$error = '';

try {
    $pdo = Database::pdo();

    if ($staffId > 0) {
        $stmt = $pdo->prepare(
            "SELECT u.user_id, u.full_name, u.email, sd.employee_code
             FROM users u
             LEFT JOIN staff_details sd ON sd.user_id = u.user_id
             WHERE u.user_id = :id AND u.user_type = 'staff'
             LIMIT 1"
        );
        $stmt->execute(['id' => $staffId]);
        $staff = $stmt->fetch();

        if ($staff) {
            $sessions = StaffLocationService::getSessions($pdo, $staffId, 30);

            if ($sessionId <= 0 && $sessions) {
                $sessionId = (int)($sessions[0]['session_id'] ?? 0);
            }

            if ($sessionId > 0) {
                $points = StaffLocationService::getPoints($pdo, $sessionId, 2000);
            }
        } else {
            $error = 'Staff member not found.';
        }
    } else {
        $error = 'Missing staff_id.';
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$nav = [
    ['label' => 'Overview', 'href' => Constants::APP_ROOT . '/admin/index.php', 'active' => false],
    ['label' => 'Customers', 'href' => Constants::APP_ROOT . '/admin/customers.php', 'active' => false],
    ['label' => 'Staff', 'href' => Constants::APP_ROOT . '/admin/staff.php', 'active' => false],
    ['label' => 'Staff Locations', 'href' => Constants::APP_ROOT . '/admin/staff_locations.php', 'active' => false],
    ['label' => 'Services', 'href' => Constants::APP_ROOT . '/admin/services.php', 'active' => false],
    ['label' => 'Task Assignment', 'href' => Constants::APP_ROOT . '/admin/task_assignment.php', 'active' => false],
    ['label' => 'Payments', 'href' => Constants::APP_ROOT . '/admin/payments.php', 'active' => false],
    ['label' => 'Complaints', 'href' => Constants::APP_ROOT . '/admin/complaints.php', 'active' => false],
    ['label' => 'Reports', 'href' => Constants::APP_ROOT . '/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 Location History</h1>
            <?php if ($staff): ?>
                <p class="mt-1 text-sm text-slate-600">
                    <?= e((string)$staff['full_name']) ?> (<?= e((string)$staff['employee_code']) ?>)
                </p>
            <?php else: ?>
                <p class="mt-1 text-sm text-slate-600">View check-in to check-out location points.</p>
            <?php endif; ?>
        </div>
        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/admin/staff_locations.php">Back</a>
    </div>

    <?php if ($staff && $sessions): ?>
        <div class="mt-5">
            <label class="block text-sm font-medium">Session</label>
            <select class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" onchange="if (this.value) window.location.href=this.value;">
                <?php foreach ($sessions as $s): ?>
                    <?php
                        $sid = (int)($s['session_id'] ?? 0);
                        $in = (string)($s['check_in_at'] ?? '');
                        $out = (string)($s['check_out_at'] ?? '');
                        $label = $in . ($out !== '' ? (' → ' . $out) : ' → (Active)');
                        $url = Constants::APP_ROOT . '/admin/staff_location_history.php?staff_id=' . (int)$staffId . '&session_id=' . $sid;
                    ?>
                    <option value="<?= e($url) ?>" <?= ($sid === $sessionId) ? 'selected' : '' ?>><?= e($label) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
    <?php endif; ?>

    <?php if ($staff && !$sessions): ?>
        <div class="mt-5 rounded-xl border bg-slate-50 p-4 text-sm text-slate-600">
            No location sessions found for this staff member.
            Staff must click <span class="font-medium">Start Day</span> in their Location Tracker to begin logging points.
        </div>
    <?php endif; ?>

    <div class="mt-6">
        <div class="flex items-center justify-between">
            <h2 class="text-base font-semibold">Location Points</h2>
            <div class="text-xs text-slate-500"><?= e((string)count($points)) ?> points</div>
        </div>

        <div class="mt-4 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">Time</th>
                        <th class="py-2 pr-4">Latitude</th>
                        <th class="py-2 pr-4">Longitude</th>
                        <th class="py-2 pr-4">Accuracy</th>
                        <th class="py-2">Map</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!$points): ?>
                        <tr class="border-b">
                            <td class="py-3 text-slate-500" colspan="5">No location points found for this session.</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($points as $p): ?>
                            <?php
                                $lat = (string)($p['latitude'] ?? '');
                                $lng = (string)($p['longitude'] ?? '');
                                $mapUrl = 'https://www.google.com/maps?q=' . rawurlencode($lat . ',' . $lng);
                            ?>
                            <tr class="border-b last:border-0">
                                <td class="py-3 pr-4 font-medium"><?= e((string)($p['recorded_at'] ?? '')) ?></td>
                                <td class="py-3 pr-4"><?= e($lat) ?></td>
                                <td class="py-3 pr-4"><?= e($lng) ?></td>
                                <td class="py-3 pr-4"><?= e((string)($p['accuracy_meters'] ?? '')) ?></td>
                                <td class="py-3">
                                    <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>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php
$content = ob_get_clean();

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