<?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();
gf_ensure_menu($con);
$acl = require_acl('can_edit', $pageLink);
$config = gf_config($con);
$errors = [];
$id = max(0, (int)($_GET['id'] ?? $_POST['id'] ?? 0));
$row = gf_ready($config) ? gf_fetch($con, $config, $id) : null;
if (!$row) {
    gf_flash('Geofence area was not found.');
    gf_redirect(gf_list_link());
}
$data = ['name' => gf_text($row, $config['name']), 'latitude' => gf_text($row, $config['lat']), 'longitude' => gf_text($row, $config['lon']), 'radius' => gf_text($row, $config['radius'])];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf($_POST['_csrf'] ?? null)) $errors[] = 'Security token expired. Please refresh and try again.';
    else {
        $data = gf_validate($_POST, $errors);
        if (!$errors && gf_duplicate($con, $config, $data['name'], $id)) $errors[] = 'Geofence area name already exists.';
        if (!$errors) {
            gf_save($con, $config, $id, $data);
            gf_flash('Geofence area updated successfully.');
            gf_redirect(gf_list_link());
        }
    }
}
console_header('Edit Geofence Area', $pageLink);
gf_breadcrumb('Edit Geofence Area');
gf_alerts(null, $errors);
gf_form_card($data, $errors, 'Edit Geofence Area', 'Update', $id);
console_footer();
