<?php

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

        $supplierModel = new Supplier();
        $this->view('suppliers.index', [
            'pageTitle' => 'Suppliers',
            'suppliers' => $supplierModel->allWithDues(),
            'summary'   => $supplierModel->summaryStats(),
            'totalDues' => $supplierModel->totalDues(),
            'csrf'      => $this->csrfField(),
        ]);
    }

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

        $name = trim($this->input('supplier_name', ''));
        if ($name === '') {
            $this->redirect('suppliers');
            return;
        }

        $supplierModel = new Supplier();
        $supplierModel->insert([
            'supplier_name'  => $name,
            'contact_person' => trim($this->input('contact_person', '')) ?: null,
            'phone'          => trim($this->input('phone', '')) ?: null,
            'email'          => trim($this->input('email', '')) ?: null,
            'address'        => trim($this->input('address', '')) ?: null,
            'is_active'      => 1,
        ]);

        AuditLogger::log(Auth::id(), 'SUPPLIER_CREATE', 'suppliers', "Added supplier: {$name}");
        $this->redirect('suppliers');
    }

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

        $id = (int) $this->input('id');
        $supplierModel = new Supplier();
        $existing = $supplierModel->find($id);
        if (!$existing) {
            $this->redirect('suppliers');
            return;
        }

        $supplierModel->update($id, [
            'supplier_name'  => trim($this->input('supplier_name', $existing['supplier_name'])),
            'contact_person' => trim($this->input('contact_person', '')) ?: null,
            'phone'          => trim($this->input('phone', '')) ?: null,
            'email'          => trim($this->input('email', '')) ?: null,
            'address'        => trim($this->input('address', '')) ?: null,
        ]);

        AuditLogger::log(Auth::id(), 'SUPPLIER_UPDATE', 'suppliers', "Updated supplier #{$id}");
        $this->redirect('suppliers');
    }

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

        $id = (int) $this->input('id');
        $supplierModel = new Supplier();
        $supplier = $supplierModel->find($id);
        if ($supplier) {
            $supplierModel->update($id, ['is_active' => $supplier['is_active'] ? 0 : 1]);
            AuditLogger::log(Auth::id(), 'SUPPLIER_TOGGLE', 'suppliers', "Supplier #{$id} active -> " . ($supplier['is_active'] ? '0' : '1'));
        }
        $this->redirect('suppliers');
    }
}
