<?php
// coordinator/modules.php
declare(strict_types=1);

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

$db = $conn ?? $mysqli ?? null;
if (!$db instanceof mysqli) {
    http_response_code(500);
    exit('Database connection not found.');
}
$db->set_charset('utf8mb4');

if (!function_exists('h')) {
    function h($value): string {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

function cmo_table_exists(mysqli $db, string $table): bool {
    $safe = $db->real_escape_string($table);
    $res = $db->query("SHOW TABLES LIKE '{$safe}'");
    return $res && $res->num_rows > 0;
}

function cmo_col_exists(mysqli $db, string $table, string $col): bool {
    $safeTable = preg_replace('/[^a-zA-Z0-9_]/', '', $table);
    $safeCol = $db->real_escape_string($col);
    $res = $db->query("SHOW COLUMNS FROM `{$safeTable}` LIKE '{$safeCol}'");
    return $res && $res->num_rows > 0;
}

function cmo_first_col(mysqli $db, string $table, array $cols): ?string {
    foreach ($cols as $col) {
        if (cmo_col_exists($db, $table, $col)) return $col;
    }
    return null;
}

$error = '';
$rows = [];

if (!cmo_table_exists($db, 'course_modules')) {
    $error = 'course_modules table not found.';
} else {
    $titleCol = cmo_first_col($db, 'course_modules', ['title', 'module_name', 'name']);
    $sortCol = cmo_first_col($db, 'course_modules', ['sort_order', 'ordering']);
    $statusCol = cmo_first_col($db, 'course_modules', ['status', 'active']);
    $hasCourseId = cmo_col_exists($db, 'course_modules', 'course_id');

    $select = [
        "cm.id",
        $titleCol ? "cm.`{$titleCol}` AS module_title" : "CONCAT('Module #', cm.id) AS module_title",
        $sortCol ? "cm.`{$sortCol}` AS sort_order" : "0 AS sort_order",
        $statusCol ? "cm.`{$statusCol}` AS status" : "'Active' AS status"
    ];

    $joins = [];

    if ($hasCourseId && cmo_table_exists($db, 'courses')) {
        $courseNameCol = cmo_first_col($db, 'courses', ['course_name', 'name', 'title']);
        if ($courseNameCol) {
            $select[] = "c.`{$courseNameCol}` AS course_name";
            $joins[] = "LEFT JOIN courses c ON c.id = cm.course_id";
        } else {
            $select[] = "'' AS course_name";
        }
    } else {
        $select[] = "'' AS course_name";
    }

    if (cmo_table_exists($db, 'lms_assessments') && cmo_col_exists($db, 'lms_assessments', 'module_id')) {
        $select[] = "COUNT(DISTINCT a.id) AS assessment_count";
        $joins[] = "LEFT JOIN lms_assessments a ON a.module_id = cm.id";
    } else {
        $select[] = "0 AS assessment_count";
    }

    $sql = "
        SELECT " . implode(",\n               ", $select) . "
        FROM course_modules cm
        " . implode("\n        ", $joins) . "
        GROUP BY cm.id
        ORDER BY course_name ASC, sort_order ASC, cm.id ASC
        LIMIT 500
    ";

    $res = $db->query($sql);
    if (!$res) {
        $error = 'Modules SQL error: ' . $db->error;
    } else {
        $rows = $res->fetch_all(MYSQLI_ASSOC);
    }
}

require_once __DIR__ . '/../includes/coordinator_layout_top.php';
?>

<div class="d-flex justify-content-between align-items-start mb-4">
    <div>
        <h1 class="page-title">Modules</h1>
        <div class="page-subtitle">View course modules and assessment mapping</div>
    </div>

    <a href="/elms/coordinator/dashboard.php" class="btn btn-light border rounded-4">
        <i class="bi bi-arrow-left me-1"></i> Dashboard
    </a>
</div>

<?php if ($error): ?>
    <div class="alert alert-warning rounded-4"><strong>Notice:</strong> <?= h($error) ?></div>
<?php endif; ?>

<div class="eden-card p-3 mb-4">
    <div class="row g-3 align-items-center">
        <div class="col-lg-8">
            <div class="input-group">
                <span class="input-group-text bg-white border-end-0"><i class="bi bi-search"></i></span>
                <input type="text" id="moduleSearch" class="form-control border-start-0" placeholder="Search module or course...">
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <span class="badge text-bg-danger rounded-pill px-3 py-2"><?= number_format(count($rows)) ?> Modules</span>
        </div>
    </div>
</div>

<div class="eden-card overflow-hidden">
    <div class="table-responsive">
        <table class="table table-hover align-middle mb-0" id="modulesTable">
            <thead class="table-light">
                <tr>
                    <th>ID</th>
                    <th>Module</th>
                    <th>Course</th>
                    <th>Sort</th>
                    <th>Assessments</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
            <?php if (!$rows): ?>
                <tr><td colspan="6" class="text-center text-muted py-5"><i class="bi bi-inbox fs-2 d-block mb-2"></i>No modules found.</td></tr>
            <?php else: foreach ($rows as $r): ?>
                <?php
                    $status = strtolower((string)($r['status'] ?? 'active'));
                    $badge = in_array($status, ['active', '1'], true) ? 'text-bg-success' : 'text-bg-secondary';
                    $statusText = $status === '1' ? 'Active' : ($status === '0' ? 'Inactive' : ucwords($status));
                ?>
                <tr>
                    <td class="text-muted">#<?= (int)$r['id'] ?></td>
                    <td class="fw-bold"><?= h($r['module_title']) ?></td>
                    <td><?= !empty($r['course_name']) ? h($r['course_name']) : '<span class="text-muted">-</span>' ?></td>
                    <td><?= (int)($r['sort_order'] ?? 0) ?></td>
                    <td><span class="badge text-bg-danger rounded-pill"><?= (int)($r['assessment_count'] ?? 0) ?></span></td>
                    <td><span class="badge <?= h($badge) ?> rounded-pill"><?= h($statusText) ?></span></td>
                </tr>
            <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const q = document.getElementById('moduleSearch');
    const rows = Array.from(document.querySelectorAll('#modulesTable tbody tr'));
    q.addEventListener('input', function(){
        const search = (q.value || '').toLowerCase().trim();
        rows.forEach(row => {
            row.style.display = search === '' || row.innerText.toLowerCase().includes(search) ? '' : 'none';
        });
    });
});
</script>

<?php require_once __DIR__ . '/../includes/coordinator_layout_bottom.php'; ?>