<?php
declare(strict_types=1);
require_once __DIR__ . '/../../app/Models/TrialBalance.php';
require_once __DIR__ . '/../../app/Models/ProfitLoss.php';
require_once __DIR__ . '/../../app/Models/BalanceSheet.php';
require_once __DIR__ . '/../../app/Models/CashFlow.php';

class PdfController {

    public function generate(string $type): void {
        switch ($type) {
            case 'trial-balance':
                $model = new TrialBalance();
                $data = $model->getTrialBalance($_GET['start'] ?? null, $_GET['end'] ?? null);
                $title = "Trial Balance";
                $view  = __DIR__ . '/../../public/reports/pdf/trial-balance.php';
                break;

            case 'profit-loss':
                $model = new ProfitLoss();
                $data = $model->getProfitLoss($_GET['start'] ?? null, $_GET['end'] ?? null);
                $title = "Profit & Loss Statement";
                $view  = __DIR__ . '/../../public/reports/pdf/profit-loss.php';
                break;

            case 'balance-sheet':
                $model = new BalanceSheet();
                $data = $model->getBalanceSheet($_GET['as_of'] ?? null);
                $title = "Balance Sheet";
                $view  = __DIR__ . '/../../public/reports/pdf/balance-sheet.php';
                break;

            case 'cashflow':
                $model = new CashFlow();
                $data = $model->getCashFlow($_GET['start'] ?? null, $_GET['end'] ?? null);
                $title = "Cash Flow Statement";
                $view  = __DIR__ . '/../../public/reports/pdf/cashflow.php';
                break;

            default:
                die("Invalid report type");
        }

        ob_start();
        include $view;
        $html = ob_get_clean();

        // PDF header
        header("Content-Type: application/pdf");
        header("Content-Disposition: inline; filename={$type}.pdf");

        // Use pypandoc for easy PDF conversion
        require_once __DIR__ . '/../../vendor/autoload.php';
        $tmpFile = tempnam(sys_get_temp_dir(), 'report_') . '.html';
        file_put_contents($tmpFile, $html);

        // Convert to PDF
        echo shell_exec("pypandoc --from=html --to=pdf $tmpFile");
        unlink($tmpFile);
    }
}
