<?php

namespace Modules\Procurement\Controllers;

use App\Controllers\BaseController;
use App\Models\SupplierModel;
use App\Models\SupplierPaymentModel;
use App\Models\VendorBillModel;
use Modules\Procurement\Services\SupplierPaymentService;

class SupplierPaymentController extends BaseController
{
    protected SupplierPaymentModel $payments;
    protected SupplierPaymentService $service;
    protected SupplierModel $suppliers;
    protected VendorBillModel $bills;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->payments  = new SupplierPaymentModel();
        $this->service   = new SupplierPaymentService();
        $this->suppliers = new SupplierModel();
        $this->bills     = new VendorBillModel();
    }

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

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

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

    public function createForm()
    {
        return view('Modules\Procurement\Views\supplier_payments\create', array_merge($this->baseViewData(), [
            'title'     => 'New Supplier Payment',
            'suppliers' => $this->suppliers->getActive(),
            'bills'     => $this->bills->scopeOutstanding()->orderBy('vendor_bills.bill_date', 'DESC')->findAll(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'supplier_id'  => 'required|is_natural_no_zero',
            'payment_date' => 'required|valid_date',
            'amount'       => 'required|decimal',
        ])) {
            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-payments')->with('success', 'Supplier payment created.');
    }

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

        $bills = $this->bills->scopeOutstanding()->orderBy('vendor_bills.bill_date', 'DESC')->findAll();
        if (! empty($payment['vendor_bill_id'])) {
            $linkedId = (int) $payment['vendor_bill_id'];
            $found = false;
            foreach ($bills as $b) {
                if ((int) $b['id'] === $linkedId) {
                    $found = true;
                    break;
                }
            }
            if (! $found) {
                $linked = (new VendorBillModel())->scopeForList()->where('vendor_bills.id', $linkedId)->first();
                if ($linked) {
                    array_unshift($bills, $linked);
                }
            }
        }

        return view('Modules\Procurement\Views\supplier_payments\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Supplier Payment',
            'payment'   => $payment,
            'suppliers' => $this->suppliers->getActive(),
            'bills'     => $bills,
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'supplier_id'  => 'required|is_natural_no_zero',
            'payment_date' => 'required|valid_date',
            'amount'       => 'required|decimal',
        ])) {
            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-payments')->with('success', 'Supplier payment updated.');
    }

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

        return redirect()->back()->with('success', 'Supplier payment submitted.');
    }

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

        return redirect()->back()->with('success', 'Supplier payment processed.');
    }

    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 payment 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-payments')->with('error', $result['error']);
        }

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