<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\CompanyModel;
use App\Models\InvoiceModel;
use App\Models\SalesOrderModel;
use App\Models\SalesReturnLineModel;
use App\Models\SalesReturnModel;
use Modules\Sale\Services\SalesReturnService;

class SalesReturnController extends BaseController
{
    protected SalesReturnModel $returns;
    protected SalesReturnLineModel $lines;
    protected SalesReturnService $service;
    protected CompanyModel $companies;
    protected InvoiceModel $invoices;
    protected SalesOrderModel $orders;

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

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

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

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

    public function createForm()
    {
        return view('Modules\Sale\Views\sales_returns\create', array_merge($this->baseViewData(), [
            'title'     => 'New Sales Return',
            'companies' => $this->companies->getActive(),
            'invoices'  => $this->invoices->whereNotIn('status', ['draft', 'cancelled'])->orderBy('invoice_date', 'DESC')->findAll(),
            'orders'    => $this->orders->whereIn('status', ['approved', 'confirmed', 'in_progress', 'fulfilled'])->orderBy('order_date', 'DESC')->findAll(),
            'lines'     => [['item_code' => '', 'item_name' => '', 'quantity' => '1', 'unit' => 'pcs', 'unit_price' => '']],
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'company_id'  => 'required|is_natural_no_zero',
            'return_date' => 'required|valid_date',
        ])) {
            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/sales-returns')->with('success', 'Sales return created.');
    }

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

        return view('Modules\Sale\Views\sales_returns\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Sales Return',
            'return'    => $return,
            'companies' => $this->companies->getActive(),
            'invoices'  => $this->invoices->whereNotIn('status', ['draft', 'cancelled'])->orderBy('invoice_date', 'DESC')->findAll(),
            'orders'    => $this->orders->whereIn('status', ['approved', 'confirmed', 'in_progress', 'fulfilled'])->orderBy('order_date', 'DESC')->findAll(),
            'lines'     => $this->lines->getForReturn($id) ?: [['item_code' => '', 'item_name' => '', 'quantity' => '1', 'unit' => 'pcs', 'unit_price' => '']],
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'company_id'  => 'required|is_natural_no_zero',
            'return_date' => 'required|valid_date',
        ])) {
            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/sales-returns')->with('success', 'Sales return 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', 'Sales return submitted.');
    }

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

        return redirect()->back()->with('success', 'Sales return approved.');
    }

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

        return redirect()->back()->with('success', 'Sales return completed.');
    }

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

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

        return redirect()->to('/sale/sales-returns')->with('success', 'Sales return deleted.');
    }
}
