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

$tenant = enrep_tenant_segment($_REQUEST['tenant'] ?? (defined('TENANT_URL') ? TENANT_URL : ''));
if ($tenant !== '' && file_exists('../../../' . $tenant . '/config.php')) {
    require_once('../../../' . $tenant . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

require_once __DIR__ . '/../../functions/logging.php';
require_once __DIR__ . '/log_functions.php';

if (function_exists('enrep_require_admin')) {
    enrep_require_admin();
}

$logId = (int)($_REQUEST['id'] ?? 0);
if ($logId < 1) {
    echo '<div class="alert alert-warning">No log entry selected.</div>';
    exit;
}

$stmt = $GLOBALS['con']->prepare("SELECT * FROM `log` WHERE `id`=? LIMIT 1");
if (!$stmt) {
    echo '<div class="alert alert-danger">Unable to load log entry.</div>';
    exit;
}
$stmt->bind_param('i', $logId);
$stmt->execute();
$res = $stmt->get_result();
$row = $res ? $res->fetch_assoc() : null;
$stmt->close();

if (!$row) {
    echo '<div class="alert alert-warning">Log entry not found.</div>';
    exit;
}

$attachments = enrep_log_row_attachments($row);
if (empty($attachments)) {
    echo '<div class="alert alert-info">This log entry has no recorded attachments.</div>';
    exit;
}

function log_attachment_normalise($attachment): array
{
    if (is_array($attachment)) {
        $file = trim((string)($attachment['file'] ?? $attachment['filename'] ?? ''));
        $source = trim((string)($attachment['source'] ?? ''), '/');
        $path = trim((string)($attachment['path'] ?? trim($source . '/' . $file, '/')), '/');
        return [
            'file' => $file,
            'source' => $source,
            'path' => $path,
            'type' => strtolower(trim((string)($attachment['type'] ?? pathinfo($file, PATHINFO_EXTENSION)))),
            'label' => trim((string)($attachment['label'] ?? $file)),
            'reportnumber' => isset($attachment['reportnumber']) ? (int)$attachment['reportnumber'] : log_attachment_reportnumber($file),
            'itemnumber' => isset($attachment['itemnumber']) ? (int)$attachment['itemnumber'] : null,
            'contents' => is_array($attachment['contents'] ?? null) ? $attachment['contents'] : [],
        ];
    }

    $file = trim((string)$attachment);
    return [
        'file' => $file,
        'source' => '',
        'path' => $file,
        'type' => strtolower(pathinfo($file, PATHINFO_EXTENSION)),
        'label' => $file,
        'reportnumber' => log_attachment_reportnumber($file),
        'itemnumber' => null,
        'contents' => [],
    ];
}

function log_attachment_reportnumber(string $file): ?int
{
    $base = basename($file);
    if (preg_match('/(?:^|_)(\d+)\.pdf$/i', $base, $matches)) {
        return (int)$matches[1];
    }

    return null;
}

function log_attachment_url(string $tenant, array $attachment): string
{
    $path = trim((string)$attachment['path'], '/');
    if ($path === '') {
        $path = trim(trim((string)$attachment['source'], '/') . '/' . (string)$attachment['file'], '/');
    }

    return '/' . str_replace('%2F', '/', rawurlencode($path));
}

function log_attachment_file_path(string $tenant, array $attachment): string
{
    $path = trim((string)$attachment['path'], '/');
    if ($path === '') {
        $path = trim(trim((string)$attachment['source'], '/') . '/' . (string)$attachment['file'], '/');
    }

    return rtrim((string)($_SERVER['DOCUMENT_ROOT'] ?? ''), '/\\') . '/' . $path;
}

function log_attachment_report_details(?int $repnumber, ?int $itemnumber = null): ?array
{
    if (!$repnumber && !$itemnumber) {
        return null;
    }

    if ($repnumber) {
        $stmt = $GLOBALS['con']->prepare(
            "SELECT ri.repnumber, ri.itemnumber, id.`desc`, id.plantnumber, id.serialnumber
             FROM reportitems ri
             LEFT JOIN itemdetails id ON id.itemnumber = ri.itemnumber
             WHERE ri.repnumber=? LIMIT 1"
        );
    } else {
        $stmt = $GLOBALS['con']->prepare(
            "SELECT 0 AS repnumber, id.itemnumber, id.`desc`, id.plantnumber, id.serialnumber
             FROM itemdetails id
             WHERE id.itemnumber=? LIMIT 1"
        );
    }
    if (!$stmt) {
        return null;
    }

    $lookup = $repnumber ?: $itemnumber;
    $stmt->bind_param('i', $lookup);
    $stmt->execute();
    $res = $stmt->get_result();
    $details = $res ? $res->fetch_assoc() : null;
    $stmt->close();

    return $details ?: null;
}

function log_attachment_zip_index(string $path): array
{
    if (!class_exists('ZipArchive') || !is_file($path)) {
        return [];
    }

    $zip = new ZipArchive();
    if ($zip->open($path) !== true) {
        return [];
    }

    $files = [];
    for ($i = 0; $i < $zip->numFiles; $i++) {
        $stat = $zip->statIndex($i);
        if ($stat && !empty($stat['name'])) {
            $files[] = [
                'name' => (string)$stat['name'],
                'reportnumber' => log_attachment_reportnumber((string)$stat['name']),
            ];
        }
    }
    $zip->close();

    return $files;
}

function log_attachment_asset_label(string $key, string $fallback): string
{
    if (function_exists('asset_label')) {
        return asset_label($key, $fallback);
    }

    $stmt = $GLOBALS['con']->prepare("SELECT asset_table_prefs FROM system WHERE id=1 LIMIT 1");
    if (!$stmt) {
        return $fallback;
    }

    $stmt->execute();
    $stmt->bind_result($prefsJson);
    $label = $fallback;
    if ($stmt->fetch() && $prefsJson) {
        $prefs = json_decode((string)$prefsJson, true);
        if (is_array($prefs) && isset($prefs[$key]['label']) && trim((string)$prefs[$key]['label']) !== '') {
            $label = trim((string)$prefs[$key]['label']);
        }
    }
    $stmt->close();

    return $label;
}

$plantLabel = log_attachment_asset_label('plantnumber', 'Plant No.');
$serialLabel = log_attachment_asset_label('serialnumber', 'Serial');
?>

<div class="table-responsive">
    <table class="table table-striped table-sm align-middle">
        <thead class="table-dark">
            <tr>
                <th>Attachment</th>
                <th>Report / Asset</th>
                <th class="text-end">Open</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($attachments as $attachmentRaw) {
                $attachment = log_attachment_normalise($attachmentRaw);
                if ($attachment['file'] === '') {
                    continue;
                }
                $url = log_attachment_url($tenant, $attachment);
                $filePath = log_attachment_file_path($tenant, $attachment);
                $report = log_attachment_report_details($attachment['reportnumber'], $attachment['itemnumber']);
                $zipIndex = !empty($attachment['contents'])
                    ? array_map(function ($content) {
                        return is_array($content) ? [
                            'name' => (string)($content['file'] ?? ''),
                            'reportnumber' => isset($content['reportnumber']) ? (int)$content['reportnumber'] : (isset($content['repnumber']) ? (int)$content['repnumber'] : null),
                            'itemnumber' => isset($content['itemnumber']) ? (int)$content['itemnumber'] : null,
                        ] : [
                            'name' => (string)$content,
                            'reportnumber' => log_attachment_reportnumber((string)$content),
                            'itemnumber' => null,
                        ];
                    }, $attachment['contents'])
                    : (strtolower(pathinfo($attachment['file'], PATHINFO_EXTENSION)) === 'zip' ? log_attachment_zip_index($filePath) : []);
            ?>
            <tr>
                <td>
                    <strong><?= enrep_log_h($attachment['label']) ?></strong><br>

                    <?php if (!is_file($filePath)) { ?>
                    <div class="text-danger small">File not found at expected web path.</div>
                    <?php } ?>
                </td>
                <td>
                    <?php if ($report) { ?>
                    <div><strong>Report:</strong> <?= (int)$report['repnumber'] ?> / <strong>Item:</strong>
                        <?= (int)$report['itemnumber'] ?></div>
                    <div><?= enrep_log_h($report['desc'] ?? '') ?></div>
                    <small class="text-muted"><?= enrep_log_h($plantLabel) ?>:
                        <?= enrep_log_h($report['plantnumber'] ?? '') ?> | <?= enrep_log_h($serialLabel) ?>:
                        <?= enrep_log_h($report['serialnumber'] ?? '') ?></small>
                    <?php } elseif (!empty($zipIndex)) { ?>
                    <span class="badge bg-info text-light"><?= count($zipIndex) ?> file(s) in ZIP</span>
                    <?php } else { ?>
                    <span class="text-muted">No report metadata</span>
                    <?php } ?>
                </td>
                <td class="text-end">
                    <a class="btn btn-secondary btn-sm" target="_blank" href="<?= enrep_log_h($url) ?>"><i
                            class="fad fa-external-link"></i></a>
                </td>
            </tr>
            <?php if (!empty($zipIndex)) { ?>
            <tr>
                <td colspan="3">
                    <div class="fw-bold mb-2">ZIP contents</div>
                    <div class="table-responsive">
                        <table class="table table-bordered table-sm mb-0">
                            <thead>
                                <tr>
                                    <th>File</th>
                                    <th>Report / Asset</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($zipIndex as $zipFile) {
                                    $zipReport = log_attachment_report_details($zipFile['reportnumber'], $zipFile['itemnumber'] ?? null);
                                ?>
                                <tr>
                                    <td><?= enrep_log_h($zipFile['name']) ?></td>
                                    <td>
                                        <?php if ($zipReport) { ?>
                                        <div><strong>Report:</strong> <?= (int)$zipReport['repnumber'] ?> /
                                            <strong>Item:</strong> <?= (int)$zipReport['itemnumber'] ?>
                                        </div>
                                        <div><?= enrep_log_h($zipReport['desc'] ?? '') ?></div>
                                        <small class="text-muted"><?= enrep_log_h($plantLabel) ?>:
                                            <?= enrep_log_h($zipReport['plantnumber'] ?? '') ?> |
                                            <?= enrep_log_h($serialLabel) ?>:
                                            <?= enrep_log_h($zipReport['serialnumber'] ?? '') ?></small>
                                        <?php } else { ?>
                                        <span class="text-muted">No report metadata</span>
                                        <?php } ?>
                                    </td>
                                </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                    </div>
                </td>
            </tr>
            <?php } ?>
            <?php } ?>
        </tbody>
    </table>
</div>
