<?php
// /elms/admin/courses/index.php
declare(strict_types=1);

$PAGE_TITLE = 'Courses';
$ACTIVE = 'courses';

require_once __DIR__ . '/../../includes/admin_auth.php';
require_once __DIR__ . '/../../includes/db.php';

$helpers = __DIR__ . '/../../includes/helpers.php';
if (is_file($helpers)) {
    require_once $helpers;
}

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

/*
|--------------------------------------------------------------------------
| Admin Courses
|--------------------------------------------------------------------------
| Converted to new admin layout/auth standard.
| Allowed admin roles are handled by includes/admin_auth.php:
| super_admin, admin, manager
*/

$db = null;

if (isset($mysqli) && $mysqli instanceof mysqli) {
    $db = $mysqli;
} elseif (isset($conn) && $conn instanceof mysqli) {
    $db = $conn;
}

if (!$db) {
    echo '<div class="alert alert-danger">Database connection not found.</div>';
    require_once __DIR__ . '/../../includes/admin_layout_bottom.php';
    exit;
}

if (!function_exists('esc')) {
    function esc($s): string
    {
        return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

if (!function_exists('admin_table_exists')) {
    function admin_table_exists(mysqli $db, string $table): bool
    {
        try {
            $st = $db->prepare("
                SELECT 1
                FROM INFORMATION_SCHEMA.TABLES
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = ?
                LIMIT 1
            ");
            $st->bind_param('s', $table);
            $st->execute();
            $ok = (bool)$st->get_result()->fetch_row();
            $st->close();

            return $ok;
        } catch (Throwable $e) {
            return false;
        }
    }
}

if (!function_exists('admin_column_exists')) {
    function admin_column_exists(mysqli $db, string $table, string $column): bool
    {
        try {
            $st = $db->prepare("
                SELECT 1
                FROM INFORMATION_SCHEMA.COLUMNS
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = ?
                  AND COLUMN_NAME = ?
                LIMIT 1
            ");
            $st->bind_param('ss', $table, $column);
            $st->execute();
            $ok = (bool)$st->get_result()->fetch_row();
            $st->close();

            return $ok;
        } catch (Throwable $e) {
            return false;
        }
    }
}

$courses = [];
$totalCourses = 0;
$activeCourses = 0;
$inactiveCourses = 0;
$q = trim((string)($_GET['q'] ?? ''));

if (!admin_table_exists($db, 'courses')) {
    echo '<div class="alert alert-warning">Courses table not found.</div>';
    require_once __DIR__ . '/../../includes/admin_layout_bottom.php';
    exit;
}

/*
|--------------------------------------------------------------------------
| Detect columns safely
|--------------------------------------------------------------------------
*/

$labelCol = 'id';

if (admin_column_exists($db, 'courses', 'course_name')) {
    $labelCol = 'course_name';
} elseif (admin_column_exists($db, 'courses', 'name')) {
    $labelCol = 'name';
} elseif (admin_column_exists($db, 'courses', 'title')) {
    $labelCol = 'title';
}

$statusCol = null;

if (admin_column_exists($db, 'courses', 'status')) {
    $statusCol = 'status';
} elseif (admin_column_exists($db, 'courses', 'active')) {
    $statusCol = 'active';
}

/*
|--------------------------------------------------------------------------
| Fetch courses
|--------------------------------------------------------------------------
*/

try {
    $sql = "SELECT id, `$labelCol` AS label";
    if ($statusCol) {
        $sql .= ", `$statusCol` AS st";
    }
    $sql .= " FROM courses";

    $where = [];
    $types = '';
    $vals = [];

    if ($q !== '') {
        $where[] = "`$labelCol` LIKE ?";
        $types .= 's';
        $vals[] = '%' . $q . '%';
    }

    if ($where) {
        $sql .= " WHERE " . implode(' AND ', $where);
    }

    $sql .= " ORDER BY label ASC";

    $stmt = $db->prepare($sql);

    if (!$stmt) {
        throw new RuntimeException('Course query prepare failed.');
    }

    if ($types !== '') {
        $stmt->bind_param($types, ...$vals);
    }

    $stmt->execute();
    $courses = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
} catch (Throwable $e) {
    echo '<div class="alert alert-danger">Unable to load courses.</div>';
    $courses = [];
}

$totalCourses = count($courses);

foreach ($courses as $c) {
    if ($statusCol) {
        $raw = $c['st'] ?? '';

        if ($statusCol === 'active') {
            ((int)$raw === 1) ? $activeCourses++ : $inactiveCourses++;
        } else {
            $s = strtolower(trim((string)$raw));
            in_array($s, ['active','enabled','1'], true) ? $activeCourses++ : $inactiveCourses++;
        }
    }
}

?>
<div class="row g-3 mb-4">
    <div class="col-md-4">
        <div class="admin-card h-100">
            <div class="admin-card-body">
                <div class="text-muted small">Total Courses</div>
                <div class="h3 mb-0"><?= (int)$totalCourses ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-4">
        <div class="admin-card h-100">
            <div class="admin-card-body">
                <div class="text-muted small">Active Courses</div>
                <div class="h3 mb-0 text-success"><?= (int)$activeCourses ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-4">
        <div class="admin-card h-100">
            <div class="admin-card-body">
                <div class="text-muted small">Inactive / Other</div>
                <div class="h3 mb-0 text-secondary"><?= (int)$inactiveCourses ?></div>
            </div>
        </div>
    </div>
</div>

<div class="admin-card mb-4">
    <div class="admin-card-header">
        <div>
            <h5 class="mb-0">Courses</h5>
            <div class="text-muted small">Manage course records, modules, content and releases</div>
        </div>

        <form class="d-flex gap-2" method="get">
            <input
                type="text"
                class="form-control"
                name="q"
                placeholder="Search courses..."
                value="<?= esc($q) ?>"
                style="min-width: 240px;"
            >

            <button class="btn btn-admin-primary">
                <i class="bi bi-search me-1"></i>
                Search
            </button>

            <?php if ($q !== ''): ?>
                <a class="btn btn-outline-secondary rounded-pill" href="index.php">
                    Reset
                </a>
            <?php endif; ?>
        </form>
    </div>

    <div class="admin-card-body">
        <div class="table-responsive">
            <table class="table align-middle mb-0">
                <thead>
                    <tr>
                        <th style="width:55%;">Course</th>
                        <th>Status</th>
                        <th class="text-end">Actions</th>
                    </tr>
                </thead>

                <tbody>
                    <?php if (!$courses): ?>
                        <tr>
                            <td colspan="3" class="text-center text-muted py-4">
                                No courses found.
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($courses as $course): ?>
                            <?php
                                $courseId = (int)($course['id'] ?? 0);
                                $label = (string)($course['label'] ?? ('Course #' . $courseId));

                                $statusText = '—';
                                $statusClass = 'bg-secondary';

                                if ($statusCol) {
                                    $rawStatus = $course['st'] ?? '';

                                    if ($statusCol === 'active') {
                                        $statusText = ((int)$rawStatus === 1) ? 'Active' : 'Inactive';
                                    } else {
                                        $statusText = trim((string)$rawStatus) !== '' ? (string)$rawStatus : 'Inactive';
                                    }

                                    $statusLower = strtolower($statusText);

                                    $statusClass = match ($statusLower) {
                                        'active', '1', 'enabled' => 'bg-success',
                                        'inactive', '0', 'disabled' => 'bg-secondary',
                                        'pending' => 'bg-warning text-dark',
                                        default => 'bg-light text-dark border',
                                    };
                                }
                            ?>

                            <tr>
                                <td>
                                    <div class="fw-semibold"><?= esc($label) ?></div>
                                    <div class="small text-muted">Course ID: <?= $courseId ?></div>
                                </td>

                                <td>
                                    <?php if ($statusCol): ?>
                                        <span class="badge <?= esc($statusClass) ?>">
                                            <?= esc($statusText) ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="text-muted">—</span>
                                    <?php endif; ?>
                                </td>

                                <td class="text-end">
                                    <div class="d-flex justify-content-end flex-wrap gap-2">
                                        <a class="btn btn-sm btn-outline-primary rounded-pill"
                                           href="modules.php?course_id=<?= $courseId ?>">
                                            <i class="bi bi-grid me-1"></i>
                                            Semesters & Modules
                                        </a>

                                        <a class="btn btn-sm btn-outline-dark rounded-pill"
                                           href="releases.php?course_id=<?= $courseId ?>">
                                            <i class="bi bi-send-check me-1"></i>
                                            Releases
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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