<?php

declare(strict_types=1);

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

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

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

$user = auth_user();
$title = 'Location Tracker';

$staffId = (int)($user['user_id'] ?? 0);
$current = null;
$error = '';

try {
    $pdo = Database::pdo();
    $stmt = $pdo->prepare('SELECT current_latitude, current_longitude, last_location_update FROM staff_details WHERE user_id = :uid LIMIT 1');
    $stmt->execute(['uid' => $staffId]);
    $current = $stmt->fetch();
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$nav = [
    ['label' => 'Overview', 'href' => '/pest/public/staff/overview.php', 'active' => false],
    ['label' => 'My Tasks', 'href' => '/pest/public/staff/index.php', 'active' => false],
    ['label' => 'Task Details', 'href' => '/pest/public/staff/task_details.php', 'active' => false],
    ['label' => 'Upload Images', 'href' => '/pest/public/staff/upload_images.php', 'active' => false],
    ['label' => 'Location Tracker', 'href' => '/pest/public/staff/location.php', 'active' => true],
    ['label' => 'Task History', 'href' => '/pest/public/staff/history.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">Update My Location</h1>
            <p class="mt-1 text-sm text-slate-600">Allow location access in your browser to update your current coordinates.</p>
        </div>
        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/staff/index.php">Back</a>
    </div>

    <div class="mt-5">
        <button id="btnGet" type="button" class="w-full rounded-2xl bg-gradient-to-b from-blue-600 to-blue-700 px-6 py-4 text-base font-semibold text-white shadow-lg hover:from-blue-500 hover:to-blue-700 active:translate-y-px">
            Get Location
        </button>
        <div class="mt-2 text-xs text-slate-500">Tap once and allow permission when asked.</div>
    </div>

    <div class="mt-5 grid grid-cols-1 gap-4 md:grid-cols-2">
        <div class="rounded-xl border bg-slate-50 p-4">
            <div class="text-xs font-medium text-slate-600">Last saved</div>
            <div class="mt-2 text-sm">
                <div><span class="text-slate-500">Latitude:</span> <span class="font-medium" id="lastLat"><?= e((string)($current['current_latitude'] ?? '')) ?></span></div>
                <div class="mt-1"><span class="text-slate-500">Longitude:</span> <span class="font-medium" id="lastLng"><?= e((string)($current['current_longitude'] ?? '')) ?></span></div>
                <div class="mt-1"><span class="text-slate-500">Updated:</span> <span class="font-medium"><?= e((string)($current['last_location_update'] ?? '')) ?></span></div>
            </div>
        </div>

        <div class="rounded-xl border bg-white p-4">
            <div class="text-xs font-medium text-slate-600">Current (device)</div>
            <div class="mt-2 text-sm">
                <div><span class="text-slate-500">Latitude:</span> <span class="font-medium" id="curLat">-</span></div>
                <div class="mt-1"><span class="text-slate-500">Longitude:</span> <span class="font-medium" id="curLng">-</span></div>
                <div class="mt-1"><span class="text-slate-500">Accuracy:</span> <span class="font-medium" id="curAcc">-</span></div>
                <div class="mt-3 grid grid-cols-1 gap-2">
                    <button id="btnStartDay" type="button" class="w-full rounded-xl bg-emerald-600 px-4 py-3 text-sm font-semibold text-white shadow hover:bg-emerald-500 disabled:opacity-50" disabled>Start Day</button>
                    <button id="btnEndDay" type="button" class="w-full rounded-xl bg-rose-600 px-4 py-3 text-sm font-semibold text-white shadow hover:bg-rose-500 disabled:opacity-50" disabled>End Day</button>
                    <button id="btnSave" type="button" class="w-full rounded-xl bg-slate-900 px-4 py-3 text-sm font-semibold text-white shadow hover:bg-slate-800 disabled:opacity-50" disabled>Save Location</button>
                </div>
                <div class="mt-3 text-sm" id="status"></div>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    var btnGet = document.getElementById('btnGet');
    var btnStartDay = document.getElementById('btnStartDay');
    var btnEndDay = document.getElementById('btnEndDay');
    var btnSave = document.getElementById('btnSave');
    var curLatEl = document.getElementById('curLat');
    var curLngEl = document.getElementById('curLng');
    var curAccEl = document.getElementById('curAcc');
    var statusEl = document.getElementById('status');
    var lastLatEl = document.getElementById('lastLat');
    var lastLngEl = document.getElementById('lastLng');

    var coords = null;

    function setStatus(text, type) {
        statusEl.textContent = text || '';
        statusEl.className = type === 'ok'
            ? 'mt-3 rounded-lg border border-green-200 bg-green-50 px-3 py-2 text-green-800'
            : type === 'err'
                ? 'mt-3 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-red-700'
                : 'mt-3 text-slate-600';
    }

    btnGet.addEventListener('click', function () {
        if (!navigator.geolocation) {
            setStatus('Geolocation is not supported by this browser.', 'err');
            return;
        }

        setStatus('Getting location...', '');
        btnSave.disabled = true;
        btnStartDay.disabled = true;
        btnEndDay.disabled = true;

        navigator.geolocation.getCurrentPosition(function (pos) {
            coords = {
                lat: pos.coords.latitude,
                lng: pos.coords.longitude,
                acc: pos.coords.accuracy
            };
            curLatEl.textContent = String(coords.lat);
            curLngEl.textContent = String(coords.lng);
            curAccEl.textContent = String(coords.acc) + 'm';
            btnSave.disabled = false;
            btnStartDay.disabled = false;
            btnEndDay.disabled = false;
            setStatus('Location fetched. Click Save Location.', 'ok');
        }, function (err) {
            setStatus('Failed to get location: ' + (err && err.message ? err.message : 'Unknown error'), 'err');
        }, {
            enableHighAccuracy: true,
            timeout: 10000,
            maximumAge: 0
        });
    });

    btnSave.addEventListener('click', function () {
        if (!coords) return;
        setStatus('Saving...', '');
        btnSave.disabled = true;

        var form = new FormData();
        form.append('lat', String(coords.lat));
        form.append('lng', String(coords.lng));
        form.append('acc', String(coords.acc || ''));

        fetch('/pest/public/staff/location_save.php', {
            method: 'POST',
            body: form,
            credentials: 'same-origin'
        }).then(function (r) {
            return r.text().then(function (t) {
                try { return JSON.parse(t); } catch (e) { return { ok: false, error: t || 'Invalid response' }; }
            });
        }).then(function (data) {
            if (data && data.ok) {
                if (lastLatEl) lastLatEl.textContent = String(coords.lat);
                if (lastLngEl) lastLngEl.textContent = String(coords.lng);
                setStatus('Saved successfully.', 'ok');
            } else {
                setStatus('Save failed: ' + (data && data.error ? data.error : 'Unknown error'), 'err');
            }
        }).catch(function () {
            setStatus('Save failed.', 'err');
        }).finally(function () {
            btnSave.disabled = false;
        });
    });

    btnStartDay.addEventListener('click', function () {
        if (!coords) return;
        setStatus('Starting day (check-in)...', '');
        btnStartDay.disabled = true;

        var form = new FormData();
        form.append('lat', String(coords.lat));
        form.append('lng', String(coords.lng));
        form.append('acc', String(coords.acc || ''));
        form.append('action', 'start_day');

        fetch('/pest/public/staff/location_save.php', {
            method: 'POST',
            body: form,
            credentials: 'same-origin'
        }).then(function (r) {
            return r.text().then(function (t) {
                try { return JSON.parse(t); } catch (e) { return { ok: false, error: t || 'Invalid response' }; }
            });
        }).then(function (data) {
            if (data && data.ok) {
                if (lastLatEl) lastLatEl.textContent = String(coords.lat);
                if (lastLngEl) lastLngEl.textContent = String(coords.lng);
                setStatus('Checked in successfully. Admin can now see your location.', 'ok');
            } else {
                setStatus('Check-in failed: ' + (data && data.error ? data.error : 'Unknown error'), 'err');
            }
        }).catch(function () {
            setStatus('Check-in failed.', 'err');
        }).finally(function () {
            btnStartDay.disabled = false;
        });
    });

    btnEndDay.addEventListener('click', function () {
        if (!coords) return;
        setStatus('Ending day (check-out)...', '');
        btnEndDay.disabled = true;

        var form = new FormData();
        form.append('lat', String(coords.lat));
        form.append('lng', String(coords.lng));
        form.append('acc', String(coords.acc || ''));
        form.append('action', 'end_day');

        fetch('/pest/public/staff/location_save.php', {
            method: 'POST',
            body: form,
            credentials: 'same-origin'
        }).then(function (r) {
            return r.text().then(function (t) {
                try { return JSON.parse(t); } catch (e) { return { ok: false, error: t || 'Invalid response' }; }
            });
        }).then(function (data) {
            if (data && data.ok) {
                if (lastLatEl) lastLatEl.textContent = String(coords.lat);
                if (lastLngEl) lastLngEl.textContent = String(coords.lng);
                setStatus('Checked out successfully.', 'ok');
            } else {
                setStatus('Check-out failed: ' + (data && data.error ? data.error : 'Unknown error'), 'err');
            }
        }).catch(function () {
            setStatus('Check-out failed.', 'err');
        }).finally(function () {
            btnEndDay.disabled = false;
        });
    });
})();
</script>
<?php
$content = ob_get_clean();

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