<?php
declare(strict_types=1);

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

$conn = iscms_init();
$pageTitle = 'Organisations Register';
$activeNav = 'organizations';

$sql = "SELECT id, org_name, org_type, reg_number, city, country, status, created_at
        FROM organizations
        ORDER BY org_name 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>Organisations</h1>
        <p>Registered manufacturers, importers, laboratories, and other regulated entities.</p>
    </div>

    <div class="section-card">
        <div class="section-header">
            <h2><i class="ri-building-2-line"></i> All organisations</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>Type</th>
                        <th>Registration</th>
                        <th>Location</th>
                        <th>Status</th>
                        <th>Created</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($rows)): ?>
                    <tr class="empty-row"><td colspan="6"><i class="ri-inbox-line me-2"></i>No organisations found</td></tr>
                    <?php else: ?>
                        <?php foreach ($rows as $r): ?>
                        <tr>
                            <td style="font-weight:600; color:var(--ssbs-blue)"><?= iscms_h($r['org_name']) ?></td>
                            <td><small><?= iscms_h(str_replace('_', ' ', $r['org_type'])) ?></small></td>
                            <td class="iscms-mono"><?= iscms_val($r['reg_number'] ?? null) ?></td>
                            <td><small><?php $loc = trim(($r['city'] ?? '') . ', ' . ($r['country'] ?? ''), ' ,'); echo iscms_val($loc); ?></small></td>
                            <td><?= iscms_status_badge((string) ($r['status'] ?? '')) ?></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();
