<?php
$pnaReportMode = trim((string)($_REQUEST['mode'] ?? 'data'));

if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    require_once __DIR__ . '/../../functions/security.php';
    $tenant = enrep_tenant_segment($_REQUEST['tenant'] ?? $_GET['tenant'] ?? null);
    if ($tenant !== '' && is_file(__DIR__ . '/../../../' . $tenant . '/config.php')) {
        require_once __DIR__ . '/../../../' . $tenant . '/config.php';
    }
}

$con = $GLOBALS['con'] ?? null;
if (!$con instanceof mysqli) {
    http_response_code(500);
    echo $pnaReportMode === 'data'
        ? json_encode(['success' => false, 'message' => 'Database connection not available', 'html' => ''])
        : 'Database connection not available';
    exit;
}

$con->set_charset('utf8mb4');
if (function_exists('enrep_require_user')) {
    enrep_require_user();
}

function pnaReportE($value): string
{
    return htmlspecialchars(trim((string)($value ?? '')), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function pnaReportDateToTs($value, bool $endOfDay = false): int
{
    $value = trim((string)$value);
    if ($value === '') {
        return 0;
    }

    $date = DateTime::createFromFormat('d-m-Y', $value);
    if (!$date) {
        return 0;
    }

    $date->setTime($endOfDay ? 23 : 0, $endOfDay ? 59 : 0, $endOfDay ? 59 : 0);
    return (int)$date->format('U');
}

function pnaReportFormatDate($value): string
{
    $value = (int)$value;
    return $value > 0 ? date('d-m-Y', $value) : '';
}

function pnaReportDefaultPrefs(): array
{
    return [
        'itemnumber' => ['label' => 'Item ID', 'visible' => true],
        'description' => ['label' => 'Description', 'visible' => true],
        'manufacturer' => ['label' => 'Manufacturer', 'visible' => true],
        'make_model' => ['label' => 'Make/Model', 'visible' => true],
        'condition' => ['label' => 'Condition', 'visible' => true],
        'plantnumber' => ['label' => 'Plant No.', 'visible' => true],
        'serialnumber' => ['label' => 'Serial', 'visible' => true],
        'locname' => ['label' => 'Location', 'visible' => true],
        'subloc' => ['label' => 'Sub-location', 'visible' => true],
        'postcode' => ['label' => 'Post Code', 'visible' => true],
        'lastReport' => ['label' => 'Result', 'visible' => true],
        'duedate' => ['label' => 'Due', 'visible' => true],
        'actions' => ['label' => 'Actions', 'visible' => true],
    ];
}

function pnaReportPrefs(mysqli $con): array
{
    $prefs = pnaReportDefaultPrefs();
    $stmt = $con->prepare("SELECT `asset_table_prefs` FROM `system` WHERE `id`='1' LIMIT 1");
    if ($stmt) {
        $stmt->execute();
        $stmt->bind_result($json);
        if ($stmt->fetch() && trim((string)$json) !== '') {
            $decoded = json_decode((string)$json, true);
            if (is_array($decoded)) {
                foreach ($prefs as $key => $default) {
                    if (!isset($decoded[$key]) || !is_array($decoded[$key])) {
                        continue;
                    }
                    $prefs[$key]['label'] = trim((string)($decoded[$key]['label'] ?? '')) !== ''
                        ? (string)$decoded[$key]['label']
                        : $default['label'];
                    if (array_key_exists('visible', $decoded[$key])) {
                        $prefs[$key]['visible'] = (bool)$decoded[$key]['visible'];
                    } elseif (array_key_exists('enabled', $decoded[$key])) {
                        $prefs[$key]['visible'] = (bool)$decoded[$key]['enabled'];
                    }
                }
            }
        }
        $stmt->close();
    }

    return $prefs;
}

function pnaReportColumns(mysqli $con): array
{
    $prefs = pnaReportPrefs($con);
    $order = ['itemnumber', 'description', 'manufacturer', 'make_model', 'condition', 'plantnumber', 'serialnumber', 'locname', 'subloc', 'postcode', 'lastReport', 'duedate'];
    $columns = [];
    foreach ($order as $key) {
        if (!isset($prefs[$key]) || !($prefs[$key]['visible'] ?? true)) {
            continue;
        }
        $columns[$key] = (string)($prefs[$key]['label'] ?? $key);
    }
    return $columns;
}

function pnaReportConditionLabel($value): string
{
    $clean = strtoupper(trim((string)$value));
    $labels = [
        'A' => 'As New',
        'B' => 'In use. Used',
        'C' => 'In use. Tired',
        'D' => 'In storage. Ready to use',
        'E' => 'In storage. Attention Needed',
        'F' => 'Disregarded',
        'G' => 'Decommissioned',
    ];
    return $labels[$clean] ?? ($clean !== '' && $clean !== '0' ? $clean : '');
}

function pnaReportRows(mysqli $con, int $clientnumber, int $fromTs, int $toTs): array
{
    if ($fromTs < 1 || $toTs < 1 || $fromTs > $toTs) {
        return [];
    }

    $params = [$fromTs, $toTs];
    $types = 'ii';
    $clientSql = '';
    if ($clientnumber > 0) {
        $clientSql = ' AND c.`clientnumber` = ?';
        $params[] = $clientnumber;
        $types .= 'i';
    }

    $sql = "
        SELECT
            c.`clientnumber`,
            c.`clientname`,
            r.`repnumber`,
            r.`reptype`,
            r.`insdate`,
            r.`nextDate`,
            r.`result`,
            a.`itemnumber`,
            a.`desc` AS description,
            a.`manf`,
            a.`model`,
            a.`condition` AS asset_condition,
            a.`plantnumber`,
            a.`serialnumber`,
            a.`duedate`,
            l.`locname`,
            a.`subloc`,
            l.`postcode`
        FROM `reportitems` r
        INNER JOIN `clientdetails` c ON c.`clientnumber` = r.`clientnumber`
        LEFT JOIN `itemdetails` a ON a.`clientnumber` = r.`clientnumber` AND a.`itemnumber` = r.`itemnumber`
        LEFT JOIN `locations` l ON l.`clientnumber` = a.`clientnumber` AND l.`locnumber` = a.`locnumber`
        WHERE c.`statuslive` = 1
          AND (a.`statuslive` = 1 OR a.`itemnumber` IS NULL)
          AND r.`repnumber` BETWEEN ? AND ?
          AND UPPER(TRIM(COALESCE(r.`result`, ''))) = 'PNA'
          {$clientSql}
        ORDER BY c.`clientname` ASC, r.`repnumber` DESC, a.`itemnumber` ASC
    ";

    $stmt = $con->prepare($sql);
    if (!$stmt) {
        return [];
    }
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();

    $rows = [];
    while ($row = $result->fetch_assoc()) {
        $rows[] = [
            'clientnumber' => (int)($row['clientnumber'] ?? 0),
            'clientname' => (string)($row['clientname'] ?? ''),
            'repnumber' => (int)($row['repnumber'] ?? 0),
            'reptype' => (string)($row['reptype'] ?? ''),
            'created' => pnaReportFormatDate($row['repnumber'] ?? 0),
            'exam_date' => pnaReportFormatDate($row['insdate'] ?? 0),
            'itemnumber' => (int)($row['itemnumber'] ?? 0),
            'description' => (string)($row['description'] ?? ''),
            'manufacturer' => (string)($row['manf'] ?? ''),
            'make_model' => (string)($row['model'] ?? ''),
            'condition' => pnaReportConditionLabel($row['asset_condition'] ?? ''),
            'plantnumber' => (string)($row['plantnumber'] ?? ''),
            'serialnumber' => (string)($row['serialnumber'] ?? ''),
            'locname' => (string)($row['locname'] ?? ''),
            'subloc' => (string)($row['subloc'] ?? ''),
            'postcode' => (string)($row['postcode'] ?? ''),
            'lastReport' => (string)($row['result'] ?? 'PNA'),
            'duedate' => pnaReportFormatDate($row['duedate'] ?? 0),
        ];
    }
    $stmt->close();

    return $rows;
}

function pnaReportTableHtml(mysqli $con, array $rows, int $clientnumber, bool $forPrint = false): string
{
    $columns = pnaReportColumns($con);
    $groupByClient = $clientnumber < 1;
    $renderServerGroups = $groupByClient && $forPrint;
    $colspan = count($columns) + 3;
    $lastClientName = null;
    ob_start();
    ?>
    <table id="<?= $forPrint ? 'pnaReportPrintTable' : 'pnaReportTable' ?>" class="table table-sm table-striped table-bordered align-middle w-100" data-group-clients="<?= $groupByClient ? '1' : '0' ?>">
        <thead class="table-dark">
            <tr>
                <?php if ($groupByClient && !$renderServerGroups) { ?><th>Client</th><?php } ?>
                <th>Report No.</th>
                <th>Created</th>
                <th>Exam Date</th>
                <?php foreach ($columns as $label) { ?>
                    <th><?= pnaReportE($label) ?></th>
                <?php } ?>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($rows as $row) { ?>
                <?php if ($renderServerGroups && $lastClientName !== (string)$row['clientname']) {
                    $lastClientName = (string)$row['clientname'];
                ?>
                    <tr class="pna-client-group">
                        <td colspan="<?= (int)$colspan ?>"><?= pnaReportE($lastClientName) ?></td>
                    </tr>
                <?php } ?>
                <tr>
                    <?php if ($groupByClient && !$renderServerGroups) { ?><td><?= pnaReportE($row['clientname']) ?></td><?php } ?>
                    <td><?= pnaReportE($row['repnumber']) ?></td>
                    <td><?= pnaReportE($row['created']) ?></td>
                    <td><?= pnaReportE($row['exam_date']) ?></td>
                    <?php foreach ($columns as $key => $label) { ?>
                        <td><?= pnaReportE($row[$key] ?? '') ?></td>
                    <?php } ?>
                </tr>
            <?php } ?>
        </tbody>
    </table>
    <?php
    return (string)ob_get_clean();
}

if (defined('PNA_REPORT_INCLUDE_ONLY') && PNA_REPORT_INCLUDE_ONLY) {
    return;
}

$clientnumber = filter_var($_REQUEST['clientnumber'] ?? 0, FILTER_VALIDATE_INT);
$clientnumber = $clientnumber !== false ? (int)$clientnumber : 0;
$fromTs = pnaReportDateToTs($_REQUEST['from'] ?? '', false);
$toTs = pnaReportDateToTs($_REQUEST['to'] ?? '', true);
$rows = pnaReportRows($con, $clientnumber, $fromTs, $toTs);

if ($pnaReportMode === 'data') {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode([
        'success' => true,
        'count' => count($rows),
        'html' => pnaReportTableHtml($con, $rows, $clientnumber),
    ]);
    exit;
}

if ($pnaReportMode === 'csv') {
    $columns = pnaReportColumns($con);
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="pna-report-' . date('Ymd-His') . '.csv"');
    $out = fopen('php://output', 'w');
    $header = $clientnumber < 1 ? ['Client'] : [];
    $header = array_merge($header, ['Report No.', 'Created', 'Exam Date'], array_values($columns));
    fputcsv($out, $header);
    foreach ($rows as $row) {
        $line = $clientnumber < 1 ? [$row['clientname']] : [];
        $line = array_merge($line, [$row['repnumber'], $row['created'], $row['exam_date']]);
        foreach ($columns as $key => $label) {
            $line[] = $row[$key] ?? '';
        }
        fputcsv($out, $line);
    }
    fclose($out);
    exit;
}

$title = 'PNA Report';
$range = pnaReportE((string)($_REQUEST['from'] ?? '')) . ' to ' . pnaReportE((string)($_REQUEST['to'] ?? ''));
$html = '<h1 style="font-size:18px;">' . $title . '</h1><p>Created date range: ' . $range . '</p>';
$html .= pnaReportTableHtml($con, $rows, $clientnumber, true);

if ($pnaReportMode === 'print') {
    $html = '<style>.pna-client-group td{background:#263238!important;color:#fff!important;font-weight:bold;}</style>' . $html;
    echo '<div class="pna-report-print">' . $html . '</div>';
    exit;
}

if ($pnaReportMode === 'pdf') {
    require_once __DIR__ . '/../../packages/mpd/vendor/autoload.php';
    $mpdf = new \Mpdf\Mpdf(['orientation' => 'L', 'tempDir' => sys_get_temp_dir()]);
    $mpdf->WriteHTML('<style>body{font-family:sans-serif;font-size:9px;} table{border-collapse:collapse;width:100%;} th,td{border:1px solid #777;padding:4px;} th{background:#2f465c;color:#fff;}.pna-client-group td{background:#263238;color:#fff;font-weight:bold;}</style>' . $html);
    $mpdf->Output('pna-report-' . date('Ymd-His') . '.pdf', 'I');
    exit;
}

http_response_code(400);
echo 'Invalid mode';
