<?php
declare(strict_types=1);
ini_set('display_errors', '0');

require_once __DIR__ . '/../includes/console_shell.php';
require_login();
require_once __DIR__ . '/geofence-area-common.php';

$pageLink = gf_menu_link();
$errors = [];
try {
    gf_ensure_menu($con);
} catch (Throwable $e) {
    $errors[] = 'Geofence menu setup could not be completed.';
}
$acl = require_acl('can_view', $pageLink);
$config = gf_config($con);
$flash = gf_current_flash();

if (!gf_ready($config)) {
    console_header('Configuration Geofence Area', $pageLink);
    gf_breadcrumb();
    gf_alerts($flash, array_merge($errors, ['A compatible geofence table or its required name, latitude, longitude, and radius columns are not available.']));
    console_footer();
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');
    $id = max(0, (int)($_POST['id'] ?? 0));
    if (!verify_csrf($_POST['_csrf'] ?? null)) {
        $errors[] = 'Security token expired. Please refresh and try again.';
    } elseif ($action === 'delete') {
        if (empty($acl['can_delete'])) $errors[] = 'You do not have permission to delete geofence areas.';
        elseif (!gf_fetch($con, $config, $id)) $errors[] = 'Geofence area was not found.';
        else {
            try {
                gf_delete($con, $config, $id);
                gf_flash('Geofence area deleted successfully.');
                gf_redirect(gf_list_link());
            } catch (Throwable $e) {
                $errors[] = 'This geofence area is in use or could not be deleted.';
            }
        }
    } elseif ($action === 'toggle') {
        if (empty($acl['can_edit'])) $errors[] = 'You do not have permission to update geofence areas.';
        elseif (!gf_fetch($con, $config, $id)) $errors[] = 'Geofence area was not found.';
        else {
            gf_toggle_status($con, $config, $id, !empty($_POST['status']) ? 1 : 0);
            gf_flash('Geofence area status updated successfully.');
            gf_redirect(gf_list_link());
        }
    }
}

$q = trim((string)($_GET['q'] ?? ''));
$status = isset($_GET['status']) && in_array((string)$_GET['status'], ['0', '1'], true) ? (string)$_GET['status'] : '';
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 15;
$totalRows = gf_count($con, $config, $q, $status);
$totalPages = max(1, (int)ceil($totalRows / $perPage));
$page = min($page, $totalPages);
$offset = ($page - 1) * $perPage;
$rows = gf_list($con, $config, $q, $status, $perPage, $offset);

console_header('Configuration Geofence Area', $pageLink);
gf_breadcrumb();
gf_alerts($flash, $errors);
?>
<section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm">
  <div class="flex flex-col gap-4 border-b border-slate-100 p-5 md:flex-row md:items-center md:justify-between">
    <div><h2 class="text-lg font-bold text-slate-800">Geofence Area List</h2><p class="mt-1 text-sm font-medium text-slate-400">Configure the coordinates and permitted radius for attendance locations.</p></div>
    <?php if (!empty($acl['can_add'])): ?><a href="<?= h(gf_add_link()) ?>" class="inline-flex items-center justify-center rounded-xl bg-brand-600 px-5 py-3 text-sm font-bold text-white shadow-sm hover:bg-brand-700"><i class="fa-solid fa-plus mr-2"></i>Add</a><?php endif; ?>
  </div>
  <form method="get" class="flex flex-col gap-3 border-b border-slate-100 p-5 md:flex-row md:items-center">
    <input type="search" name="q" value="<?= h($q) ?>" placeholder="Search geofence area" class="w-full rounded-xl border border-slate-200 px-4 py-3 text-sm font-semibold outline-none focus:border-brand-500 focus:ring-4 focus:ring-brand-100 md:max-w-sm">
    <?php if ($config['status'] !== ''): ?><select name="status" class="rounded-xl border border-slate-200 px-4 py-3 text-sm font-semibold"><option value="">All statuses</option><option value="1" <?= $status === '1' ? 'selected' : '' ?>>Active</option><option value="0" <?= $status === '0' ? 'selected' : '' ?>>Inactive</option></select><?php endif; ?>
    <button class="rounded-xl bg-slate-900 px-5 py-3 text-sm font-bold text-white"><i class="fa-solid fa-filter mr-2"></i>Filter</button>
    <a href="<?= h(gf_list_link()) ?>" class="rounded-xl border border-slate-200 px-5 py-3 text-center text-sm font-bold text-slate-600">Clear</a>
  </form>
  <div class="overflow-x-auto"><table class="w-full min-w-[900px] text-left text-sm">
    <thead class="bg-slate-50 text-[10px] font-extrabold uppercase tracking-wider text-slate-600"><tr><th class="px-5 py-4">Sr No</th><th class="px-5 py-4">Name</th><th class="px-5 py-4">Latitude</th><th class="px-5 py-4">Longitude</th><th class="px-5 py-4">Radius</th><?php if ($config['status'] !== ''): ?><th class="px-5 py-4">Status</th><?php endif; ?><th class="px-5 py-4 text-right">Actions</th></tr></thead>
    <tbody class="divide-y divide-slate-100">
    <?php if (!$rows): ?><tr><td colspan="<?= $config['status'] !== '' ? 7 : 6 ?>" class="px-5 py-16 text-center font-bold text-slate-400">No geofence areas found.</td></tr><?php endif; ?>
    <?php foreach ($rows as $index => $row): $id = (int)$row[$config['id']]; ?>
      <tr class="hover:bg-slate-50/70"><td class="px-5 py-4 font-semibold text-slate-500"><?= $offset + $index + 1 ?></td><td class="px-5 py-4 font-bold text-slate-800"><?= h(gf_text($row, $config['name'], '-')) ?></td><td class="px-5 py-4"><?= h(gf_text($row, $config['lat'], '-')) ?></td><td class="px-5 py-4"><?= h(gf_text($row, $config['lon'], '-')) ?></td><td class="px-5 py-4"><?= h(gf_text($row, $config['radius'], '-')) ?></td>
      <?php if ($config['status'] !== ''): $active = (int)($row[$config['status']] ?? 0) === 1; ?><td class="px-5 py-4"><span class="rounded-full px-3 py-1 text-xs font-bold <?= $active ? 'bg-emerald-50 text-emerald-700' : 'bg-slate-100 text-slate-500' ?>"><?= $active ? 'Active' : 'Inactive' ?></span></td><?php endif; ?>
      <td class="px-5 py-4"><div class="flex justify-end gap-2"><?php if (!empty($acl['can_edit'])): ?><a href="<?= h(gf_edit_link($id)) ?>" class="inline-flex h-10 w-10 items-center justify-center rounded-xl border border-slate-200 text-slate-600 hover:bg-brand-50 hover:text-brand-600" title="Edit"><i class="fa-solid fa-pen-to-square"></i></a><?php endif; ?><?php if (!empty($acl['can_delete'])): ?><form method="post" onsubmit="return confirm('Delete this geofence area?');"><input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= $id ?>"><button class="inline-flex h-10 w-10 items-center justify-center rounded-xl border border-slate-200 text-slate-600 hover:bg-red-50 hover:text-red-600" title="Delete"><i class="fa-solid fa-trash-can"></i></button></form><?php endif; ?></div></td></tr>
    <?php endforeach; ?>
    </tbody></table></div>
  <?php if ($totalPages > 1): ?><div class="flex items-center justify-between border-t border-slate-100 px-5 py-4 text-sm font-semibold text-slate-500"><span>Page <?= $page ?> of <?= $totalPages ?></span><div class="flex gap-2"><?php $query = ['q' => $q, 'status' => $status]; if ($page > 1): ?><a class="rounded-lg border border-slate-200 px-3 py-2" href="?<?= h(http_build_query($query + ['page' => $page - 1])) ?>">Previous</a><?php endif; ?><?php if ($page < $totalPages): ?><a class="rounded-lg border border-slate-200 px-3 py-2" href="?<?= h(http_build_query($query + ['page' => $page + 1])) ?>">Next</a><?php endif; ?></div></div><?php endif; ?>
</section>
<?php console_footer();
