<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\CompanyModel;
use App\Models\ContactModel;
use App\Models\CustomerHistoryModel;
use Modules\Sale\Services\CustomerHistoryService;

class CustomerHistoryController extends BaseController
{
    protected CustomerHistoryModel $history;
    protected CompanyModel $companies;
    protected ContactModel $contacts;
    protected CustomerHistoryService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->history   = new CustomerHistoryModel();
        $this->companies = new CompanyModel();
        $this->contacts  = new ContactModel();
        $this->service   = new CustomerHistoryService();
    }

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

        $entries = $this->history
            ->scopeForList($search ?: null, $eventType, $companyId ? (int) $companyId : null)
            ->orderBy('event_at', 'DESC')
            ->paginate(25);

        return view('Modules\Sale\Views\customer_history\index', array_merge($this->baseViewData(), [
            'title'      => 'Customer History',
            'entries'    => $entries,
            'pager'      => $this->history->pager,
            'companies'  => $this->companies->getActive(),
            'companyMap' => $this->buildCompanyMap(),
            'filters'    => compact('search', 'eventType', 'companyId'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Sale\Views\customer_history\create', array_merge($this->baseViewData(), [
            'title'            => 'Log Customer Event',
            'companies'        => $this->companies->getActive(),
            'prefillCompanyId' => $this->request->getGet('company_id'),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'company_id' => 'required|is_natural_no_zero',
            'title'      => 'required|min_length[2]|max_length[200]',
            'event_type' => 'required|in_list[note,call,email,meeting,status_change,document,other]',
            'event_at'   => 'required',
        ])) {
            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/customer-history')->with('success', 'History entry logged.');
    }

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

        return redirect()->to('/sale/customer-history')->with('success', 'History entry deleted.');
    }

    protected function buildCompanyMap(): array
    {
        $map = [];
        foreach ($this->companies->findAll() as $c) {
            $map[$c['id']] = $c['name'];
        }

        return $map;
    }
}
