<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\CompanyModel;
use App\Models\QuotationModel;
use App\Models\SalesOrderLineModel;
use App\Models\SalesOrderModel;
use Modules\Sale\Services\SalesOrderService;

class SalesOrderController extends BaseController
{
    protected SalesOrderModel $orders;
    protected SalesOrderLineModel $lines;
    protected SalesOrderService $service;
    protected CompanyModel $companies;
    protected QuotationModel $quotations;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->orders      = new SalesOrderModel();
        $this->lines       = new SalesOrderLineModel();
        $this->service     = new SalesOrderService();
        $this->companies   = new CompanyModel();
        $this->quotations  = new QuotationModel();
    }

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

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

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

    public function createForm()
    {
        return view('Modules\Sale\Views\orders\create', array_merge($this->baseViewData(), [
            'title'      => 'New Sales Order',
            'companies'  => $this->companies->getActive(),
            'quotations' => $this->quotations->scopeForList(null, null)->whereIn('quotations.status', ['approved', 'sent'])->orderBy('quotations.number', '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',
            'order_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/orders')->with('success', 'Sales order created.');
    }

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

        return view('Modules\Sale\Views\orders\edit', array_merge($this->baseViewData(), [
            'title'      => 'Edit Sales Order',
            'order'      => $order,
            'companies'  => $this->companies->getActive(),
            'quotations' => $this->quotations->scopeForList(null, null)->whereIn('quotations.status', ['approved', 'sent', 'converted'])->orderBy('quotations.number', 'DESC')->findAll(),
            'lines'      => $this->lines->getForOrder($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',
            'order_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/orders')->with('success', 'Sales order updated.');
    }

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

        return redirect()->back()->with('success', 'Order submitted for approval.');
    }

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

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