<?php

namespace App\Controllers\Report;

use App\Controllers\BaseController;
use App\Libraries\PdfGenerator;
use App\Models\OrderModel;
use App\Models\ActivityLogModel;

class Pdf extends BaseController
{
    public function printInvoice($id_order)
    {
        $orderModel = new OrderModel();
        $data['order'] = $orderModel->getDetailOrder($id_order);
        
        if (!$data['order']) return redirect()->back()->with('error', 'Data tidak ditemukan.');
        
        // 1. Audit Trail
        (new ActivityLogModel())->logActivity(
            session()->get('id_user') ?? 1, 
            "Mencetak Invoice ID Order #{$id_order}"
        );
        
        $html = view('reports/pdf/invoice_template', $data);
        $pdf = new PdfGenerator();
        return $pdf->generate($html, "Invoice_" . $id_order, 'A4', 'portrait');
    }

    public function printWorkOrder($id_order)
    {
        $orderModel = new OrderModel();
        
        // Pastikan Model mengambil relasi order_customs
        $data['order'] = $orderModel->getDetailOrder($id_order);
        
        if (!$data['order']) return redirect()->back()->with('error', 'Data tidak ditemukan.');

        // 2. Audit Trail
        (new ActivityLogModel())->logActivity(
            session()->get('id_user') ?? 1, 
            "Mencetak Work Order (Teknis) ID Order #{$id_order}"
        );
        
        $html = view('reports/pdf/work_order_template', $data);
        $pdf = new PdfGenerator();
        return $pdf->generate($html, "WorkOrder_" . $id_order, 'A4', 'landscape');
    }
}