<?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_add', $pageLink);
$config = gf_config($con);
$errors = [];
$data = ['name' => '', 'latitude' => '', 'longitude' => '', 'radius' => ''];
if (!gf_ready($config)) $errors[] = 'A compatible geofence table or its required columns are not available.';
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'])) $errors[] = 'Geofence area name already exists.';
        if (!$errors) {
            gf_save($con, $config, 0, $data);
            gf_flash('Geofence area added successfully.');
            gf_redirect(gf_list_link());
        }
    }
}
console_header('Add Geofence Area', $pageLink);
gf_breadcrumb('Add Geofence Area');
gf_alerts(null, $errors);
gf_form_card($data, $errors, 'New Geofence Area', 'Submit');
console_footer();
