<?php
// /includes/engines/report.php
declare(strict_types=1);
mb_internal_encoding('UTF-8');
header('Content-Type: application/json; charset=UTF-8');

try {
    // Tenant
    $tenant = trim($_REQUEST['tenant'] ?? '');
    if ($tenant === '') throw new RuntimeException('Missing tenant');

    if (file_exists('../../../' . $tenant . '/config.php')) require_once('../../../' . $tenant . '/config.php');
    if (file_exists('/config.php')) require_once('/config.php');

    // Optional helpers
    $financeFns = '../../../' . $tenant . '/includes/finance/finance_functions.php';
    if (file_exists($financeFns)) require_once($financeFns);

    // Inputs
    $type        = trim((string)($_REQUEST['type'] ?? 'report'));
    $contentIn   = (string)($_REQUEST['content'] ?? '');
    if ($contentIn === '') throw new RuntimeException('Missing content');

    $variant     = strtolower(trim((string)($_REQUEST['variant'] ?? 'default'))); // default | statement
    $format      = strtoupper(trim((string)($_REQUEST['format'] ?? 'A4-L')));
    $orientation = strtoupper(trim((string)($_REQUEST['orientation'] ?? '')));
    $headerTxt   = (string)($_REQUEST['header'] ?? '');
    $footerTxt   = (string)($_REQUEST['footer'] ?? '');
    $logoRel     = (string)($_REQUEST['logo'] ?? 'images/company/logo.jpg');

    $showPN      = isset($_REQUEST['show_page_numbers']) ? (int)$_REQUEST['show_page_numbers'] : 1;
    $showDate    = isset($_REQUEST['show_generated_date']) ? (int)$_REQUEST['show_generated_date'] : 1;
    $cover       = isset($_REQUEST['cover']) ? (int)$_REQUEST['cover'] : 0;
    $water       = trim((string)($_REQUEST['watermark'] ?? ''));
    $emitBodyCss = !empty($_REQUEST['emit_body_css']) ? 1 : 0;

    $cssArr      = [];
    if (isset($_REQUEST['css'])) $cssArr = is_array($_REQUEST['css']) ? $_REQUEST['css'] : [$_REQUEST['css']];

    // Paths
    $tenantRoot = realpath('../../../' . $tenant) ?: ('../../../' . $tenant);
    $outDir     = $tenantRoot . '/output/reps';
    if (!is_dir($outDir)) @mkdir($outDir, 0775, true);
    $typeUK = $type;
    if (preg_match('/^(.*_)(\d{4})-(\d{2})-(\d{2})$/', $type, $m)) {
        $typeUK = $m[1] . $m[4] . '-' . $m[3] . '-' . $m[2];   
    }
    $fnameBase = preg_replace('/[^a-zA-Z0-9_\-]+/', '_', $typeUK);
    $fname = $fnameBase . '.pdf';
    $fpath = $outDir . '/' . $fname;

    // Orientation
    if ($orientation === 'L' || $orientation === 'P') {
        $base = strpos($format, '-') !== false ? explode('-', $format)[0] : $format;
        $format = $base . '-' . $orientation;
    }
    if (strpos($format, '-') === false) $format .= '-L';

    // Sanitise body
    $contentIn = preg_replace('#<script\b[^>]*>.*?</script>#is', '', $contentIn);

    // -------- Legacy-compatible blocks --------
    $body   = '';
    $header = '';
    $footer = '';

    // Tenant style.php (CSS rules)
    $stylePath  = $tenantRoot . '/engines/report_structure/style.php';
    $styleRaw   = is_file($stylePath) ? file_get_contents($stylePath) : '';
    $styleNoTag = preg_replace('#</?style[^>]*>#i', '', $styleRaw);

    // Tenant header/footer includes
    $headerView = $tenantRoot . '/engines/report_structure/header.php';
    if (is_file($headerView)) $header .= file_get_contents($headerView);

    // AddressBox / Statement
    if (!empty($_REQUEST['addressBox'])) {
        $body .= '<table width="100%" style="font-family: verdana; font-size: 8pt; color: #2a3f54; font-weight: bold;">
        <tr><td align="right"><h3>STATEMENT OF ACCOUNT</h3></td></tr></table>';

        switch ($_REQUEST['addressBox']) {
            case 'client':
                if (function_exists('getClientDetails')) {
                    $body .= '<table width="100%" style="font-family: verdana; font-size: 8pt; color: #000000; border-bottom:1px solid #2a3f54">
                    <tr><td>' . getClientDetails($_REQUEST['clientnumber']) . '</td></tr></table>';
                }
                break;
            case 'agent':
                if (function_exists('getCompanyDetails') && function_exists('getAgentDetails')) {
                    $body .= '<table width="100%" style="font-family: serif; font-size: 8pt; color: #000000; font-weight: bold; font-style: italic; border-bottom:1px solid #2a3f54">
                    <tr>
                      <td style="width:50%">' . getCompanyDetails('address') . '</td>
                      <td style="width:50%; text-align:right">' . getAgentDetails($_REQUEST['number']) . '</td>
                    </tr></table>';
                }
                break;
            case 'broker':
                if (function_exists('getCompanyDetails') && function_exists('getBrokerDetails')) {
                    $body .= '<table width="100%" style="font-family: serif; font-size: 8pt; color: #000000; font-weight: bold; font-style: italic; border-bottom:1px solid #2a3f54">
                    <tr>
                      <td style="width:50%">' . getCompanyDetails('address') . '</td>
                      <td style="width:50%; text-align:right">' . getBrokerDetails($_REQUEST['number']) . '</td>
                    </tr></table>';
                }
                break;
        }

        $total = $_REQUEST['total'] ?? '';
        $footer .= '
        <table width="100%" style="font-family: verdana; font-size: 8pt; color: #000000;">
          <tr style="background-color:#2a3f54">
            <td align="right" style="color:#fff; font-weight: bold;">Account current Balance: £' . htmlspecialchars((string)$total) . '</td>
          </tr>
          <tr><td align="center">-- Thank you for your business --</td></tr>
          <tr><td><p>Please make all cheques Payable to <span style="color:#2a3f54">[CNAME]</span></p>
          <p><span style="color:#2a3f54">Bank Name</span> [CBANK]. <span style="color:#2a3f54">Account Number</span> [CACNO]. <span style="color:#2a3f54">Sort Code</span> [CSCODE]</p>
          <p><small>When paying by BACS, please ensure that your company name and this invoice number is used as payment reference.</small></p></td></tr>
        </table>';
    } else {
        $footerView = $tenantRoot . '/engines/report_structure/footer_view.php';
        //if (is_file($footerView)) $footer .= file_get_contents($footerView);
    }

    // Append incoming content
    $body .= $contentIn;

    // -------- Placeholder replacements --------
    $tenantKey = defined('TENANT_URL') ? TENANT_URL : $tenant;

    $get = function (string $key): string {
        return function_exists('getCompanyDetails') ? (string)getCompanyDetails($key) : '';
    };

    // Footer text placeholders
    $footer = str_replace(
        ['[WEB]','[CNAME]','[CBANK]','[CACNO]','[CSCODE]'],
        [$get('web'), $get('name'), $get('bankName'), $get('accountNo'), $get('sortCode')],
        $footer
    );

    // Body path placeholder
    $body = str_replace('[REPORT_PATH]', $get('web'), $body);

    // Header images [LGO], [AF1]..[AF6]
    $imgBase = '../../../' . $tenantKey . '/images/company/';
    $logoPath  = $imgBase . 'logo.jpg';
    if (file_exists($logoPath)) {
        $header = str_replace('[LGO]', '<img src="' . $logoPath . '" height="50px" />', $header);
    }
    for ($i = 1; $i <= 6; $i++) {
        $afPath = $imgBase . 'afl_' . $i . '.jpg';
        if (file_exists($afPath)) {
            $header = str_replace('[AF' . $i . ']', '<td><img src="' . $afPath . '" width="50px" /></td>', $header);
        }
    }

    // -------- CSS aggregation for mPDF --------
    $css = '';

    // 1) Tenant bootstrap for PDFs
    $bootstrapPdf = $tenantRoot . '/packages/bootstrap/bootstrap.gen.css';
    if (is_file($bootstrapPdf)) {
        $css .= file_get_contents($bootstrapPdf) . "\n";
        if ($emitBodyCss) $body .= '<style>' . file_get_contents($bootstrapPdf) . '</style>';
    }

    // 2) Tenant style.php rules
    if ($styleNoTag !== '') {
        $css .= $styleNoTag . "\n";
        if ($emitBodyCss) $body .= '<style>' . $styleNoTag . '</style>';
    }

    // 3) Extra css[]
    foreach ($cssArr as $c) {
        $cPath = $c;
        if (strpos($cPath, '://') === false) {
            $cPath = (str_starts_with($c, '/')) ? ($tenantRoot . $c) : ($tenantRoot . '/' . $c);
        }
        if (is_file($cPath)) {
            $css .= file_get_contents($cPath) . "\n";
            if ($emitBodyCss) $body .= '<style>' . file_get_contents($cPath) . '</style>';
        }
    }

    // 4) Minimal fallback
    $css .= "table{border-collapse:collapse;width:100%}.table,.table td,.table th{border:1px solid #ddd}.table th{background:#f6f6f6}.table-striped tbody tr:nth-child(odd){background:#fafafa}.table-sm td,.table-sm th{padding:6px}\n";

    // -------- mPDF --------
    require_once '../../packages/mpd/vendor/autoload.php'; // fixed path

    $mpdfCfg = [
        'mode' => 'utf-8',
        'format' => $format,
        'margin_left'   => 12,
        'margin_right'  => 12,
        'margin_top'    => 38,
        'margin_bottom' => 22,
        'margin_header' => 10,
        'margin_footer' => 10,
        'tempDir' => sys_get_temp_dir(),
    ];
    $mpdf = new \Mpdf\Mpdf($mpdfCfg);
    $mpdf->SetTitle($type);
    $mpdf->SetAuthor('EnRep Reporting System');
    $mpdf->SetSubject($type);

    if ($water !== '') { $mpdf->SetWatermarkText($water, 0.1); $mpdf->showWatermarkText = true; }

    // Header/Footer blocks
    $ukDate = date('d-m-Y');
    $pageNo = $showPN ? '{PAGENO}/{nbpg}' : '';
    $genStr = $showDate ? 'Generated: ' . $ukDate : '';

    $logoAbs = $tenantRoot . '/' . ltrim($logoRel, '/');
    $logoHtml = is_file($logoAbs) ? '<img src="' . htmlspecialchars($logoAbs) . '" style="height:28px;">' : '';

    $prettyTitle = $typeUK; // use the UK-normalised version if you kept it in scope
    if (preg_match('/^vat_([a-z]+)_(\d{2})-(\d{2})-(\d{4})$/i', $prettyTitle, $m)) {
        $labelMap = ['in'=>'VAT In','out'=>'VAT Out','compare'=>'VAT Comparison'];
        $label = $labelMap[strtolower($m[1])] ?? ucfirst($m[1]);
        $prettyTitle = $label . ' ' . $m[2] . '-' . $m[3] . '-' . $m[4];          // dd-mm-yyyy
    } elseif (preg_match('/^vat_([a-z]+)_(\d{4})-(\d{2})-(\d{2})$/i', $prettyTitle, $m)) {
        $labelMap = ['in'=>'VAT In','out'=>'VAT Out','compare'=>'VAT Comparison'];
        $label = $labelMap[strtolower($m[1])] ?? ucfirst($m[1]);
        $prettyTitle = $label . ' ' . $m[4] . '-' . $m[3] . '-' . $m[2];          // convert yyyy-mm-dd → dd-mm-yyyy
    } else {
        $prettyTitle = ucwords(str_replace(['_', '-'], ' ', $prettyTitle));
    }

    // --- Compose header block (no logo, centred titles) ---
    $headerBlock = $header; 

    if ($variant === 'statement') {
        $headerBlock .= '
        <table width="100%" style="border-bottom:1px solid #ccc; font-size:10pt;">
            <tr>
            <td align="center">
                <div style="font-size:12pt;font-weight:600;">' . htmlspecialchars($prettyTitle) . '</div>
                <div style="font-size:9pt;color:#666;">Statement</div>
            </td>
            </tr>
        </table>';
    } else {
        $rightTxt = htmlspecialchars($headerTxt);
        $headerBlock .= '
        <table width="100%" style="border-bottom:1px solid #ccc; font-size:10pt;">
            <tr>
            <td align="center">
                <div style="font-size:12pt;font-weight:600;">' . htmlspecialchars($prettyTitle) . '</div>'
                . ($rightTxt !== '' ? '<div style="font-size:9pt;color:#666;">' . $rightTxt . '</div>' : '') .
            '</td>
            </tr>
        </table>';
    }

    $footerBlock = '<table width="100%" style="border-top:1px solid #ccc; font-size:9pt; color:#666;">
      <tr>
        <td width="33%">' . htmlspecialchars($genStr) . '</td>
        <td width="34%" align="center">' . htmlspecialchars($footerTxt) . '</td>
        <td width="33%" align="right">' . $pageNo . '</td>
      </tr>
    </table>';
    if (trim($footer) !== '') $footerBlock = $footer . $footerBlock;

    $mpdf->SetHTMLHeader($headerBlock);
    $mpdf->SetHTMLFooter($footerBlock);

    // CSS + Body
    $mpdf->WriteHTML($css, \Mpdf\HTMLParserMode::HEADER_CSS);

    if ($cover) {
        $mpdf->WriteHTML('<div style="height:70vh;display:flex;flex-direction:column;justify-content:center;align-items:center;text-align:center;">
            <div style="margin-bottom:12px;">' . $logoHtml . '</div>
            <div style="font-size:22pt;font-weight:700;margin-bottom:8px;">' . htmlspecialchars($type) . '</div>'
            . ($headerTxt !== '' ? '<div style="font-size:12pt;color:#666;">' . htmlspecialchars($headerTxt) . '</div>' : '') .
            '<div style="font-size:10pt;color:#999;margin-top:18px;">' . htmlspecialchars($genStr) . '</div>
        </div>', \Mpdf\HTMLParserMode::HTML_BODY);
        $mpdf->AddPage();
    }

    $mpdf->WriteHTML('<div class="report-body" style="font-size:10pt; line-height:1.35;">' . $body . '</div>', \Mpdf\HTMLParserMode::HTML_BODY);
    $mpdf->Output($fpath, \Mpdf\Output\Destination::FILE);

    // Return relative path (per your correction)
    $href = '/output/reps/' . $fname;

    echo json_encode(['ok' => 1, 'href' => $href, 'file' => $fname], JSON_UNESCAPED_SLASHES);
    exit;

} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => 0, 'error' => $e->getMessage()]);
    exit;
}