<?php

namespace Modules\Accounting\Controllers;

use App\Controllers\BaseController;
use App\Models\ApPaymentModel;
use App\Models\SupplierBillModel;
use App\Models\SupplierModel;
use Modules\Accounting\Services\ApPaymentService;

class PaymentController extends BaseController
{
    protected ApPaymentModel $payments;
    protected ApPaymentService $service;
    protected SupplierModel $suppliers;
    protected SupplierBillModel $bills;

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

    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('ap_payments.payment_date', 'DESC')
            ->orderBy('ap_payments.id', 'DESC')
            ->findAll();

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

    public function createForm()
    {
        return view('Modules\Accounting\Views\payments\create', array_merge($this->baseViewData(), [
            'title'     => 'New Payment',
            'suppliers' => $this->suppliers->getActive(),
            'bills'     => $this->bills->scopeOutstanding()->orderBy('supplier_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('/accounting/payments')->with('success', 'Payment created.');
    }

    public function show(int $id)
    {
        $payment = $this->payments->find($id);
        if (! $payment) {
            return redirect()->to('/accounting/payments')->with('error', 'Payment not found.');
        }
        if ($payment['status'] === 'draft') {
            return redirect()->to('/accounting/payments/' . $id . '/edit');
        }

        return redirect()->to('/accounting/payments');
    }

    public function editForm(int $id)
    {
        $payment = $this->payments->find($id);
        if (! $payment) {
            return redirect()->to('/accounting/payments')->with('error', 'Payment not found.');
        }
        if ($payment['status'] !== 'draft') {
            return redirect()->to('/accounting/payments')->with('error', 'Only draft payments can be edited.');
        }

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

        return view('Modules\Accounting\Views\payments\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit 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('/accounting/payments')->with('success', 'Payment updated.');
    }

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

        return redirect()->back()->with('success', 'Payment posted.');
    }

    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', 'Payment cancelled.');
    }

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

        return redirect()->to('/accounting/payments')->with('success', 'Payment deleted.');
    }
}
