<?php
declare(strict_types=1);

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

$conn = iscms_init();
$pageTitle = 'Certificate types';
$activeNav = 'certificate_types';

$sql = "SELECT id, type_name, type_code, validity_years, is_active, created_at
        FROM certificate_types
        ORDER BY type_name ASC
        LIMIT 200";
$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>Certificate types</h1>
        <p>Templates and rules for issued certificates (validity, codes).</p>
    </div>

    <div class="section-card">
        <div class="section-header">
            <h2><i class="ri-award-line"></i> Types</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>Name</th>
                        <th>Code</th>
                        <th>Validity (years)</th>
                        <th>Active</th>
                        <th>Created</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($rows)): ?>
                    <tr class="empty-row"><td colspan="5"><i class="ri-inbox-line me-2"></i>No certificate types</td></tr>
                    <?php else: ?>
                        <?php foreach ($rows as $r): ?>
                        <tr>
                            <td style="font-weight:600; color:var(--ssbs-blue)"><?= iscms_h($r['type_name']) ?></td>
                            <td class="iscms-mono"><?= iscms_h($r['type_code']) ?></td>
                            <td><?= (int) ($r['validity_years'] ?? 0) ?></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>
                            <td><small class="text-muted"><?= !empty($r['created_at']) ? iscms_h(substr((string) $r['created_at'], 0, 10)) : '<span class="text-muted">-</span>' ?></small></td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
    </div>
<?php
iscms_render_footer();
