<?php

class DeliveryZoneController extends Controller
{
    public function index(): void
    {
        Auth::requirePermission('delivery', 'view');

        $zoneModel = new DeliveryZone();
        $this->view('delivery.zones', [
            'pageTitle' => 'Delivery Zones',
            'zones'     => $zoneModel->allZones(),
            'csrf'      => $this->csrfField(),
        ]);
    }

    public function store(): void
    {
        Auth::requirePermission('delivery', 'edit');
        $this->verifyCsrf();

        $name = trim($this->input('zone_name', ''));
        if ($name === '') {
            $this->redirect('delivery/zones');
            return;
        }

        $isFree = (int) $this->input('is_free_delivery', 0);
        $zoneModel = new DeliveryZone();
        $zoneModel->insert([
            'zone_name'        => $name,
            'radius_km'        => (float) $this->input('radius_km', 0),
            'is_free_delivery' => $isFree,
            'delivery_fee'     => $isFree ? 0 : (float) $this->input('delivery_fee', 0),
            'is_active'        => 1,
        ]);

        AuditLogger::log(Auth::id(), 'DELIVERY_ZONE_CREATE', 'delivery', "Added delivery zone: {$name}");
        $this->redirect('delivery/zones');
    }

    public function update(): void
    {
        Auth::requirePermission('delivery', 'edit');
        $this->verifyCsrf();

        $id = (int) $this->input('id');
        $zoneModel = new DeliveryZone();
        $existing = $zoneModel->find($id);
        if (!$existing) {
            $this->redirect('delivery/zones');
            return;
        }

        $isFree = (int) $this->input('is_free_delivery', 0);
        $zoneModel->update($id, [
            'zone_name'        => trim($this->input('zone_name', $existing['zone_name'])),
            'radius_km'        => (float) $this->input('radius_km', $existing['radius_km']),
            'is_free_delivery' => $isFree,
            'delivery_fee'     => $isFree ? 0 : (float) $this->input('delivery_fee', $existing['delivery_fee']),
        ]);

        AuditLogger::log(Auth::id(), 'DELIVERY_ZONE_UPDATE', 'delivery', "Updated delivery zone #{$id}");
        $this->redirect('delivery/zones');
    }

    public function toggle(): void
    {
        Auth::requirePermission('delivery', 'edit');
        $this->verifyCsrf();

        $id = (int) $this->input('id');
        $zoneModel = new DeliveryZone();
        $zone = $zoneModel->find($id);
        if ($zone) {
            $zoneModel->update($id, ['is_active' => $zone['is_active'] ? 0 : 1]);
            AuditLogger::log(Auth::id(), 'DELIVERY_ZONE_TOGGLE', 'delivery', "Zone #{$id} active -> " . ($zone['is_active'] ? '0' : '1'));
        }
        $this->redirect('delivery/zones');
    }

    public function delete(): void
    {
        Auth::requirePermission('delivery', 'delete');
        $this->verifyCsrf();

        $id = (int) $this->input('id');
        $db = Database::getConnection();
        $stmt = $db->prepare("SELECT COUNT(*) as cnt FROM orders WHERE delivery_zone_id = :id");
        $stmt->execute(['id' => $id]);
        $inUse = (int) $stmt->fetch()['cnt'] > 0;

        $zoneModel = new DeliveryZone();
        if ($inUse) {
            // Zone has order history — deactivate instead of deleting
            $zoneModel->update($id, ['is_active' => 0]);
            AuditLogger::log(Auth::id(), 'DELIVERY_ZONE_DEACTIVATE', 'delivery', "Zone #{$id} has order history — deactivated instead of deleted");
        } else {
            $zoneModel->delete($id);
            AuditLogger::log(Auth::id(), 'DELIVERY_ZONE_DELETE', 'delivery', "Deleted delivery zone #{$id}");
        }
        $this->redirect('delivery/zones');
    }
}
