<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\CompanyModel;
use App\Models\OpportunityModel;
use App\Models\PriceListModel;
use App\Models\QuotationLineModel;
use App\Models\QuotationModel;
use App\Models\QuotationTemplateModel;
use Modules\Sale\Services\QuotationService;
use Modules\Sale\Services\SalesOrderService;

class QuotationController extends BaseController
{
    protected QuotationModel $quotations;
    protected QuotationLineModel $lines;
    protected QuotationService $service;
    protected CompanyModel $companies;
    protected QuotationTemplateModel $templates;
    protected PriceListModel $priceLists;
    protected OpportunityModel $opportunities;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->quotations   = new QuotationModel();
        $this->lines        = new QuotationLineModel();
        $this->service      = new QuotationService();
        $this->companies    = new CompanyModel();
        $this->templates    = new QuotationTemplateModel();
        $this->priceLists   = new PriceListModel();
        $this->opportunities = new OpportunityModel();
    }

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

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

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

    public function createForm()
    {
        return view('Modules\Sale\Views\quotations\create', array_merge($this->baseViewData(), [
            'title'         => 'New Quotation',
            'companies'     => $this->companies->getActive(),
            'templates'     => $this->templates->getActive(),
            'priceLists'    => $this->priceLists->getActive(),
            'opportunities' => $this->opportunities->where('status', 'open')->orderBy('name', 'ASC')->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',
            'quotation_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/quotations')->with('success', 'Quotation created.');
    }

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

        return view('Modules\Sale\Views\quotations\edit', array_merge($this->baseViewData(), [
            'title'         => 'Edit Quotation',
            'quotation'     => $quotation,
            'companies'     => $this->companies->getActive(),
            'templates'     => $this->templates->getActive(),
            'priceLists'    => $this->priceLists->getActive(),
            'opportunities' => $this->opportunities->where('status', 'open')->orderBy('name', 'ASC')->findAll(),
            'lines'         => $this->lines->getForQuotation($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',
            'quotation_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/quotations')->with('success', 'Quotation 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', 'Quotation submitted for approval.');
    }

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

        return redirect()->back()->with('success', 'Quotation marked as sent.');
    }

    public function convert(int $id)
    {
        $orderService = new SalesOrderService();
        $result = $orderService->createFromQuotation($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error'] ?? 'Could not convert quotation.');
        }

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

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

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

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