<?php

namespace App\Controllers;

use App\Models\ClientModel;
use App\Models\DeliveryNoteModel;
use App\Models\DeliveryNoteTemplateModel;
use App\Models\InspectionModel;
use App\Models\InspectionTemplateModel;
use App\Models\ReportModel;
use CodeIgniter\HTTP\ResponseInterface;

class VerifyController extends BaseController
{
    public function show(string $token): string
    {
        [$kind, $entity] = $this->resolve($token);
        if ($entity === null) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        $client = (new ClientModel())->find((int) $entity['client_id']);
        $template = null;
        if ($kind === 'inspection') {
            $template = (new InspectionTemplateModel())->find((int) $entity['template_id']);
        } elseif ($kind === 'delivery_note') {
            $template = (new DeliveryNoteTemplateModel())->find((int) $entity['template_id']);
        }

        return view('verify/show', [
            'title' => 'Verificación de documento',
            'kind' => $kind,
            'entity' => $entity,
            'client' => $client,
            'template' => $template,
            'company' => company_profile(),
        ]);
    }

    public function pdf(string $token): ResponseInterface
    {
        [$kind, $entity] = $this->resolve($token);
        if ($entity === null) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        if ($kind === 'inspection') {
            return (new InspectionController())->renderPdf((int) $entity['id'], false);
        }
        if ($kind === 'delivery_note') {
            return (new DeliveryNoteController())->renderPdf((int) $entity['id'], false);
        }
        return (new ReportController())->renderPdf((int) $entity['id'], false);
    }

    private function resolve(string $token): array
    {
        $inspection = (new InspectionModel())->where('verify_token', $token)->first();
        if ($inspection !== null) {
            return ['inspection', $inspection];
        }
        $report = (new ReportModel())->where('verify_token', $token)->first();
        if ($report !== null) {
            return ['report', $report];
        }
        $deliveryNote = (new DeliveryNoteModel())->where('verify_token', $token)->first();
        if ($deliveryNote !== null) {
            return ['delivery_note', $deliveryNote];
        }
        return [null, null];
    }
}
