<?php
declare(strict_types=1);

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

$conn = iscms_init();
$pageTitle = 'Standard categories';
$activeNav = 'standard_categories';

$sql = "SELECT c.id, c.category, c.code, c.is_active,
               p.category AS parent_category
        FROM standard_categories c
        LEFT JOIN standard_categories p ON c.parent_id = p.id
        ORDER BY c.category 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>Standard categories</h1>
        <p>Classification tree for national, regional, and international standards.</p>
    </div>

    <div class="section-card">
        <div class="section-header">
            <h2><i class="ri-folder-3-line"></i> Categories</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>Category</th>
                        <th>Code</th>
                        <th>Parent</th>
                        <th>Active</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($rows)): ?>
                    <tr class="empty-row"><td colspan="4"><i class="ri-inbox-line me-2"></i>No categories</td></tr>
                    <?php else: ?>
                        <?php foreach ($rows as $r): ?>
                        <tr>
                            <td style="font-weight:600; color:var(--ssbs-blue)"><?= iscms_h($r['category']) ?></td>
                            <td class="iscms-mono"><?= iscms_val($r['code'] ?? null) ?></td>
                            <td><small><?= iscms_val($r['parent_category'] ?? null) ?></small></td>
                            <td><?= !empty($r['is_active']) ? '<span class="badge bg-success-subtle text-success" style="font-size:.68rem">Yes</span>' : '<span class="badge bg-secondary-subtle text-secondary" style="font-size:.68rem">No</span>' ?></td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
    </div>
<?php
iscms_render_footer();
