<?php
if (file_exists('../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}
require_once('../asset/asset_functions.php');
require_once('../inspection_reports/inspection_reports_functions.php');

$context = enrep_inspection_report_context($_REQUEST);
$startTs = $context['startTs'];
$endTs = $context['endTs'];
$mode = $context['mode'];
$fcn = (string)($_REQUEST['FCN'] ?? 'clients');

if ($startTs === null || $endTs === null || $startTs > $endTs) {
    echo '<div class="col-12 alert alert-warning text-center">Please enter a valid date range</div>';
    exit;
}

$tenantParam = defined('TENANT_URL') ? TENANT_URL : (string)($_REQUEST['tenant'] ?? '');
$exportBase = [
    'tenant' => $tenantParam,
    'start' => $context['start'],
    'end' => $context['end'],
    'mode' => $mode,
    'view' => $fcn === 'items' ? 'items' : 'clients',
];
if ($fcn === 'items') {
    $exportBase['clientnumber'] = $context['clientnumber'];
}

$csvUrl = ROOT_URL . '/includes/inspection_reports/inspection_reports_export.php?' . http_build_query(array_merge($exportBase, ['inspection_export' => 'csv']));
$pdfUrl = ROOT_URL . '/includes/inspection_reports/inspection_reports_export.php?' . http_build_query(array_merge($exportBase, ['inspection_export' => 'pdf']));
$printTitle = ($mode === 'done') ? 'Inspections Carried Out' : 'Inspections To Be Done';

if ($fcn === 'items') {
    $clientRows = [];
    $stmt = $GLOBALS['con']->prepare("SELECT `clientname` FROM `clientdetails` WHERE `clientnumber` = ?");
    $stmt->bind_param("i", $context['clientnumber']);
    $stmt->execute();
    $clientResult = $stmt->get_result();
    $stmt->close();
    $clientName = mysqli_fetch_array($clientResult);
    $rows = enrep_inspection_report_item_rows($context['clientnumber'], $startTs, $endTs, $mode);
    $printTitle .= ' - ' . ($clientName['clientname'] ?? '');
    $tableHtml = enrep_inspection_report_render_item_table($rows);
    $visibleCount = count($rows);
} else {
    $rows = enrep_inspection_report_client_rows($startTs, $endTs, $mode);
    $tableHtml = enrep_inspection_report_render_client_table($rows, $mode, true);
    $visibleCount = count($rows);
}
?>
<div class="container-fluid px-0">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <h3 class="mb-0"><?= enrep_inspection_report_h($printTitle) ?></h3>
            <small class="text-muted">Showing <?= (int)$visibleCount ?> rows for <?= enrep_inspection_report_h($context['start']) ?> - <?= enrep_inspection_report_h($context['end']) ?></small>
        </div>
        <div class="btn-group noprint no-print">
            <a class="btn btn-secondary" href="<?= enrep_inspection_report_h($csvUrl) ?>" download><i class="fad fa-file-csv me-1"></i>CSV</a>
            <a class="btn btn-secondary" href="<?= enrep_inspection_report_h($pdfUrl) ?>"><i class="fad fa-file-pdf me-1"></i>PDF</a>
            <button type="button" class="btn btn-secondary" onclick="printInspectionReportView()"><i class="fad fa-print me-1"></i>Print</button>
        </div>
    </div>

    <div id="inspectionReportPrintArea">
        <?= $tableHtml ?>
    </div>
</div>

<script>
function printInspectionReportView() {
    printContainer('inspectionReportPrintArea', {
        orientation: "landscape",
        header: '<p><?= addslashes($printTitle) ?> : <?= addslashes($context['start']) ?> - <?= addslashes($context['end']) ?></p>',
        footer: '<p>Generated by EnRep Reporting System: <?= date('d-m-Y') ?></p>',
        logoUrl: 'images/company/logo.jpg',
        styles: [ROOT_URL + '/src/css/print.css'],
    });
}
</script>
