<?php

class BrokerController extends Controller
{
    private Broker $brokers;

    public function __construct()
    {
        $this->brokers = new Broker();
    }

    public function index(): void
    {
        Auth::requireRole(['owner','admin','dispatcher','team']);
        $search = trim($_GET['search'] ?? '');
        $brokers = $this->brokers->all($search ?: null);
        $this->view('brokers/index', compact('brokers', 'search'));
        clear_old();
    }

    public function create(): void
    {
        Auth::requireRole(['owner','admin','dispatcher','team']);
        $broker = null;
        $this->view('brokers/create', compact('broker'));
    }

    public function store(): void
    {
        Auth::requireRole(['owner','admin','dispatcher','team']);
        Csrf::verify();

        if (empty(trim($_POST['company_name'] ?? ''))) {
            set_old($_POST);
            $this->flash('danger', 'Company name is required.');
            $this->redirect('/brokers/create');
        }

        $this->brokers->create($_POST);
        $this->flash('success', 'Broker/customer created successfully.');
        $this->redirect('/brokers');
    }

    public function edit(): void
    {
        Auth::requireRole(['owner','admin','dispatcher','team']);
        $broker = $this->brokers->find((int) ($_GET['id'] ?? 0));

        if (!$broker) {
            $this->flash('danger', 'Broker/customer not found.');
            $this->redirect('/brokers');
        }

        $this->view('brokers/edit', compact('broker'));
    }

    public function update(): void
    {
        Auth::requireRole(['owner','admin','dispatcher','team']);
        Csrf::verify();

        $id = (int) ($_POST['id'] ?? 0);
        if (!$id || empty(trim($_POST['company_name'] ?? ''))) {
            set_old($_POST);
            $this->flash('danger', 'Company name is required.');
            $this->redirect('/brokers/edit?id=' . $id);
        }

        $this->brokers->update($id, $_POST);
        $this->flash('success', 'Broker/customer updated successfully.');
        $this->redirect('/brokers');
    }

    public function delete(): void
    {
        Auth::requireRole(['owner','admin','dispatcher','team']);
        Csrf::verify();
        $this->brokers->delete((int) ($_POST['id'] ?? 0));
        $this->flash('success', 'Broker/customer deleted successfully.');
        $this->redirect('/brokers');
    }
}
