<?php

namespace Modules\Sale\Controllers;

use App\Controllers\BaseController;
use App\Models\CompanyModel;
use App\Models\CustomerDocumentModel;
use Modules\Sale\Services\CustomerDocumentService;

class CustomerDocumentController extends BaseController
{
    protected CustomerDocumentModel $documents;
    protected CompanyModel $companies;
    protected CustomerDocumentService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->documents = new CustomerDocumentModel();
        $this->companies = new CompanyModel();
        $this->service   = new CustomerDocumentService();
    }

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

        $documents = $this->documents
            ->scopeForList($search ?: null, $status, $companyId ? (int) $companyId : null, $category)
            ->orderBy('created_at', 'DESC')
            ->paginate(20);

        return view('Modules\Sale\Views\customer_documents\index', array_merge($this->baseViewData(), [
            'title'      => 'Customer Documents',
            'documents'  => $documents,
            'pager'      => $this->documents->pager,
            'companies'  => $this->companies->getActive(),
            'companyMap' => $this->buildCompanyMap(),
            'filters'    => compact('search', 'status', 'companyId', 'category'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Sale\Views\customer_documents\create', array_merge($this->baseViewData(), [
            'title'            => 'Upload Document',
            '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[150]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $file   = $this->request->getFile('document_file');
        $result = $this->service->create($this->request->getPost(), $file, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/sale/customer-documents')->with('success', 'Document uploaded.');
    }

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

        return view('Modules\Sale\Views\customer_documents\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Document',
            'document'  => $document,
            'companies' => $this->companies->getActive(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'company_id' => 'required|is_natural_no_zero',
            'title'      => '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/customer-documents')->with('success', 'Document updated.');
    }

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

        return redirect()->back()->with('success', 'Document archived.');
    }

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

        return redirect()->back()->with('success', 'Document restored.');
    }

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

        return redirect()->to('/sale/customer-documents')->with('success', 'Document deleted.');
    }

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

        return $map;
    }
}
