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

if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    $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();

$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) : '';
require_once('../../includes/master/form_functions.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;
};

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

$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 = '';
$clientnumber = $requestClientnumber;

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;
    }

    $clientnumber = (int)$rd['clientnumber'];
    $description = $id['desc'] ?? '';
    $plantnumber = $id['plantnumber'] ?? '';
    $serialnumber = $id['serialnumber'] ?? '';
    $swl = $id['swl'] ?? '';

    $col = '';
    $tag = 'P2UD';
    if ($rd['result'] === "DEFECTS") {
        $col = "#F4AA09";
        $tag = "DEFECTS";
    }
    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";
    }

    $ret .= '
<tr>
<td align="center"><a class="btn-info" href="https://[REPORT_PATH]/preview.php?repnumber=' . $cover_h($repnumber) . '" alt="View full report online" title="View full report online">&nbsp;&nbsp;' . $cover_h($itemnumber) . '&nbsp;&nbsp;</a></td>
<td>' . $cover_h($repnumber) . '</td>
<td>' . $cover_h($description) . '</td>
<td>' . $cover_h(getItemLocation($itemnumber, 'name')) . '</td>
<td>' . $cover_h($plantnumber) . '</td>
<td>' . $cover_h($serialnumber) . '</td>
<td>' . $cover_h($swl) . '</td>
<td>' . $cover_h(!empty($rd['insdate']) ? date('d-m-Y', (int)$rd['insdate']) : '') . '</td>
<td>' . $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 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;
}

$postData = '
<style>
#coverDetails {
    font-family: serif;
    font-size: 10pt;
    line-height: 1.25;
    table-layout: fixed;
}
#coverDetails td,
#coverDetails th {
    font-size: 10pt !important;
    line-height: 1.25;
    padding: 4px 3px;
    vertical-align: top;
    white-space: normal;
    word-wrap: break-word;
}
#coverDetails th {
    font-size: 9pt !important;
}
</style>
';

$pdf = '<table id="coverDetails" class="table-sm" width="100%">
<colgroup>
<col width="7%"><col width="8%"><col width="18%"><col width="14%"><col width="10%">
<col width="10%"><col width="7%"><col width="9%"><col width="9%"><col width="8%">
</colgroup>
<thead>
<tr><td colspan="10">
<table id="" class="table-sm" width="100%">
<tbody>
<tr valign="top">';
if ($site > 0) {
    $pdf .= '<td width="60%" valign="top"><h3>Report Summary - ' . $cover_h(getClientName($clientnumber)) . $coverTitleHtml . '</h3></td>
<td width="20%" align="right" valign="top" style="font-family: serif; font-size: 10pt; color: #000000; font-weight: bold;">' . $cover_address(getClientAddress($clientnumber)) . '</td>
<td width="20%" align="right" valign="top" style="font-family: serif; font-size: 10pt; color: #000000; font-weight: bold;">' . $cover_address(getFullLocation($site)) . '</td>
';
} else {
    $pdf .= '
<td width="80%" valign="top"><h3>Report Summary - ' . $cover_h(getClientName($clientnumber)) . $coverTitleHtml . '</h3></td>
<td width="20%" align="right" valign="top" style="font-family: serif; font-size: 10pt; color: #000000; font-weight: bold;">' . $cover_address(getClientAddress($clientnumber)) . '</td>
';
}
$pdf .= '
</tr>
</tbody>
</table>
</td></tr>

<tr><th>Item No</th><th>Report No</th><th>Description</th><th>Location</th><th>Plant No</th><th>Serial No</th><th>SWL</th><th>Last Inspection</th><th>Next Inspection</th><th>Status</th></tr></thead>
<tbody>
' . $ret . '
</tbody>
</table>';
$orientation = "L";
$default_header = "";
$default_footer = "";
$generic = "yes";
$cover = "yes";

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