<?php

defined('BASEPATH') or exit('No direct script access allowed');

use app\libraries\TenantHelper;

/**
 * Invoicing_print trait aiding to apply custom code on simple duplication of :
 * 1. backend/Invoicing_invoice => api/Invoicing_invoice
 * 2. backend/Invoicing_receipt => api/Invoicing_receipt
 * 
 * - require_once 'Invoicing_print.php';
 * - use Invoicing_print;
 * - extends MY_ApiController
 * - public static $_output = 'F'; (optional)
 * - remove all exit() method;
 * - import as many  $this->model_name->setTenantNo($tenantNo); as possible from the constructor
 */
trait Invoicing_print
{

    public function index()
    {
        /** @var Invoicing_invoice|Invoicing_receipt $this*/

        $this->is_get();

        switch ($this->router->fetch_class()) {
            case 'invoicing_invoice':
                $invoiceId = $this->input->get('invoiceId');
                $tenantNo = $this->input->get('tenant_no');

                TenantHelper::setTenant($tenantNo);
                $this->Invoice_model->setTenantNo($tenantNo);
                $this->Invoicing_model->setTenantNo($tenantNo);
                $this->Invoice_item_model->setTenantNo($tenantNo);
                $this->Student_model->setTenantNo($tenantNo);
                $this->Setting_center_model->setTenantNo($tenantNo);

                ob_start();
                $this->printinvoice();
                ob_clean();

                $item = $this->Invoicing_model->detail($invoiceId);
                $filename = $item['issued_name'] . '.pdf';

                echo $this->respond([
                    'file' => base_url(sprintf('/uploads/tenants/%s/invoice/%s', $tenantNo,  $filename))
                ]);
                break;
            case 'invoicing_receipt':
                $receiptId = $this->input->get('receiptId');
                $tenantNo = $this->input->get('tenant_no');

                TenantHelper::setTenant($tenantNo);
                $this->Invoicing_model->setTenantNo($tenantNo);
                $this->Invoice_model->setTenantNo($tenantNo);
                $this->Invoice_item_model->setTenantNo($tenantNo);
                $this->Receipt_model->setTenantNo($tenantNo);
                $this->Receipt_item_model->setTenantNo($tenantNo);
                $this->Student_model->setTenantNo($tenantNo);
                $this->Student_credit_model->setTenantNo($tenantNo);
                $this->Setting_center_model->setTenantNo($tenantNo);

                ob_start();
                $this->printreceipt();
                ob_end_clean();

                $item = $this->Receipt_model->detail($receiptId);
                $filename = $item['issued_name'] . '.pdf';

                echo $this->respond([
                    'file' => base_url(sprintf('/uploads/tenants/%s/receipt/%s', $tenantNo,  $filename))
                ]);
                break;
            default:
                echo $this->respond(['file' => '']);
                break;
        }
    }
}
