<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/iscms_layout.php';

$conn = iscms_init();
$pageTitle = 'Standards library';
$activeNav = 'standards';

$sql = "SELECT s.id, s.standard_number, s.title, s.standard_type, s.status, s.effective_date,
               sc.category AS category_name
        FROM standards s
        LEFT JOIN standard_categories sc ON s.category_id = sc.id
        ORDER BY s.standard_number ASC
        LIMIT 500";
$result = $conn->query($sql);
$rows = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
$dbError = $result ? null : $conn->error;

iscms_render_head($pageTitle);
iscms_render_sidebar($activeNav);
iscms_render_topbar($pageTitle);
?>
    <div class="page-header">
        <h1>Standards library</h1>
        <p>Published standards referenced in conformity assessment and product mapping.</p>
    </div>

    <div class="section-card">
        <div class="section-header">
            <h2><i class="ri-book-2-line"></i> Standards</h2>
            <span class="text-muted" style="font-size:.75rem"><?= count($rows) ?> shown</span>
        </div>
        <div class="table-responsive">
            <?php if ($dbError): ?>
                <div class="alert alert-danger m-3" style="font-size:.85rem">Unable to load data: <?= iscms_h($dbError) ?></div>
            <?php else: ?>
            <table class="ssbs-table">
                <thead>
                    <tr>
                        <th>Number</th>
                        <th>Title</th>
                        <th>Category</th>
                        <th>Type</th>
                        <th>Status</th>
                        <th>Effective</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($rows)): ?>
                    <tr class="empty-row"><td colspan="6"><i class="ri-inbox-line me-2"></i>No standards</td></tr>
                    <?php else: ?>
                        <?php foreach ($rows as $r): ?>
                        <tr>
                            <td class="iscms-mono" style="font-weight:600; color:var(--ssbs-blue)"><?= iscms_h($r['standard_number']) ?></td>
                            <td><small><?= iscms_h($r['title']) ?></small></td>
                            <td><small><?= iscms_val($r['category_name'] ?? null) ?></small></td>
                            <td><small><?= iscms_h(str_replace('_', ' ', (string) ($r['standard_type'] ?? ''))) ?></small></td>
                            <td><?= iscms_status_badge((string) ($r['status'] ?? '')) ?></td>
                            <td><small class="text-muted"><?= !empty($r['effective_date']) ? iscms_h((string) $r['effective_date']) : '<span class="text-muted">-</span>' ?></small></td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
    </div>
<?php
iscms_render_footer();
