<?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);

$hasExplicitPdfOptions = isset($_REQUEST['orientation']) || isset($_REQUEST['pageMode']) || isset($_REQUEST['imageMode']) || isset($_REQUEST['tagMode']);
if ($cx) {
    enrepApplyReportPdfOptions($cx);
}
if (!isset($_REQUEST['orientation'])) {
    $_REQUEST['orientation'] = $_REQUEST['pageMode'] ?? '1';
}
if (!isset($_REQUEST['imageMode'])) {
    $_REQUEST['imageMode'] = '0';
}
if (!isset($_REQUEST['tagMode'])) {
    $_REQUEST['tagMode'] = '0';
}
if ($hasExplicitPdfOptions) {
    enrepSaveReportPdfOptions($GLOBALS['con'], (int)($_REQUEST['repnumber'] ?? 0), $_REQUEST);
}

$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']);
$detailsData = json_decode($details, true);

$det = [];

if (
    is_array($detailsData) &&
    !empty($detailsData['success']) &&
    isset($detailsData['item']) &&
    is_array($detailsData['item'])
) {
    $det = $detailsData['item'];
}

$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'] ?? '';

// Make report type safe for filenames
$reportTypeSafe = preg_replace('/[^0-9A-Za-z_]/', '', (string)$reportType);

// Prefer report-specific header, then generic header
$custom_header_specific = $TENANT_DIR . '/output/custom_header_' . $reportTypeSafe . '.php';
$custom_header_file     = $TENANT_DIR . '/output/custom_header.php';

if (is_file($custom_header_specific) && filesize($custom_header_specific) > 0) {

    ob_start();
    include $custom_header_specific;
    $contractHeader = ob_get_clean();

} elseif (is_file($custom_header_file) && filesize($custom_header_file) > 0) {

    ob_start();
    include $custom_header_file;
    $contractHeader = ob_get_clean();

} else {

    // existing default header block stays exactly as you have it
    $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 = ''; 
$injections = [];

/* ===== 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';
$footerMode     = $footerMode     ?? 'repeat';
$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() >= 5) {
        $out = (array) $fn($cx, $det, $freq, $repnumber);
    } else {
        $out = (array) $fn($cx, $det, $freq);
    }

    // Map result to variables expected 
    $body           = (string)($out['body']           ?? '');
    $headerTemplate = (string)($out['headerTemplate'] ?? $headerTemplate);
    $footerTemplate = (string)($out['footerTemplate'] ?? $footerTemplate);
    $footerMode     = (string)($out['footerMode']     ?? $out['footermode'] ?? $footerMode);
    $orientation    = (string)($out['orientation']    ?? $orientation);
    if (isset($out['injections']) && is_array($out['injections'])) {
    $injections = $out['injections'];
    }
}

// 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
    }
    if (isset($out['footerMode']) || isset($out['footermode'])) {
        $footerMode = (string)($out['footerMode'] ?? $out['footermode']);
    }
}

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

$reportImageDefaults = [
    'main_logo'        => 40,
    'client_logo'      => 40,
    'affiliation_logo' => 40
];

$reportImageSettings = $reportImageDefaults;

$stmtImg = $GLOBALS['con']->prepare("SELECT `report_image_settings` FROM `system` WHERE `id` = 1 LIMIT 1");
if ($stmtImg) {
    $stmtImg->execute();
    $resImg = $stmtImg->get_result();
    $rowImg = $resImg ? $resImg->fetch_assoc() : null;
    $stmtImg->close();

    if (!empty($rowImg['report_image_settings'])) {
        $tmpImg = json_decode((string)$rowImg['report_image_settings'], true);
        if (is_array($tmpImg)) {
            $reportImageSettings['main_logo'] = isset($tmpImg['main_logo']) && preg_match('/^\d{1,2}$/', (string)$tmpImg['main_logo'])
                ? (int)$tmpImg['main_logo']
                : $reportImageDefaults['main_logo'];

            $reportImageSettings['client_logo'] = isset($tmpImg['client_logo']) && preg_match('/^\d{1,2}$/', (string)$tmpImg['client_logo'])
                ? (int)$tmpImg['client_logo']
                : $reportImageDefaults['client_logo'];

            $reportImageSettings['affiliation_logo'] = isset($tmpImg['affiliation_logo']) && preg_match('/^\d{1,2}$/', (string)$tmpImg['affiliation_logo'])
                ? (int)$tmpImg['affiliation_logo']
                : $reportImageDefaults['affiliation_logo'];
        }
    }
}

// ----------------- 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
    'footerMode' => $footerMode, // repeat or tail
    'orientation' => $orientation, // 'P' or 'L'
    'customImages' => $customImages, // for AF images logic in generator
    'injections'     => $injections,
    'reportImageSettings' => $reportImageSettings,
];

;

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


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