<?php
require_once __DIR__ . '/../security.php';

$tenant = enrep_tenant_segment();
if ($tenant !== '' && 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();

require_once('../../includes/master/form_functions.php');
require_once __DIR__ . '/../delivery/exclusions.php';

$clientnumber = enrep_request_int('clientnumber');
$site = enrep_request_int('site');
$mode = enrep_request_enum('mode', ['split', ''], '');
if ($clientnumber < 1) {
    enrep_fail(400, 'Invalid client');
}

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

function gen_shed_address($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);
}

function gen_shed_last_report_badge(array $report): string
{
    if (empty($report)) {
        return '<span class="schedule-badge schedule-badge-missing">P2UD</span>';
    }

    $rd = enrepReportDataFromRow($report);
    $result = strtoupper(trim((string)($report['result'] ?? '')));
    $reptype = (string)($report['reptype'] ?? '');

    $class = 'schedule-badge-missing';
    $tag = 'P2UD';
    $detail = 'No report or report is prior to update';

    if ($result === 'PASS') {
        $class = 'schedule-badge-pass';
        $tag = 'PASS';
        $detail = 'The item passed examination';
    } elseif ($result === 'DEFECTS') {
        $class = 'schedule-badge-defects';
        $tag = 'DEFECTS';
        $detail = (string)($rd['bdefect'] ?? '');
    } elseif ($result === 'URGENT') {
        $class = 'schedule-badge-urgent';
        $tag = 'URGENT';
        $adefect = explode('|', (string)($rd['adefect'] ?? ''));
        $detail = (string)($adefect[0] ?? '');
    } elseif ($result === 'OBS') {
        $class = 'schedule-badge-obs';
        $tag = 'OBS';
        $detail = (string)($rd['obs'] ?? '');
    }

    if ($reptype === '518') {
        $class = 'schedule-badge-pna';
        $tag = 'NIR';
        $detail = (string)($rd['pnareason'] ?? '');
    } elseif ($reptype === '503') {
        $class = 'schedule-badge-pna';
        $tag = 'PNA';
        $detail = (string)($rd['pnareason'] ?? '');
    }

    return '<span class="schedule-badge ' . $class . '" title="' . gen_shed_h(strip_tags($detail)) . '">' . gen_shed_h($tag) . '</span>';
}

function gen_shed_template_file(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';
}

function gen_shed_template_path(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;
}

function gen_shed_site_name(int $site): string
{
    if ($site < 1 || !isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
        return '';
    }

    try {
        $stmt = $GLOBALS['con']->prepare("SELECT `locname` FROM `locations` WHERE `locnumber`=? LIMIT 1");
        if (!$stmt) {
            return '';
        }
        $stmt->bind_param('i', $site);
        $stmt->execute();
        $stmt->bind_result($name);
        $siteName = $stmt->fetch() ? trim((string)$name) : '';
        $stmt->close();

        return $siteName;
    } catch (Throwable $e) {
        return '';
    }
}

$shedPrefs = is_array($GLOBALS['assetPrefs'] ?? null) ? $GLOBALS['assetPrefs'] : [];
try {
    $stmt = $GLOBALS['con']->prepare("SELECT `asset_table_prefs` FROM `system` WHERE `id`='1' LIMIT 1");
    if ($stmt) {
        $stmt->execute();
        $stmt->bind_result($shedPrefsJson);
        if ($stmt->fetch() && trim((string)$shedPrefsJson) !== '') {
            $decodedPrefs = json_decode((string)$shedPrefsJson, true);
            if (is_array($decodedPrefs)) {
                foreach ($decodedPrefs as $prefKey => $prefValue) {
                    if (is_array($prefValue)) {
                        $shedPrefs[$prefKey] = array_merge($shedPrefs[$prefKey] ?? [], $prefValue);
                    }
                }
            }
        }
        $stmt->close();
    }
} catch (Throwable $e) {
    // Keep fallback labels if the settings lookup is unavailable.
}

$shed_label = static function (string $key, string $fallback) use (&$shedPrefs): string {
    $label = $shedPrefs[$key]['label'] ?? '';
    if (is_string($label) && trim($label) !== '') {
        return trim($label);
    }

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

$scheduleLabels = [
    'itemnumber' => 'Item No',
    'description' => $shed_label('description', 'Description'),
    'plantnumber' => $shed_label('plantnumber', 'Plant No'),
    'serialnumber' => $shed_label('serialnumber', 'Serial No'),
    'location' => $site > 0 ? $shed_label('subloc', 'Sub-location') : $shed_label('locname', 'Location'),
    'lastInspection' => 'Last Inspection',
    'nextInspection' => $shed_label('duedate', 'Next Inspection'),
];

$ret = '';
$coverRows = [];
$siteFilter = '';
if ($site > 0) {
    $siteFilter = " AND `locnumber`=?";
}

$stmt = $GLOBALS['con']->prepare("SELECT `itemnumber`,`locnumber`,`code`,`desc`,`plantnumber`,`serialnumber`,`subloc`,`currdate`,`duedate` FROM `itemdetails` WHERE `clientnumber`=? AND `statuslive`='1'{$siteFilter} ORDER BY abs(duedate) ASC") or die(mysqli_error($GLOBALS['con']));
if ($site > 0) {
    $stmt->bind_param('ii', $clientnumber, $site);
} else {
    $stmt->bind_param('i', $clientnumber);
}
$stmt->execute();
$ic = $stmt->get_result();
$stmt->close();

$rowIndex = 0;
while ($id = mysqli_fetch_array($ic)) {
    if (delivery_item_code_excluded($id['code'] ?? '')) {
        continue;
    }

    $stmt2 = $GLOBALS['con']->prepare("SELECT `repnumber`,`insdate`,`result`,`reptype`,`reportdata` FROM `reportitems` WHERE `itemnumber`=? ORDER BY abs(repitem) DESC LIMIT 1") or die(mysqli_error($GLOBALS['con']));
    $itemnumber = (int)$id['itemnumber'];
    $stmt2->bind_param('i', $itemnumber);
    $stmt2->execute();
    $get = $stmt2->get_result();
    $stmt2->close();
    $rget = mysqli_fetch_array($get);
    $insDate = !empty($rget['insdate']) ? date('d-m-Y', (int)$rget['insdate']) : '';
    $dueDate = !empty($id['duedate']) ? date('d-m-Y', (int)$id['duedate']) : '';
    $lastReport = is_array($rget) ? gen_shed_last_report_badge($rget) : gen_shed_last_report_badge([]);
    $locationDisplay = $site > 0 ? (string)($id['subloc'] ?? '') : (string)getItemLocation($itemnumber, 'name');
    $cellStyle = ' style="background-color:' . (($rowIndex % 2 === 0) ? '#f2f2f2' : '#ffffff') . ';"';
    $rowIndex++;

    $coverRows[] = [
        'itemnumber' => $itemnumber,
        'description' => (string)($id['desc'] ?? ''),
        'plantnumber' => (string)($id['plantnumber'] ?? ''),
        'serialnumber' => (string)($id['serialnumber'] ?? ''),
        'location' => $locationDisplay,
        'locationDisplay' => $locationDisplay,
        'lastInspection' => $insDate,
        'nextInspection' => $dueDate,
        'duedate' => $dueDate,
        'lastReport' => $lastReport,
        'status' => $lastReport,
    ];

    $ret .= '
<tr>
<td align="center"' . $cellStyle . '>' . gen_shed_h($itemnumber) . '</td>
<td' . $cellStyle . '>' . gen_shed_h($id['desc']) . '</td>
<td' . $cellStyle . '>' . gen_shed_h($id['plantnumber']) . '</td>
<td' . $cellStyle . '>' . gen_shed_h($id['serialnumber']) . '</td>
<td' . $cellStyle . '>' . gen_shed_h($locationDisplay) . '</td>
<td' . $cellStyle . '>' . gen_shed_h($insDate) . '</td>
<td' . $cellStyle . '>' . gen_shed_h($dueDate) . '</td>
</tr>';
}

$cover_h = static function ($value): string {
    return gen_shed_h($value);
};
$cover_address = static function ($value): string {
    return gen_shed_address($value);
};
$coverTitleHtml = '';
$coverTableRows = $ret;
$coverTableLabels = $scheduleLabels;
$coverColumnDefinitions = [
    'itemnumber' => ['label' => $scheduleLabels['itemnumber'], 'width' => '8%', 'align' => 'center'],
    'description' => ['label' => $scheduleLabels['description'], 'width' => '28%'],
    'plantnumber' => ['label' => $scheduleLabels['plantnumber'], 'width' => '12%'],
    'serialnumber' => ['label' => $scheduleLabels['serialnumber'], 'width' => '12%'],
    'location' => ['label' => $scheduleLabels['location'], 'width' => '18%'],
    'lastInspection' => ['label' => $scheduleLabels['lastInspection'], 'width' => '11%', 'align' => 'center'],
    'nextInspection' => ['label' => $scheduleLabels['nextInspection'], 'width' => '11%', 'align' => 'center'],
    'duedate' => ['label' => $scheduleLabels['nextInspection'], 'width' => '11%', 'align' => 'center'],
    'lastReport' => ['label' => 'Last Report', 'width' => '9%', 'align' => 'center', 'html' => true],
    'status' => ['label' => 'Last Report', 'width' => '9%', 'align' => 'center', 'html' => true],
];
$cover_cell = static function (array $coverRow, string $key, array $column = []) use ($cover_h): string {
    $value = $coverRow[$key] ?? '';
    if ($key === 'location') {
        $value = $coverRow['locationDisplay'] ?? $value;
    }

    $align = !empty($column['align']) ? ' align="' . $cover_h($column['align']) . '"' : '';
    $textAlign = $column['align'] ?? 'left';
    $valueHtml = !empty($column['html']) ? (string)$value : $cover_h($value);

    return '<td' . $align . ' 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) . '" 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>';
    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) ? '#ffffff' : '#f2f2f2';
        $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 = ['itemnumber', 'description', 'plantnumber', 'serialnumber', 'location', 'lastInspection', 'nextInspection'];
$coverTable = $cover_table($coverDefaultColumns);
$requestedCoverTemplate = enrep_request_string('cover_template', 'default', 80);
$coverParts = require gen_shed_template_path(gen_shed_template_file($requestedCoverTemplate));
if (!is_array($coverParts)) {
    enrep_fail(500, 'Invalid cover template');
}

$postData = '
<style>
#scheduleDetails {
    font-family: serif;
    font-size: 10pt;
    line-height: 1.25;
    table-layout: fixed;
}
#scheduleDetails td,
#scheduleDetails th {
    font-size: 10pt !important;
    line-height: 1.25;
    padding: 4px 3px;
    vertical-align: top;
    white-space: normal;
    word-wrap: break-word;
}
#scheduleDetails th {
    font-size: 9pt !important;
}
#scheduleDetails .schedule-column-head th {
    background-color: #2a3f54 !important;
    color: #ffffff !important;
    font-weight: bold;
}
.schedule-badge {
    display: block;
    border-radius: 10rem;
    color: #ffffff;
    font-size: 8pt;
    font-weight: bold;
    line-height: 1.1;
    padding: 3px 5px;
    text-align: center;
    white-space: nowrap;
}
.schedule-badge-pass { background-color: #007e33; }
.schedule-badge-defects { background-color: #f80; }
.schedule-badge-urgent { background-color: #c00; }
.schedule-badge-obs { background-color: #37474F; }
.schedule-badge-pna { background-color: #4B515D; }
.schedule-badge-missing { background-color: #9211E8; }
#scheduleDetails .schedule-title-cell,
#scheduleDetails #repDetails td {
    background-color: #ffffff !important;
}
</style>
';
$scheduleTitle = 'Schedule - ' . gen_shed_h(getClientName($clientnumber));
$addressHtml = gen_shed_address(getClientAddress($clientnumber));
if ($site > 0) {
    $siteName = gen_shed_site_name($site);
    $siteAddress = trim((string)getFullLocation($site));
    if ($siteName !== '') {
        $scheduleTitle .= ' - ' . gen_shed_h($siteName);
    }
    if ($siteAddress !== '') {
        $addressHtml = gen_shed_address($siteAddress);
    }
}

$pdf = '<table id="scheduleDetails" class="table-sm" width="100%">
<colgroup>
<col width="8%"><col width="28%"><col width="12%"><col width="12%"><col width="18%"><col width="11%"><col width="11%">
</colgroup>
<thead>
<tr class="schedule-title-row"><td colspan="7" class="schedule-title-cell" style="background-color:#ffffff!important;">
<table id="repDetails" class="table-sm" width="100%">
<tbody>
<tr valign="top">
';
$pdf .= '<td width="80%" valign="top" style="background-color:#ffffff!important;"><h3>' . $scheduleTitle . '</h3></td>
<td width="20%" align="right" valign="top" style="background-color:#ffffff!important; font-family: serif; font-size: 10pt; color: #000000; font-weight: bold;">' . $addressHtml . '</td>
';
$pdf .= '</tr>
</tbody>
</table>
</td></tr>
<tr class="schedule-column-head" style="background-color:#2a3f54!important; color:#ffffff!important;"><th style="background-color:#2a3f54!important; color:#ffffff!important;">' . gen_shed_h($scheduleLabels['itemnumber']) . '</th><th style="background-color:#2a3f54!important; color:#ffffff!important;">' . gen_shed_h($scheduleLabels['description']) . '</th><th style="background-color:#2a3f54!important; color:#ffffff!important;">' . gen_shed_h($scheduleLabels['plantnumber']) . '</th><th style="background-color:#2a3f54!important; color:#ffffff!important;">' . gen_shed_h($scheduleLabels['serialnumber']) . '</th><th style="background-color:#2a3f54!important; color:#ffffff!important;">' . gen_shed_h($scheduleLabels['location']) . '</th><th style="background-color:#2a3f54!important; color:#ffffff!important;">' . gen_shed_h($scheduleLabels['lastInspection']) . '</th><th style="background-color:#2a3f54!important; color:#ffffff!important;">' . gen_shed_h($scheduleLabels['nextInspection']) . '</th></tr>
</thead>
<tbody>
' . $ret . '
</tbody>
</table>';
$orientation = "L";
$default_header = (string)($coverParts['default_header'] ?? '');
$default_footer = (string)($coverParts['default_footer'] ?? '');
$generic = (string)($coverParts['generic'] ?? 'yes');
$cover = (string)($coverParts['cover'] ?? 'yes');
$scheduleFile = $clientnumber . '_schedule.pdf';
$_REQUEST['cover_file'] = $scheduleFile;
$filestore = '../../..' . TENANT_URL . '/output/reports/' . $clientnumber . '/' . $scheduleFile;

include('../../includes/engines/ext.pdf.engine');

if ($mode !== 'split') {
    echo $postData;
    exit();
}
