<?php

namespace Modules\Procurement\Controllers;

use App\Controllers\BaseController;
use App\Models\PurchaseRequestLineModel;
use App\Models\PurchaseRequestModel;
use Modules\Procurement\Services\PurchaseRequestService;

class PurchaseRequestController extends BaseController
{
    protected PurchaseRequestModel $requests;
    protected PurchaseRequestLineModel $lines;
    protected PurchaseRequestService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->requests = new PurchaseRequestModel();
        $this->lines    = new PurchaseRequestLineModel();
        $this->service  = new PurchaseRequestService();
    }

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

        $requests = $this->requests
            ->scopeForList($search ?: null, $status)
            ->orderBy('purchase_requests.request_date', 'DESC')
            ->orderBy('purchase_requests.id', 'DESC')
            ->findAll();

        return view('Modules\Procurement\Views\purchase_requests\index', array_merge($this->baseViewData(), [
            'title'    => 'Purchase Requests',
            'requests' => $requests,
            'filters'  => compact('search', 'status'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Procurement\Views\purchase_requests\create', array_merge($this->baseViewData(), [
            'title' => 'New Purchase Request',
            'lines' => [['item_code' => '', 'item_name' => '', 'quantity' => '1', 'unit' => 'pcs', 'unit_price' => '']],
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'request_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('/procurement/purchase-requests')->with('success', 'Purchase request created.');
    }

    public function editForm(int $id)
    {
        $request = $this->requests->find($id);
        if (! $request) {
            return redirect()->to('/procurement/purchase-requests')->with('error', 'Purchase request not found.');
        }

        return view('Modules\Procurement\Views\purchase_requests\edit', array_merge($this->baseViewData(), [
            'title'   => 'Edit Purchase Request',
            'request' => $request,
            'lines'   => $this->lines->getForPurchaseRequest($id) ?: [['item_code' => '', 'item_name' => '', 'quantity' => '1', 'unit' => 'pcs', 'unit_price' => '']],
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'request_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('/procurement/purchase-requests')->with('success', 'Purchase request 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', 'Purchase request submitted for approval.');
    }

    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', 'Purchase request approved.');
    }

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

        return redirect()->back()->with('success', 'Purchase request rejected.');
    }

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

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

        return redirect()->to('/procurement/purchase-requests')->with('success', 'Purchase request deleted.');
    }
}
