<?php
require_once __DIR__ . '/../security.php';
$tenant = "alanboswell.enrep.co.uk";
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {

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

if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    enrep_fail(400, 'Tenant config not found');
}
enrep_require_user();


$mode = enrep_request_enum('mode', ['split', ''], '');
$requestClientnumber = enrep_request_int('clientnumber');
$site = enrep_request_int('site');
$requestedCoverFile = array_key_exists('cover_file', $_POST) ? enrep_request_string('cover_file', '', 160) : '';
$coverTitle = array_key_exists('cover_title', $_POST) ? enrep_request_string('cover_title', '', 120) : '';
$dateRangeTitle = '';
if (array_key_exists('cover_dateRange', $_REQUEST)) {
    $dateRangeTitle = enrep_request_string('cover_dateRange', '', 120);
} elseif (array_key_exists('cover_date_range', $_REQUEST)) {
    $dateRangeTitle = enrep_request_string('cover_date_range', '', 120);
}

if ($mode !== 'split') {
    require_once('../../includes/master/form_functions.php');
}
require_once __DIR__ . '/../delivery/exclusions.php';

$cover_h = static function ($value): string {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
};

$cover_address = static function ($value): string {
    $value = preg_replace('/<br\s*\/?>/i', "\n", (string)$value);
$value = strip_tags($value);
$lines = preg_split('/\r\n|\r|\n/', $value);
$lines = array_map(static function ($line): string {
return htmlspecialchars(trim($line), ENT_QUOTES, 'UTF-8');
}, $lines ?: []);
$lines = array_values(array_filter($lines, static function ($line): bool {
return $line !== '';
}));

return implode('<br>', $lines);
};

$cover_file = static function (string $file): string {
$file = enrep_safe_filename($file);
if (!preg_match('/\Areport_cover(?:_[A-Za-z0-9_-]+)?\.pdf\z/', $file)) {
enrep_fail(400, 'Invalid cover file');
}
return $file;
};

$cover_template = static function (string $template): string {
$template = trim($template);
if ($template === '') {
$template = 'default';
}
$template = preg_replace('/\.php\z/i', '', $template);
if (!preg_match('/\A[A-Za-z0-9_-]{1,80}\z/', $template)) {
enrep_fail(400, 'Invalid cover template');
}

return $template . '.php';
};

$cover_template_path = static function (string $templateFile): string {
$tenantDir = defined('TENANT_URL') ? trim((string)TENANT_URL, "/\\") : enrep_tenant_segment();
$path = '../../../' . $tenantDir . '/output/covers/' . $templateFile;
if (!is_file($path)) {
enrep_fail(500, 'Cover template not found');
}

return $path;
};

$cover_truncate = static function ($value, int $limit = 20): string {
$value = trim((string)$value);
if ($limit < 1) { return $value; } if (function_exists('mb_strlen') && function_exists('mb_substr')) { return
    mb_strlen($value, 'UTF-8' )> $limit ? mb_substr($value, 0, $limit, 'UTF-8') . '...' : $value;
    }

    return strlen($value) > $limit ? substr($value, 0, $limit) . '...' : $value;
    };

    $coverPrefs = is_array($GLOBALS['assetPrefs'] ?? null) ? $GLOBALS['assetPrefs'] : [];
    if (isset($GLOBALS['con']) && $GLOBALS['con'] instanceof mysqli) {
    try {
    $stmt = $GLOBALS['con']->prepare("SELECT `asset_table_prefs` FROM `system` WHERE `id`='1' LIMIT 1");
    if ($stmt) {
    $stmt->execute();
    $stmt->bind_result($coverPrefsJson);
    if ($stmt->fetch() && trim((string)$coverPrefsJson) !== '') {
    $decodedPrefs = json_decode((string)$coverPrefsJson, true);
    if (is_array($decodedPrefs)) {
    foreach ($decodedPrefs as $prefKey => $prefValue) {
    if (is_array($prefValue)) {
    $coverPrefs[$prefKey] = array_merge($coverPrefs[$prefKey] ?? [], $prefValue);
    }
    }
    }
    }
    $stmt->close();
    }
    } catch (Throwable $e) {
    // Keep existing labels if the settings lookup is unavailable.
    }
    }
    $cover_label = static function (string $key, string $fallback) use (&$coverPrefs): string {
    $label = $coverPrefs[$key]['label'] ?? '';
    if (is_string($label) && trim($label) !== '') {
    return trim($label);
    }

    return function_exists('asset_label') ? asset_label($key, $fallback) : $fallback;
    };

    $coverTitleHtml = $coverTitle !== '' ? ' - ' . $cover_h($coverTitle) : '';
    $coverDateRangeHtml = $dateRangeTitle !== '' ? $cover_h($dateRangeTitle) : '';

    $rawItems = $_REQUEST['items'] ?? [];
    if (!is_array($rawItems)) {
    $decoded = json_decode((string)$rawItems, true);
    $rawItems = is_array($decoded) ? $decoded : preg_split('/[|,\s]+/', (string)$rawItems, -1, PREG_SPLIT_NO_EMPTY);
    }

    $ret = '';
    $coverRows = [];
    $clientnumber = $requestClientnumber;
    $firstRepnumber = 0;
    $firstItemnumber = 0;
    $firstForm = 0;
    $coverTableLabels = [
    'itemnumber' => 'Item No',
    'repnumber' => 'Report No',
    'description' => $cover_label('description', 'Description'),
    'manufacturer' => $cover_label('manufacturer', 'Manufacturer'),
    'make_model' => $cover_label('make_model', 'Make/Model'),
    'type' => $cover_label('type', 'Type'),
    'condition' => $cover_label('condition', 'Condition'),
    'locname' => $cover_label('locname', 'Location'),
    'subloc' => $cover_label('subloc', 'Sub-location'),
    'location' => $site > 0 ? $cover_label('subloc', 'Sub-location') : $cover_label('locname', 'Location'),
    'postcode' => $cover_label('postcode', 'Post Code'),
    'plantnumber' => $cover_label('plantnumber', 'Plant No'),
    'serialnumber' => $cover_label('serialnumber', 'Serial No'),
    'swl' => 'SWL',
    'lastInspection' => 'Last Inspection',
    'duedate' => $cover_label('duedate', 'Due'),
    'nextInspection' => $cover_label('duedate', 'Next Inspection'),
    'lastReport' => $cover_label('lastReport', 'Result'),
    'status' => $cover_label('lastReport', 'Status'),
    ];

    $coverColumnDefinitions = [
    'itemnumber' => ['label' => $coverTableLabels['itemnumber'], 'width' => '8%', 'align' => 'center', 'link' => true],
    'repnumber' => ['label' => $coverTableLabels['repnumber'], 'width' => '9%', 'align' => 'center', 'link' => true],
    'description' => ['label' => $coverTableLabels['description'], 'width' => '20%', 'short' => true],
    'manufacturer' => ['label' => $coverTableLabels['manufacturer'], 'width' => '12%'],
    'make_model' => ['label' => $coverTableLabels['make_model'], 'width' => '12%'],
    'type' => ['label' => $coverTableLabels['type'], 'width' => '10%'],
    'condition' => ['label' => $coverTableLabels['condition'], 'width' => '10%'],
    'locname' => ['label' => $coverTableLabels['locname'], 'width' => '15%'],
    'subloc' => ['label' => $coverTableLabels['subloc'], 'width' => '15%'],
    'location' => ['label' => $coverTableLabels['location'], 'width' => '15%'],
    'postcode' => ['label' => $coverTableLabels['postcode'], 'width' => '8%'],
    'plantnumber' => ['label' => $coverTableLabels['plantnumber'], 'width' => '12%'],
    'serialnumber' => ['label' => $coverTableLabels['serialnumber'], 'width' => '12%'],
    'swl' => ['label' => $coverTableLabels['swl'], 'width' => '7%'],
    'lastInspection' => ['label' => $coverTableLabels['lastInspection'], 'width' => '9%', 'align' => 'center'],
    'duedate' => ['label' => $coverTableLabels['duedate'], 'width' => '9%', 'align' => 'center'],
    'nextInspection' => ['label' => $coverTableLabels['nextInspection'], 'width' => '9%', 'align' => 'center'],
    'lastReport' => ['label' => $coverTableLabels['lastReport'], 'width' => '8%', 'align' => 'center', 'status' =>
    true],
    'status' => ['label' => $coverTableLabels['status'], 'width' => '8%', 'align' => 'center', 'status' => true],
    ];

    foreach ($rawItems as $itemdata) {
    $itemdata = trim((string)$itemdata);
    if (!preg_match('/\A([0-9]+)-([0-9]+)-([0-9]+)(?:-[0-9]+)?\z/', $itemdata, $matches)) {
    continue;
    }

    $repnumber = (int)$matches[1];
    $itemnumber = (int)$matches[2];
    if ($repnumber < 1 || $itemnumber < 1) { continue; } $stmt=$GLOBALS['con']->prepare("SELECT * FROM `reportitems`
        WHERE `repnumber`=? AND `itemnumber`=? LIMIT 1") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('ii', $repnumber, $itemnumber);
        $stmt->execute();
        $rc = $stmt->get_result();
        $stmt->close();
        $rd = mysqli_fetch_array($rc);
        if (!$rd) {
        continue;
        }

        $stmt = $GLOBALS['con']->prepare("SELECT * FROM `itemdetails` WHERE `itemnumber`=? LIMIT 1") or
        die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $itemnumber);
        $stmt->execute();
        $ic = $stmt->get_result();
        $stmt->close();
        $id = mysqli_fetch_array($ic);
        if (!$id) {
        continue;
        }
        if (delivery_item_code_excluded($id['code'] ?? '')) {
        continue;
        }

        $clientnumber = (int)$rd['clientnumber'];
        if ($firstRepnumber < 1) { $firstRepnumber=$repnumber; $firstItemnumber=$itemnumber;
            $firstForm=(int)($rd['reptype'] ?? $matches[3]); } $description=$id['desc'] ?? '' ;
            $descriptionShort=$cover_truncate($description, 32); $manufacturer=$id['manf'] ?? $id['manufacturer'] ?? ''
            ; $model=$id['model'] ?? '' ; $makeModel=trim((string)$model); $type=function_exists('getReportDesc') ?
            getReportDesc($rd['reptype'], 'formtype' ) : ($rd['reptype'] ?? '' ); $condition=$id['condition'] ??
            $id['itemcondition'] ?? '' ; $plantnumber=$id['plantnumber'] ?? '' ; $serialnumber=$id['serialnumber'] ?? ''
            ; $swl=$id['swl'] ?? '' ; $locationName=getItemLocation($itemnumber, 'name' );
            $subLocation=trim((string)($id['subloc'] ?? '' )); $locationDisplay=$site> 0 ? $subLocation : $locationName;
            $postcode = '';
            if (!empty($id['locnumber'])) {
            $stmt = $GLOBALS['con']->prepare("SELECT `postcode` FROM `locations` WHERE `locnumber`=? LIMIT 1");
            if ($stmt) {
            $locnumber = (int)$id['locnumber'];
            $stmt->bind_param('i', $locnumber);
            $stmt->execute();
            $stmt->bind_result($postcodeResult);
            if ($stmt->fetch()) {
            $postcode = (string)$postcodeResult;
            }
            $stmt->close();
            }
            }

            $col = '';
            $tag = 'P2UD';
            if ($rd['result'] === "DEFECT" || $rd['result'] === "DEFECTS") {
            $col = "#F4AA09";
            $tag = "DEFECT";
            }
            if ($rd['result'] === "URGENT") {
            $col = "#e96152";
            $tag = "URGENT";
            }
            if ($rd['result'] === "PASS") {
            $col = "#007E33";
            $tag = "PASS";
            }
            if ($rd['result'] === "OBS") {
            $col = "#333333";
            $tag = "OBS";
            }
            if ($rd['reptype'] === "503" || $rd['reptype'] === "518") {
            $col = "#cccccc";
            $tag = "PNA";
            }
            if ($rd['result'] === "POBS") {
            $col = "#007E33";
            $tag = "PASS/OBS";
            }


            $coverRows[] = [
            'itemnumber' => $itemnumber,
            'repnumber' => $repnumber,
            'description' => $description,
            'descriptionShort' => $descriptionShort,
            'manufacturer' => $manufacturer,
            'make_model' => $makeModel,
            'type' => $type,
            'condition' => $condition,
            'location' => $locationName,
            'locname' => $locationName,
            'subloc' => $subLocation,
            'locationDisplay' => $locationDisplay,
            'locationHtml' => $cover_h($locationDisplay),
            'locnameHtml' => $cover_h($locationName),
            'sublocHtml' => $cover_h($subLocation),
            'postcode' => $postcode,
            'plantnumber' => $plantnumber,
            'serialnumber' => $serialnumber,
            'swl' => $swl,
            'lastInspection' => !empty($rd['insdate']) ? date('d-m-Y', (int)$rd['insdate']) : '',
            'duedate' => !empty($rd['nextDate']) ? date('d-m-Y', (int)$rd['nextDate']) : '',
            'nextInspection' => !empty($rd['nextDate']) ? date('d-m-Y', (int)$rd['nextDate']) : '',
            'lastReport' => $tag,
            'status' => $tag,
            'statusColour' => $col,
            'reportUrl' => 'https://[REPORT_PATH]/preview.php?repnumber=' . $cover_h($repnumber),
            ];

            $ret .= '
            <tr>
                <td align="center"><a class="btn-info coverLink"
                        href="https://[REPORT_PATH]/preview.php?repnumber=' . $cover_h($repnumber) . '"
                        alt="View full report online" title="View full report online">&nbsp;&nbsp;' .
                        $cover_h($repnumber) . '&nbsp;&nbsp;</a></td>
                <td align="center" title="' . $cover_h($description) . '">' . $cover_h($descriptionShort) . '</td>
                <td align="center" class="cover-location">' . $cover_h($locationDisplay) . '</td>
                <tdalign="center">' . $cover_h($plantnumber) . '</tdalign=>
                    <td align="center">' . $cover_h($serialnumber) . '</td>
                    <td align="center">' . $cover_h($swl) . '</td>
                    <td align="center">' . $cover_h(!empty($rd['insdate']) ? date('d-m-Y', (int)$rd['insdate']) : '') .
                        '</td>
                    <td align="center">' . $cover_h(!empty($rd['nextDate']) ? date('d-m-Y', (int)$rd['nextDate']) : '')
                        . '</td>
                    <td align="center" style="background-color:' . $cover_h($col) . '; color:#ffffff"><a
                            class="coverLink" style="text-decoration:none;color:#ffffff"
                            href="https://[REPORT_PATH]/preview.php?repnumber=' . $cover_h($repnumber) . '"
                            alt="View full report online" title="View full report online" target="_BLANK">' .
                            $cover_h($tag) . '</a></td>
            </tr>';
            }

            if ($clientnumber < 1) { $clientnumber=$requestClientnumber; } $coverTableRows=$ret; $cover_cell=static
                function (array $coverRow, string $key, array $column=[]) use ($cover_h): string {
                $value=$coverRow[$key] ?? '' ; if ($key==='location' ) { $value=$coverRow['locationDisplay'] ??
                $coverRow['locname'] ?? $coverRow['location'] ?? '' ; } elseif ( !empty($column['short']) &&
                isset($coverRow[$key . 'Short' ]) ) { $value=$coverRow[$key . 'Short' ]; } $valueHtml=in_array( $key,
                ['location', 'locname' , 'subloc' ], true ) && isset($coverRow[$key . 'Html' ]) ? (string)$coverRow[$key
                . 'Html' ] : $cover_h($value); if (!empty($column['status'])) {
                $colour=(string)($coverRow['statusColour'] ?? '' ); return '<td align="center" style="background-color:'
                . $cover_h($colour)
                . '; color:#ffffff; font-size:8pt; line-height:1.05; padding:2px 4px; vertical-align:middle; text-align:center; border-bottom:1px solid #ffffff; border-right:1px solid #ffffff; page-break-inside:avoid;"><a class="coverLink" style="text-decoration:none;color:#ffffff" href="'
                . $cover_h($coverRow['reportUrl'] ?? '' )
                . '" alt="View full report online" title="View full report online" target="_BLANK">' . $valueHtml
                . '</a></td>' ; } $align=!empty($column['align']) ? ' align="' . $cover_h($column['align']) . '"' : '' ;
                $title=$key==='description' ? ' title="' . $cover_h($coverRow['description'] ?? '' ) . '"' : '' ;
                $textAlign=$column['align'] ?? 'left' ; if (!empty($column['link'])) { return '<td' . $align . $title
                . ' style="font-size:8pt; line-height:1.05; padding:2px 4px; vertical-align:middle; text-align:' .
                $cover_h($textAlign)
                . '; border-bottom:1px solid #ffffff; border-right:1px solid #ffffff; page-break-inside:avoid;"><a class="btn-info coverLink" href="'
                . $cover_h($coverRow['reportUrl'] ?? '' )
                . '" alt="View full report online" title="View full report online">&nbsp;&nbsp;' . $valueHtml
                . '&nbsp;&nbsp;</a></td>' ; } return '<td' . $align . $title
                . ' style="font-size:8pt; line-height:1.05; padding:2px 4px; vertical-align:middle; text-align:' .
                $cover_h($textAlign)
                . '; border-bottom:1px solid #ffffff; border-right:1px solid #ffffff; page-break-inside:avoid;">' .
                $valueHtml . '</td>' ; }; $cover_table=static function (array $columnKeys, array $rows=null, array
                $attrs=[]) use (&$coverRows, &$coverColumnDefinitions, $cover_cell, $cover_h): string { $columns=[];
                foreach ($columnKeys as $key) { $key=(string)$key; if (isset($coverColumnDefinitions[$key])) {
                $columns[$key]=$coverColumnDefinitions[$key] + ['key'=> $key];
                }
                }
                if (empty($columns)) {
                return '';
                }

                $id = isset($attrs['id']) ? (string)$attrs['id'] : 'coverDetails';
                $class = isset($attrs['class']) ? (string)$attrs['class'] : 'table-sm coverDetails';
                $html = '<table id="' . $cover_h($id) . '" class="' . $cover_h($class) . ' clientOps" width="100%"
                    autosize="1" cellspacing="0" cellpadding="0"
                    style="width:100%; border-collapse:collapse; border-spacing:0; page-break-inside:auto;">';
                    $html .= '<colgroup>';
                        foreach ($columns as $column) {
                        $width = !empty($column['width']) ? ' width="' . $cover_h($column['width']) . '"' : '';
                        $html .= '<col' . $width . '>' ; } $html
                            .='</colgroup><thead style="display:table-header-group;"><tr><th colspan="' .
                            count($columns)
                            . '" style="font-size:8pt; line-height:1.05; padding:2px 4px; vertical-align:middle; text-align:left; color:#ffffff; font-weight:normal; border-bottom:1px solid #ffffff;">Click a Result status to see the full report.</th></tr><tr>'
                            ; foreach ( $columns as $column ) { $width=!empty($column['width']) ? ' width="' .
                            $cover_h($column['width']) . '"' : '' ; $html .='<th' . $width
                            . ' style="font-size:8pt; line-height:1.05; padding:2px 4px; vertical-align:middle; border-right:1px solid #ffffff; border-bottom:1px solid #ffffff;">'
                            . $cover_h($column['label'] ?? $column['key']) . '</th>' ; } $html .='</tr></thead><tbody>'
                            ; $rowIndex=0; foreach (($rows ?? $coverRows) as $coverRow) { $rowBg=($rowIndex % 2)
                            ? '#cccccc' : '#ffffff' ; $html .='<tr style="background-color:' . $rowBg
                            . '; page-break-inside:avoid; page-break-after:auto;">' ; foreach ( $columns as $column ) {
                            $html .=$cover_cell($coverRow, (string)$column['key'], $column); } $html .='</tr>' ;
                            $rowIndex++; } $html .='</tbody></table>' ; return $html; };
                            $coverDefaultColumns=[ 'repnumber' , 'description' , 'location' , 'plantnumber'
                            , 'serialnumber' , 'swl' , 'lastInspection' , 'nextInspection' , 'status' ];
                            $coverTable=$cover_table($coverDefaultColumns);
                            $requestedCoverTemplate=enrep_request_string('cover_template', 'default' , 80);
                            $coverParts=require $cover_template_path($cover_template($requestedCoverTemplate)); if
                            (!is_array($coverParts)) { enrep_fail(500, 'Invalid cover template' ); }
                            $postData=(string)($coverParts['postData'] ?? '' ); $pdf=(string)($coverParts['body'] ?? ''
                            ); $orientation=(string)($coverParts['orientation'] ?? 'L' );
                            $default_header=(string)($coverParts['default_header'] ?? '' );
                            $default_footer=(string)($coverParts['default_footer'] ?? '' );
                            $generic=(string)($coverParts['generic'] ?? 'yes' ); $cover=(string)($coverParts['cover']
                            ?? 'yes' ); if (empty($_REQUEST['repnumber'])) {
                            $_REQUEST['repnumber']=(string)$firstRepnumber; } if (empty($_REQUEST['form'])) {
                            $_REQUEST['form']=(string)$firstForm; } if (!isset($cx) || !is_array($cx)) { $cx=[]; } if
                            (empty($cx['itemnumber'])) { $cx['itemnumber']=$firstItemnumber; } if ($mode==="split" ) {
                            if ($requestedCoverFile !=='' ) { $coverFile=$cover_file($requestedCoverFile); } else {
                            $safeName=isset($name) ? preg_replace('/[^A-Za-z0-9_-]/', '' , (string)$name) : 'cover' ; if
                            ($safeName==='' ) { $safeName='cover' ; } $coverFile=$cover_file('report_cover_' . $safeName
                            . '.pdf' ); } $_REQUEST['cover_file']=$coverFile; $filestore='../../../' . TENANT_URL
                            . '/output/reports/' . $clientnumber . '/' . $coverFile;
                            include('../../includes/engines/ext.pdf.engine'); } else { $coverFile=$requestedCoverFile
                            !=='' ? $cover_file($requestedCoverFile) : 'report_cover.pdf' ;
                            $_REQUEST['cover_file']=$coverFile; $filestore='../../../' . TENANT_URL . '/output/reports/'
                            . $clientnumber . '/' . $coverFile; include('../../includes/engines/ext.pdf.engine'); echo
                            $postData; exit(); }
