<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\CompanyModel;
use App\Models\DeliveryLineModel;
use App\Models\DeliveryModel;
use App\Models\SalesOrderModel;
use Modules\Sale\Services\DeliveryService;

class DeliveryNoteController extends BaseController
{
    protected DeliveryModel $deliveries;
    protected DeliveryLineModel $lines;
    protected DeliveryService $service;
    protected CompanyModel $companies;
    protected SalesOrderModel $orders;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->deliveries = new DeliveryModel();
        $this->lines      = new DeliveryLineModel();
        $this->service    = new DeliveryService();
        $this->companies  = new CompanyModel();
        $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;

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

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

    public function createForm()
    {
        return view('Modules\Sale\Views\delivery_notes\create', array_merge($this->baseViewData(), [
            'title'     => 'New Delivery Note',
            'companies' => $this->companies->getActive(),
            'orders'    => $this->orders->scopeForList(null, null)->whereIn('sales_orders.status', ['approved', 'confirmed', 'in_progress'])->orderBy('sales_orders.number', 'DESC')->findAll(),
            'lines'     => [['item_code' => '', 'item_name' => '', 'quantity' => '1', 'unit' => 'pcs']],
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'company_id'    => 'required|is_natural_no_zero',
            'delivery_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/delivery-notes')->with('success', 'Delivery note created.');
    }

    public function createFromOrder(int $orderId)
    {
        $result = $this->service->createFromOrder($orderId, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error'] ?? 'Could not create delivery note.');
        }

        return redirect()->to('/sale/delivery-notes/' . $result['id'] . '/edit')->with('success', 'Delivery note created from order.');
    }

    public function editForm(int $id)
    {
        $delivery = $this->deliveries->find($id);
        if (! $delivery) {
            return redirect()->to('/sale/delivery-notes')->with('error', 'Delivery note not found.');
        }

        return view('Modules\Sale\Views\delivery_notes\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Delivery Note',
            'delivery'  => $delivery,
            'companies' => $this->companies->getActive(),
            'orders'    => $this->orders->scopeForList(null, null)->whereIn('sales_orders.status', ['approved', 'confirmed', 'in_progress', 'fulfilled'])->orderBy('sales_orders.number', 'DESC')->findAll(),
            'lines'     => $this->lines->getForDelivery($id) ?: [['item_code' => '', 'item_name' => '', 'quantity' => '1', 'unit' => 'pcs']],
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'company_id'    => 'required|is_natural_no_zero',
            'delivery_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/delivery-notes')->with('success', 'Delivery note updated.');
    }

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

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

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

        return redirect()->to('/sale/delivery-notes')->with('success', 'Delivery note deleted.');
    }
}
