<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\CompanyModel;
use App\Models\InvoiceModel;
use App\Models\RefundModel;
use App\Models\SalesReturnModel;
use Modules\Sale\Services\RefundService;

class RefundController extends BaseController
{
    protected RefundModel $refunds;
    protected RefundService $service;
    protected CompanyModel $companies;
    protected InvoiceModel $invoices;
    protected SalesReturnModel $returns;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->refunds   = new RefundModel();
        $this->service   = new RefundService();
        $this->companies = new CompanyModel();
        $this->invoices  = new InvoiceModel();
        $this->returns   = new SalesReturnModel();
    }

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

        $refunds = $this->refunds
            ->scopeForList($search ?: null, $status, $companyId ? (int) $companyId : null)
            ->orderBy('refunds.refund_date', 'DESC')
            ->orderBy('refunds.id', 'DESC')
            ->findAll();

        return view('Modules\Sale\Views\refunds\index', array_merge($this->baseViewData(), [
            'title'     => 'Refunds',
            'refunds'   => $refunds,
            'companies' => $this->companies->getActive(),
            'filters'   => compact('search', 'status', 'companyId'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Sale\Views\refunds\create', array_merge($this->baseViewData(), [
            'title'     => 'New Refund',
            'companies' => $this->companies->getActive(),
            'invoices'  => $this->invoices->whereNotIn('status', ['draft', 'cancelled'])->orderBy('invoice_date', 'DESC')->findAll(),
            'returns'   => $this->returns->whereIn('status', ['approved', 'completed'])->orderBy('return_date', 'DESC')->findAll(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'company_id'  => 'required|is_natural_no_zero',
            'refund_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('/sale/refunds')->with('success', 'Refund created.');
    }

    public function editForm(int $id)
    {
        $refund = $this->refunds->find($id);
        if (! $refund) {
            return redirect()->to('/sale/refunds')->with('error', 'Refund not found.');
        }

        return view('Modules\Sale\Views\refunds\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Refund',
            'refund'    => $refund,
            'companies' => $this->companies->getActive(),
            'invoices'  => $this->invoices->whereNotIn('status', ['draft', 'cancelled'])->orderBy('invoice_date', 'DESC')->findAll(),
            'returns'   => $this->returns->whereIn('status', ['approved', 'completed'])->orderBy('return_date', 'DESC')->findAll(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'company_id'  => 'required|is_natural_no_zero',
            'refund_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('/sale/refunds')->with('success', 'Refund 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', 'Refund 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', 'Refund 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', 'Refund cancelled.');
    }

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

        return redirect()->to('/sale/refunds')->with('success', 'Refund deleted.');
    }
}
