<?php

namespace Modules\Procurement\Controllers;

use App\Controllers\BaseController;
use App\Models\SupplierContractModel;
use App\Models\SupplierModel;
use Modules\Procurement\Services\SupplierContractService;

class SupplierContractController extends BaseController
{
    protected SupplierContractModel $contracts;
    protected SupplierModel $suppliers;
    protected SupplierContractService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->contracts = new SupplierContractModel();
        $this->suppliers = new SupplierModel();
        $this->service   = new SupplierContractService();
    }

    public function index()
    {
        $search     = trim((string) $this->request->getGet('q'));
        $status     = $this->request->getGet('status') ?: null;
        $supplierId = $this->request->getGet('supplier_id') ?: null;

        $contracts = $this->contracts
            ->scopeForList($search ?: null, $status, $supplierId ? (int) $supplierId : null)
            ->orderBy('supplier_contracts.id', 'DESC')
            ->findAll();

        return view('Modules\Procurement\Views\supplier_contracts\index', array_merge($this->baseViewData(), [
            'title'     => 'Supplier Contracts',
            'contracts' => $contracts,
            'suppliers' => $this->suppliers->getActive(),
            'filters'   => compact('search', 'status', 'supplierId'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Procurement\Views\supplier_contracts\create', array_merge($this->baseViewData(), [
            'title'     => 'New Supplier Contract',
            'suppliers' => $this->suppliers->getActive(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'title'       => 'required|min_length[2]|max_length[200]',
            'supplier_id' => 'required|is_natural_no_zero',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->create($this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/procurement/supplier-contracts')->with('success', 'Supplier contract created.');
    }

    public function editForm(int $id)
    {
        $contract = $this->contracts->find($id);
        if (! $contract) {
            return redirect()->to('/procurement/supplier-contracts')->with('error', 'Supplier contract not found.');
        }

        return view('Modules\Procurement\Views\supplier_contracts\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Supplier Contract',
            'contract'  => $contract,
            'suppliers' => $this->suppliers->getActive(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'title'       => 'required|min_length[2]|max_length[200]',
            'supplier_id' => 'required|is_natural_no_zero',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->update($id, $this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/procurement/supplier-contracts')->with('success', 'Supplier contract updated.');
    }

    public function activate(int $id)
    {
        $result = $this->service->activate($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error']);
        }

        return redirect()->back()->with('success', 'Supplier contract activated.');
    }

    public function terminate(int $id)
    {
        $result = $this->service->terminate($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error']);
        }

        return redirect()->back()->with('success', 'Supplier contract terminated.');
    }

    public function cancel(int $id)
    {
        $result = $this->service->cancel($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error']);
        }

        return redirect()->back()->with('success', 'Supplier contract cancelled.');
    }

    public function destroy(int $id)
    {
        $result = $this->service->delete($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->to('/procurement/supplier-contracts')->with('error', $result['error']);
        }

        return redirect()->to('/procurement/supplier-contracts')->with('success', 'Supplier contract deleted.');
    }
}
