<?php //assembler

if (file_exists('../../../' . ($_REQUEST['tenant'] ?? '') . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}
require_once('../../includes/master/form_functions.php');

$rx = mysqli_query($GLOBALS['con'], "SELECT * FROM `reportitems` WHERE `repnumber`='" . $_REQUEST['repnumber'] . "' AND `itemnumber`='" . $_REQUEST['items'] . "' ORDER BY abs(insdate) DESC LIMIT 1") or die(mysqli_error($GLOBALS['con']));
$cx = mysqli_fetch_array($rx);

$itemcheck = mysqli_query($GLOBALS['con'], "SELECT `code` FROM `itemdetails` WHERE `itemnumber`='" . $cx['itemnumber'] . "'") or die(mysqli_error($GLOBALS['con']));
$itemcode = mysqli_fetch_array($itemcheck);

if (empty($cx['frequency'])) {
    $freq = getFreq($itemcode['code']);
} else {
    $freq = $cx['frequency'];
}
$contract = getItemOwner($cx['itemnumber']);
$clt = explode("|", $contract);
$details = getItemDetailed($_REQUEST['repnumber'], $cx['itemnumber']);
$det = explode("|", $details);
$reportType = $cx['reptype'];
$dynamicCases = include('../../..' . TENANT_URL . '/output/custom_reports.php');
include('../../..' . TENANT_URL . '/output/custom_images.php');

$TENANT_DIR  = '../../../' . TENANT_URL;
$ENGINES_DIR = '../../../' . ROOT_URL . '/engines/pdf_structure';


$wrapper_Start = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>

<head>
    <meta name="viewport" content="width=device-width" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link href="packages/bootstrap/bootstrap.gen.css" rel="stylesheet">
</head>

<body bgcolor="#FFFFFF" topmargin="0" leftmargin="0" marginheight="0" marginwidth="0" style="font-size:10px!important">
    ';

$wrapper_End = '</body>

</html>';

$orientation = 'P';
if (isset($_REQUEST['orientation'])) {
    $orientation = ($_REQUEST['orientation'] === '0') ? 'L' : 'P';
}

$repnumber = $_REQUEST['repnumber'] ?? '';
$custom_header_file = $TENANT_DIR . '/output/custom_header.php';

if (is_file($custom_header_file) && filesize($custom_header_file) > 0) {
    ob_start();
    include $custom_header_file;
    $contractHeader = ob_get_clean();
} else {

    $contractHeader = '
<table class="tableClientDetails" width="100%">
    <tr valign="top">
        <td width="30%" valign="top">
            <table width="100%">
                <tr>
                    <th width="25%" class="themeColour">Owner</th>
                    <td>' . strtoupper($clt[0] ?? '') . '</td>
                </tr>
                <tr valign="top">
                    <th valign="top"></th>
                    <td valign="top">' . getClientAddressLong($cx['clientnumber'] ?? 0, 'address') . '</td>
                </tr>
            </table>
        </td>
        <td valign="top" width="30%">
            <table id="clientDetails" width="100%">
                <tr valign="top">
                    <th width="25%" class="themeColour">Site</th>
                    <td>' . strtoupper(getItemLocation($cx['itemnumber'] ?? 0, 'name')) . '</td>
                </tr>
                <tr valign="top">
                    <th valign="top"></th>
                    <td valign="top">' . getItemLocation($cx['itemnumber'] ?? 0, 'addressLong') . '</td>
                </tr>
            </table>
        </td>
        <td valign="top">
            <table id="repDetails" class="table-sm" width="100%">
                <tr>
                    <td align="right"><i>' . nl2br(getItemReportDesc($repnumber, 'regs')) . '</i></td>
                </tr>
                <tr>
                    <td align="right" style="font-size:12px" class="themeColour"><strong>' .
        getItemReportDesc($repnumber, 'formtype') . '</strong></td>
                </tr>
                <tr>
                    <td align="right"><small><i>Contract Number:</i> ' . ($clt[1] ?? '') . '</small></td>
                </tr>
                <tr>
                    <td align="right"><small><i>Report Number:</i> ' . $repnumber . '</small></td>
                </tr>
                <tr>
                    <td align="right"><small><i>Item Ref:</i> ' . ($cx['itemnumber'] ?? '') . '</small></td>
                </tr>
            </table>
        </td>
    </tr>
</table>';
}



$headerTemplate = 'header.php';
$footerTemplate = 'footer.php';
$inst = '';
$body = '';


/* ===== TEMPLATES: default + custom callable maps (REPLACES THE OLD SWITCH) ===== */

// Resolve tenant path
$tenantSlug = defined('TENANT_URL') ? TENANT_URL : ($_REQUEST['tenant'] ?? '');
$TENANT_DIR = '../../../' . $tenantSlug;

// Load default templates (REQUIRED). Must return ['FORM' => function($cx,$det,$freq[, $repnumber]) { return compact('body','headerTemplate','footerTemplate','orientation'); }]
$defaultFile = $TENANT_DIR . '/output/default_reports.php';
if (!is_file($defaultFile)) { http_response_code(500); die('default_reports.php missing'); }
$defaultCases = include $defaultFile;
if (!is_array($defaultCases)) { http_response_code(500); die('default_reports.php must return an array'); }

// Load custom templates (OPTIONAL). Same return shape as default.
$dynamicCases = [];
$customFile = $TENANT_DIR . '/output/custom_reports.php';
if (is_file($customFile)) {
    $ret = include $customFile;
    if (is_array($ret)) $dynamicCases = $ret;
}

// Select callable: custom overrides default
$fn = null;
if (isset($dynamicCases[$reportType]) && is_callable($dynamicCases[$reportType])) {
    $fn = $dynamicCases[$reportType];
} elseif (isset($defaultCases[$reportType]) && is_callable($defaultCases[$reportType])) {
    $fn = $defaultCases[$reportType];
}

// Prepare defaults exactly as before (your file already defines these earlier)
$headerTemplate = $headerTemplate ?? 'header.php';
$footerTemplate = $footerTemplate ?? 'footer.php';
$orientation    = $orientation    ?? 'P';
$inst           = '';      // deprecated; everything goes in $body
$body           = '';

// Call the template if found
if ($fn) {
    // Support both 3-arg and 4-arg callables
    if ((new ReflectionFunction($fn))->getNumberOfParameters() >= 4) {
        $out = (array) $fn($cx, $det, $freq, $repnumber);
    } else {
        $out = (array) $fn($cx, $det, $freq);
    }

    // Map result to variables expected by pdfGenerator-single.php
    $body           = (string)($out['body']           ?? '');
    $headerTemplate = (string)($out['headerTemplate'] ?? $headerTemplate);
    $footerTemplate = (string)($out['footerTemplate'] ?? $footerTemplate);
    $orientation    = (string)($out['orientation']    ?? $orientation);
}

// Guard to avoid a blank PDF during wiring
if ($body === '') {
    $body = '<div style="padding:8px;font-size:12px;color:#900">No content produced for form '
          . htmlspecialchars($reportType) . '.</div>';
}

/* ===== END TEMPLATES BLOCK ===== */


if (
    is_array($dynamicCases) && isset($dynamicCases[$reportType]) &&
    is_callable($dynamicCases[$reportType])
) {

    $out = $dynamicCases[$reportType]($cx, $det, $freq);
    if (!empty($out['headerTemplate'])) {
        $headerTemplate = $out['headerTemplate']; // always .php
    }
    if (isset($out['inst'])) {
        $inst = (string)$out['inst'];
    }
    if (!empty($out['body'])) {
        $body = (string)$out['body'];
    }
    if (!empty($out['footerTemplate'])) {
        $footerTemplate = $out['footerTemplate']; // always .php
    }
}

// Ensure $customImages is always an array
if (!isset($customImages) || !is_array($customImages)) {
    $customImages = [];
}

// ----------------- Return the parts for the generator -----------------
$parts = [
    'wrapper_Start' => $wrapper_Start,
    'wrapper_End' => $wrapper_End,
    'headerTemplate' => $headerTemplate, // ref name; generator resolves path
    'contractHeader' => $contractHeader, // first page only
    'inst' => $inst, // first page only (under header)
    'body' => $body, // main content
    'footerTemplate' => $footerTemplate, // ref name or file per your current use
    'orientation' => $orientation, // 'P' or 'L'
    'customImages' => $customImages, // for AF images logic in generator
];

;

$genScript = (getCompanyDetails('repMode') == 0)
    ? 'pdfGenerator-repeat.php'
    : 'pdfGenerator-single.php';


include('../../includes/engines/' . $genScript);
echo $_REQUEST['repnumber'] . "-0-0" . $cx['itemnumber'];