<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;

class AdminDeliveryController extends Controller
{
    public function index()
    {
        $this->checkPermission(); // Assuming standard admin check
        $db = Database::getInstance()->getConnection();
        $zones = $db->query("SELECT * FROM delivery_zones ORDER BY neighborhood ASC")->fetchAll();
        
        $this->view('admin.delivery_zones', ['zones' => $zones]);
    }

    public function save()
    {
        $this->checkPermission();
        
        $db = Database::getInstance()->getConnection();
        
        $id = $_POST['id'] ?? '';
        $neighborhood = trim($_POST['neighborhood'] ?? '');
        $fee = str_replace(['R$', ' '], '', $_POST['fee'] ?? '0');
        $fee = str_replace(',', '.', $fee);
        
        if (empty($neighborhood)) {
            $this->redirect('/admin/delivery');
        }

        if ($id) {
            $stmt = $db->prepare("UPDATE delivery_zones SET neighborhood = ?, fee = ? WHERE id = ?");
            $stmt->execute([$neighborhood, $fee, $id]);
        } else {
            $stmt = $db->prepare("INSERT INTO delivery_zones (neighborhood, fee) VALUES (?, ?)");
            $stmt->execute([$neighborhood, $fee]);
        }
        
        $this->redirect('/admin/delivery');
    }

    public function delete($id)
    {
        $this->checkPermission();
        $db = Database::getInstance()->getConnection();
        $stmt = $db->prepare("DELETE FROM delivery_zones WHERE id = ?");
        $stmt->execute([$id]);
        $this->redirect('/admin/delivery');
    }
}
