<?php
require_once(__DIR__ . "/../header.php");
require_once(__DIR__ . "/../../public/connection.php");

if (!isset($_SESSION)) session_start();

/* ================= SAVE GEO-FENCE ================= */
if (isset($_POST['save_geo'])) {
    $lat    = $_POST['latitude'];
    $lng    = $_POST['longitude'];
    $radius = $_POST['radius'];
    $active = $_POST['is_active'];

    $connection->query("
        UPDATE geo_fence_settings SET
        latitude='$lat',
        longitude='$lng',
        radius_meters='$radius',
        is_active='$active'
    ");
}

/* ================= RESET DEVICE ================= */
if (isset($_GET['reset_device'])) {
    $staff_id = intval($_GET['reset_device']);
    $connection->query("
        UPDATE staff_device_binding
        SET is_active=0
        WHERE staff_id=$staff_id
    ");
}

/* ================= FETCH DATA ================= */
$geo = $connection->query("
    SELECT * FROM geo_fence_settings LIMIT 1
")->fetch_assoc();

$logs = $connection->query("
    SELECT 
        s.id AS staff_id,
        s.name,
        l.ip_address,
        l.latitude,
        l.longitude,
        l.scan_time,
        d.device_hash,
        d.last_used_at
    FROM staff_attendance_logs l
    JOIN staff s ON s.id = l.staff_id
    LEFT JOIN staff_device_binding d ON d.staff_id = s.id
    ORDER BY l.scan_time DESC
");
?>

<!-- PAGE TITLE -->
<div class="page-title mb-4">
    <h1 class="mb-1">
        <i class="fa fa-shield-alt text-primary"></i>
        Attendance Security Control
    </h1>
    <p class="text-muted">
        Configure geo-fencing rules and monitor staff attendance security logs.
    </p>
</div>

<style>
.card{
    border-radius:14px;
}
.card-header{
    background:#fff;
    font-weight:600;
}
.form-label{
    font-weight:600;
}
.badge-device{
    font-size:0.75rem;
    font-family:monospace;
}
.table th{
    white-space:nowrap;
}
.table td{
    vertical-align:middle;
}
.geo-status{
    font-size:0.85rem;
}
</style>

<!-- ================= GEO-FENCE SETTINGS ================= -->
<div class="card shadow-sm mb-4">
    <div class="card-header d-flex justify-content-between align-items-center">
        <span>
            <i class="fa fa-map-marker-alt text-danger"></i>
            Geo-Fence Configuration
        </span>
        <span class="badge <?= $geo['is_active'] ? 'bg-success' : 'bg-secondary' ?> geo-status">
            <?= $geo['is_active'] ? 'ACTIVE' : 'DISABLED' ?>
        </span>
    </div>

    <div class="card-body">
        <form method="POST" class="row g-3">

            <div class="col-md-4">
                <label class="form-label">School Latitude</label>
                <input type="text"
                       name="latitude"
                       value="<?= htmlspecialchars($geo['latitude']) ?>"
                       class="form-control"
                       required>
            </div>

            <div class="col-md-4">
                <label class="form-label">School Longitude</label>
                <input type="text"
                       name="longitude"
                       value="<?= htmlspecialchars($geo['longitude']) ?>"
                       class="form-control"
                       required>
            </div>

            <div class="col-md-2">
                <label class="form-label">Radius (meters)</label>
                <input type="number"
                       name="radius"
                       value="<?= htmlspecialchars($geo['radius_meters']) ?>"
                       class="form-control"
                       required>
            </div>

            <div class="col-md-2">
                <label class="form-label">Geo-Fence Status</label>
                <select name="is_active" class="form-select">
                    <option value="1" <?= $geo['is_active'] ? 'selected' : '' ?>>Enabled</option>
                    <option value="0" <?= !$geo['is_active'] ? 'selected' : '' ?>>Disabled</option>
                </select>
            </div>

            <div class="col-12 text-end">
                <button name="save_geo" class="btn btn-primary px-4">
                    <i class="fa fa-save"></i> Save Settings
                </button>
            </div>
        </form>
    </div>
</div>

<!-- ================= SECURITY LOGS ================= -->
<div class="card shadow-sm">
    <div class="card-header">
        <i class="fa fa-lock text-dark"></i>
        Attendance Security Logs
    </div>

    <div class="card-body table-responsive">
        <table class="table table-bordered table-hover align-middle">
            <thead class="table-light">
                <tr>
                    <th>Staff</th>
                    <th>IP Address</th>
                    <th>GPS Location</th>
                    <th>Device Fingerprint</th>
                    <th>Scan Activity</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>

            <?php if ($logs->num_rows == 0): ?>
                <tr>
                    <td colspan="6" class="text-center text-muted py-4">
                        No attendance scans recorded yet
                    </td>
                </tr>
            <?php endif; ?>

            <?php while ($row = $logs->fetch_assoc()): ?>
                <tr>
                    <td>
                        <strong><?= htmlspecialchars($row['name']) ?></strong><br>
                        <small class="text-muted">
                            Staff ID: <?= $row['staff_id'] ?>
                        </small>
                    </td>

                    <td>
                        <span class="text-muted"><?= htmlspecialchars($row['ip_address']) ?></span>
                    </td>

                    <td>
                        <small>
                            <?= htmlspecialchars($row['latitude']) ?>,<br>
                            <?= htmlspecialchars($row['longitude']) ?>
                        </small>
                    </td>

                    <td>
                        <?php if ($row['device_hash']): ?>
                            <span class="badge bg-secondary badge-device">
                                <?= substr($row['device_hash'], 0, 18) ?>…
                            </span>
                        <?php else: ?>
                            <span class="badge bg-light text-muted">No device</span>
                        <?php endif; ?>
                    </td>

                    <td>
                        <?= htmlspecialchars($row['scan_time']) ?><br>
                        <small class="text-muted">
                            Last used: <?= htmlspecialchars($row['last_used_at'] ?? '—') ?>
                        </small>
                    </td>

                    <td>
                        <a href="?reset_device=<?= $row['staff_id'] ?>"
                           class="btn btn-sm btn-outline-danger"
                           onclick="return confirm('Reset device for this staff?')">
                            <i class="fa fa-sync-alt"></i> Reset
                        </a>
                    </td>
                </tr>
            <?php endwhile; ?>

            </tbody>
        </table>
    </div>
</div>
