<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\InvoiceModel;
use App\Models\OrderModel;
use App\Models\OrderItemModel;
use Dompdf\Dompdf;

class InvoicePublic extends BaseController
{
    protected InvoiceModel $invoiceModel;
    protected OrderModel $orderModel;
    protected OrderItemModel $itemModel;

    public function __construct()
    {
        $this->invoiceModel = new InvoiceModel();
        $this->orderModel   = new OrderModel();
        $this->itemModel    = new OrderItemModel();
    }

    /**
     * Detail Invoice
     */
    public function detail($token)
    {
        $invoice = $this->invoiceModel
            ->where('access_token', $token)
            ->first();

        if (! $invoice) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound('Invoice tidak ditemukan.');
        }

        $order = $this->orderModel->find($invoice['id_order']);

        $items = $this->itemModel
            ->where('id_order', $invoice['id_order'])
            ->findAll();

        return view('invoice/public', [
            'invoice' => $invoice,
            'order'   => $order,
            'items'   => $items,
        ]);
    }

    /**
     * Download PDF
     */
    public function pdf($token)
    {
        $invoice = $this->invoiceModel
            ->where('access_token', $token)
            ->first();

        if (! $invoice) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound('Invoice tidak ditemukan.');
        }

        $order = $this->orderModel->find($invoice['id_order']);

        $items = $this->itemModel
            ->where('id_order', $invoice['id_order'])
            ->findAll();

        $html = view('invoice/pdf', [
            'invoice' => $invoice,
            'order'   => $order,
            'items'   => $items,
        ]);

        $dompdf = new Dompdf();

        $dompdf->loadHtml($html);

        $dompdf->setPaper('A4', 'portrait');

        $dompdf->render();

        return $this->response
            ->setHeader('Content-Type', 'application/pdf')
            ->setBody($dompdf->output());
    }
}