<?php
namespace App;

use Dompdf\Dompdf;
use Dompdf\Options; 
use Mustache_Engine;

class PdfGenerator {
    public function generatePdf($invoiceData) {
        if (empty($invoiceData)) {
            throw new \Exception('Invoice data is required');
        }

        // Initialize Dompdf with options
        $options = new Options();
        $options->set('isHtml5ParserEnabled', true);
        $options->set('isPhpEnabled', true);
        $options->set('defaultFont', 'Helvetica');
        $options->set('chroot', __DIR__ . '/../');
        
        $dompdf = new Dompdf($options);
        
        // Generate HTML content
        $html = $this->generateHtml($invoiceData);
        
        // Load HTML and render PDF
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        // Save PDF to file
        $filename = __DIR__ . '/../output/pdf/invoice_' . 
            (isset($invoiceData['invoice_number']) ? $invoiceData['invoice_number'] : time()) . '.pdf';
        
        $dir = dirname($filename);
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }

        file_put_contents($filename, $dompdf->output());
        return $filename;
    }

    private function generateHtml($data) {
        $template = file_get_contents(__DIR__ . '/../templates/index.html');
        $mustache = new Mustache_Engine();
        
        $items = isset($data['line_items']) ? $data['line_items'] : array();
        $formattedItems = [];
        $no = 1;
        
        foreach ($items as $item) {
            $formattedItems[] = [
                'no' => $no,
                'description' => $item['description'],
                'quantity' => $item['quantity'],
                'rate' => number_format($item['rate'], 0, '.', ','),
                'amount' => number_format($item['item_total'], 0, '.', ',')
            ];
            $no++;
        }

        $subtotal = $data['total'];
        $dpp = $subtotal * 11 / 12;
        $ppn = $dpp * 0.12;
        $total = $dpp + $ppn;
        $terms = urldecode($data['terms']);
        $notes = urldecode($data['notes']);
        $term_condition = urldecode($data['term_condition']);

        $viewData = [
            'company_name' => $data['company_name'],
            'company_address' => $data['company_address'],
            'invoice_number' => $data['invoice_number'],
            'invoice_date' => date('d M Y', strtotime($data['date'])),
            'due_date' => date('d M Y', strtotime($data['due_date'])),
            'customer_name' => $data['customer_name'],
            'customer_address' => $data['customer_address'],
            'line_items' => $formattedItems,
            'subtotal' => number_format($subtotal, 0, ',', ','),
            'dpp' => number_format($dpp, 0, ',', ','),
            'ppn' => number_format($ppn, 0, ',', ','),
            'total' => number_format($total, 0, ',', ','),
            'terms' => $terms,
            'status' => $data['status'],
            'note' => $notes,
            'po' => $data['po'],
            'quote' => $data['quote'],
            'term_condition' => $term_condition
        ];

        return $mustache->render($template, $viewData);
    }
}
