<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\PriceListItemModel;
use App\Models\PriceListModel;
use Modules\Sale\Services\PriceListService;

class PriceListController extends BaseController
{
    protected PriceListModel $lists;
    protected PriceListItemModel $items;
    protected PriceListService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->lists   = new PriceListModel();
        $this->items   = new PriceListItemModel();
        $this->service = new PriceListService();
    }

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

        $lists = $this->lists
            ->scopeForList($search ?: null, $status)
            ->orderBy('name', 'ASC')
            ->findAll();

        return view('Modules\Sale\Views\price_lists\index', array_merge($this->baseViewData(), [
            'title'   => 'Price Lists',
            'lists'   => $lists,
            'filters' => compact('search', 'status'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Sale\Views\price_lists\create', array_merge($this->baseViewData(), [
            'title' => 'Add Price List',
            'lines' => [['item_code' => '', 'item_name' => '', 'unit' => 'pcs', 'unit_price' => '']],
        ]));
    }

    public function store()
    {
        if (! $this->validate(['name' => 'required|min_length[2]|max_length[150]'])) {
            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/price-lists')->with('success', 'Price list created.');
    }

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

        return view('Modules\Sale\Views\price_lists\edit', array_merge($this->baseViewData(), [
            'title' => 'Edit Price List',
            'list'  => $list,
            'lines' => $this->items->getForList($id) ?: [['item_code' => '', 'item_name' => '', 'unit' => 'pcs', 'unit_price' => '']],
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate(['name' => 'required|min_length[2]|max_length[150]'])) {
            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/price-lists')->with('success', 'Price list updated.');
    }

    public function activate(int $id)
    {
        $this->service->activate($id, (int) $this->session->get('user_id'));

        return redirect()->back()->with('success', 'Price list activated.');
    }

    public function deactivate(int $id)
    {
        $this->service->deactivate($id, (int) $this->session->get('user_id'));

        return redirect()->back()->with('success', 'Price list deactivated.');
    }

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

        return redirect()->to('/sale/price-lists')->with('success', 'Price list deleted.');
    }
}
