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

if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . '/../../includes/auth.php';
require_role(['super_admin','branch_admin','admin']);

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

$mysqli = $mysqli ?? ($conn ?? null);
if (!$mysqli instanceof mysqli) {
    http_response_code(500);
    exit('Database connection missing.');
}

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

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

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

function pick_col(string $table, array $cols, string $fallback = 'id'): string {
    foreach ($cols as $c) {
        if (column_exists_local($table, $c)) return $c;
    }
    return $fallback;
}

function dt_local(?string $value): string {
    if (!$value || $value === '0000-00-00 00:00:00') return '';
    return date('Y-m-d\TH:i', strtotime($value));
}

function to_mysql_dt(string $value): ?string {
    $value = trim($value);
    if ($value === '') return null;
    $ts = strtotime($value);
    return $ts ? date('Y-m-d H:i:s', $ts) : null;
}

$course_id = filter_input(INPUT_GET, 'course_id', FILTER_VALIDATE_INT)
          ?: filter_input(INPUT_POST, 'course_id', FILTER_VALIDATE_INT)
          ?: 0;

if ($course_id <= 0) {
    http_response_code(400);
    exit('Missing course_id');
}

/* Course */
$courseLabelCol = pick_col('courses', ['course_name','name','title'], 'id');
$stmt = $mysqli->prepare("SELECT id, `$courseLabelCol` AS label FROM courses WHERE id=? LIMIT 1");
$stmt->bind_param('i', $course_id);
$stmt->execute();
$COURSE = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$COURSE) {
    http_response_code(404);
    exit('Course not found');
}

/* Detect modules table */
$moduleTable = null;
if (table_exists_local('course_modules') && column_exists_local('course_modules', 'course_id')) {
    $moduleTable = 'course_modules';
} elseif (table_exists_local('lms_modules') && column_exists_local('lms_modules', 'course_id')) {
    $moduleTable = 'lms_modules';
}

if (!$moduleTable) {
    http_response_code(500);
    exit('No module table found.');
}

$moduleTitleCol = pick_col($moduleTable, ['title','name','module_name'], 'id');
$moduleOrderCol = pick_col($moduleTable, ['sort_order','order_no','position'], 'id');

/* Detect content table */
$contentTable = null;
foreach (['lms_content','lms_contents','lms_module_contents','module_contents','lms_content_items'] as $tbl) {
    if (table_exists_local($tbl)) {
        $contentTable = $tbl;
        break;
    }
}

if (!$contentTable) {
    http_response_code(500);
    exit('No content table found.');
}

$contentTitleCol  = pick_col($contentTable, ['title','name','content_title'], 'id');
$contentTypeCol   = pick_col($contentTable, ['content_type','type','lesson_type'], '');
$contentUrlCol    = pick_col($contentTable, ['url','file_path','file_url','path','source_path_or_url','link'], '');
$contentDescCol   = pick_col($contentTable, ['description','content','body'], '');
$contentModuleCol = pick_col($contentTable, ['module_id','lms_module_id','course_module_id'], 'module_id');
$contentOrderCol  = pick_col($contentTable, ['sort_order','order_no','position'], 'id');

$hasAvailableFrom = column_exists_local($contentTable, 'available_from');
$hasAvailableTo   = column_exists_local($contentTable, 'available_to');
$hasActive        = column_exists_local($contentTable, 'active');
$hasRequirePaid   = column_exists_local($contentTable, 'require_paid');

$msg = '';
$err = '';

/* Save */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_releases') {
    $contentIds = $_POST['content_id'] ?? [];

    if (!is_array($contentIds)) $contentIds = [];

    foreach ($contentIds as $cidRaw) {
        $cid = (int)$cidRaw;
        if ($cid <= 0) continue;

        $availableFrom = to_mysql_dt($_POST['available_from'][$cid] ?? '');
        $availableTo   = to_mysql_dt($_POST['available_to'][$cid] ?? '');
        $active        = isset($_POST['active'][$cid]) ? 1 : 0;
        $requirePaid   = isset($_POST['require_paid'][$cid]) ? 1 : 0;

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

        if ($hasAvailableFrom) {
            $sets[] = 'available_from=?';
            $types .= 's';
            $vals[] = $availableFrom;
        }

        if ($hasAvailableTo) {
            $sets[] = 'available_to=?';
            $types .= 's';
            $vals[] = $availableTo;
        }

        if ($hasActive) {
            $sets[] = 'active=?';
            $types .= 'i';
            $vals[] = $active;
        }

        if ($hasRequirePaid) {
            $sets[] = 'require_paid=?';
            $types .= 'i';
            $vals[] = $requirePaid;
        }

        if (!$sets) continue;

        $types .= 'i';
        $vals[] = $cid;

        $sql = "UPDATE `$contentTable` SET " . implode(', ', $sets) . " WHERE id=?";
        $st = $mysqli->prepare($sql);
        $st->bind_param($types, ...$vals);
        $st->execute();
        $st->close();
    }

    $msg = 'Release settings saved successfully.';
}

/* Read modules */
$modules = [];
$st = $mysqli->prepare("
    SELECT id, `$moduleTitleCol` AS title
    FROM `$moduleTable`
    WHERE course_id=?
    ORDER BY `$moduleOrderCol`, id
");
$st->bind_param('i', $course_id);
$st->execute();
$res = $st->get_result();
while ($r = $res->fetch_assoc()) {
    $modules[(int)$r['id']] = $r;
}
$st->close();

/* Read content */
$contentByModule = [];

if ($modules) {
    $ids = implode(',', array_map('intval', array_keys($modules)));

    $select = [
        "id",
        "`$contentModuleCol` AS module_id",
        "`$contentTitleCol` AS title"
    ];

    $select[] = $contentTypeCol ? "`$contentTypeCol` AS content_type" : "'' AS content_type";
    $select[] = $contentUrlCol ? "`$contentUrlCol` AS url" : "'' AS url";
    $select[] = $contentDescCol ? "`$contentDescCol` AS description" : "'' AS description";
    $select[] = $hasAvailableFrom ? "available_from" : "NULL AS available_from";
    $select[] = $hasAvailableTo ? "available_to" : "NULL AS available_to";
    $select[] = $hasActive ? "active" : "1 AS active";
    $select[] = $hasRequirePaid ? "require_paid" : "0 AS require_paid";

    $sql = "
        SELECT " . implode(', ', $select) . "
        FROM `$contentTable`
        WHERE `$contentModuleCol` IN ($ids)
        ORDER BY `$contentModuleCol`, `$contentOrderCol`, id
    ";

    $rs = $mysqli->query($sql);
    while ($row = $rs->fetch_assoc()) {
        $mid = (int)$row['module_id'];
        $contentByModule[$mid][] = $row;
    }
}

$PAGE_TITLE = 'Releases';
$ACTIVE_MENU = 'courses';

$__layoutOpened = false;
foreach (['admin_layout_top.php','layout_top.php','admin_header.php','header_admin.php'] as $f) {
    $p = __DIR__ . '/../../includes/' . $f;
    if (is_file($p)) {
        require_once $p;
        $__layoutOpened = true;
        break;
    }
}
if (!$__layoutOpened) echo '<div class="container-fluid p-3">';
?>

<style>
.release-wrap{
    width: 100%;
    max-width: none;
    padding-right: 12px;
}

.release-head{
    background:linear-gradient(135deg,#111827,#1f2937);
    color:#fff;
    border-radius:16px;
    padding:18px 20px;
    box-shadow:0 10px 28px rgba(15,23,42,.14);
    width:100%;
}

.release-head .muted{
    color:rgba(255,255,255,.72);
}

.module-card{
    width:100%;
    border:1px solid #e5e7eb;
    border-radius:14px;
    overflow:hidden;
    background:#fff;
    box-shadow:0 6px 18px rgba(15,23,42,.05);
    margin-bottom:12px;
}

.module-card .module-title{
    background:#f8fafc;
    padding:10px 14px;
    border-bottom:1px solid #e5e7eb;
}

.content-row{
    padding:10px 14px;
    border-bottom:1px solid #eef2f7;
}

.content-row:last-child{
    border-bottom:0;
}

.content-row .row{
    --bs-gutter-x:.6rem;
    --bs-gutter-y:.45rem;
}

.badge-soft{
    background:#eef2ff;
    color:#3730a3;
    border:1px solid #c7d2fe;
    font-size:11px;
    padding:4px 8px;
}

.small-muted{
    color:#64748b;
    font-size:11px;
}

.empty-box{
    border:1px dashed #cbd5e1;
    border-radius:14px;
    padding:22px;
    text-align:center;
    color:#64748b;
    background:#f8fafc;
}

.form-control,
.form-select{
    border-radius:10px;
}

.content-row .form-control-sm{
    min-height:34px;
    padding:5px 9px;
    font-size:12px;
}

.form-check{
    min-height:auto;
}

.form-check-input{
    margin-top:.2rem;
}

/* desktop column balance */
@media (min-width: 992px){
    .content-row .col-lg-4{
        flex:0 0 auto;
        width:32%;
    }

    .content-row .col-lg-2{
        flex:0 0 auto;
        width:17%;
    }
}

/* remove large right blank feeling */
@media (min-width: 1200px){
    .release-wrap{
        max-width: calc(100vw - 250px);
    }
}
</style>

<div class="release-wrap">

    <div class="release-head mb-4">
        <div class="d-flex flex-wrap align-items-center justify-content-between gap-3">
            <div>
                <h1 class="h4 mb-1">Content Releases</h1>
                <div class="muted"><?= esc($COURSE['label']) ?></div>
            </div>
            <div class="d-flex gap-2">
                <a href="content.php?course_id=<?= (int)$course_id ?>" class="btn btn-light btn-sm">
                    Manage Content
                </a>
                <a href="index.php" class="btn btn-outline-light btn-sm">
                    ← Back to Courses
                </a>
            </div>
        </div>
    </div>

    <?php if ($msg): ?>
        <div class="alert alert-success"><?= esc($msg) ?></div>
    <?php endif; ?>

    <?php if ($err): ?>
        <div class="alert alert-danger"><?= esc($err) ?></div>
    <?php endif; ?>

    <?php if (!$hasAvailableFrom && !$hasAvailableTo && !$hasActive && !$hasRequirePaid): ?>
        <div class="alert alert-warning">
            Release columns not found in <b><?= esc($contentTable) ?></b>.
            Add columns like <code>available_from</code>, <code>available_to</code>, <code>active</code>, <code>require_paid</code>.
        </div>
    <?php endif; ?>

    <?php if (!$modules): ?>
        <div class="empty-box">
            No modules found for this course.
        </div>
    <?php else: ?>

        <form method="post">
            <input type="hidden" name="action" value="save_releases">
            <input type="hidden" name="course_id" value="<?= (int)$course_id ?>">

            <div class="d-flex justify-content-end mb-3">
                <button class="btn btn-primary">
                    Save Release Settings
                </button>
            </div>

            <?php foreach ($modules as $mid => $module): ?>
                <div class="module-card">
                    <div class="module-title d-flex justify-content-between align-items-center">
                        <div>
                            <strong><?= esc($module['title']) ?></strong>
                            <span class="small-muted ms-2">Module ID: <?= (int)$mid ?></span>
                        </div>
                        <span class="badge badge-soft rounded-pill">
                            <?= count($contentByModule[$mid] ?? []) ?> item(s)
                        </span>
                    </div>

                    <?php if (empty($contentByModule[$mid])): ?>
                        <div class="content-row">
                            <span class="small-muted">No content added for this module.</span>
                        </div>
                    <?php else: ?>
                        <?php foreach ($contentByModule[$mid] as $item): ?>
                            <?php $cid = (int)$item['id']; ?>
                            <input type="hidden" name="content_id[]" value="<?= $cid ?>">

                            <div class="content-row">
                                <div class="row g-3 align-items-center">
                                    <div class="col-lg-4">
                                        <div class="fw-semibold"><?= esc($item['title']) ?></div>
                                        <div class="small-muted">
                                            <?= esc($item['content_type'] ?: 'content') ?>
                                            <?php if (!empty($item['url'])): ?>
                                                · <?= esc(mb_strimwidth((string)$item['url'], 0, 60, '...')) ?>
                                            <?php endif; ?>
                                        </div>
                                    </div>

                                    <div class="col-lg-2 col-md-6">
                                        <label class="small-muted">Release From</label>
                                        <input
                                            type="datetime-local"
                                            class="form-control form-control-sm"
                                            name="available_from[<?= $cid ?>]"
                                            value="<?= esc(dt_local($item['available_from'] ?? null)) ?>"
                                            <?= !$hasAvailableFrom ? 'disabled' : '' ?>
                                        >
                                    </div>

                                    <div class="col-lg-2 col-md-6">
                                        <label class="small-muted">Release Until</label>
                                        <input
                                            type="datetime-local"
                                            class="form-control form-control-sm"
                                            name="available_to[<?= $cid ?>]"
                                            value="<?= esc(dt_local($item['available_to'] ?? null)) ?>"
                                            <?= !$hasAvailableTo ? 'disabled' : '' ?>
                                        >
                                    </div>

                                    <div class="col-lg-2 col-md-6">
                                        <label class="small-muted d-block">Visibility</label>
                                        <div class="form-check form-switch">
                                            <input
                                                class="form-check-input"
                                                type="checkbox"
                                                name="active[<?= $cid ?>]"
                                                <?= !empty($item['active']) ? 'checked' : '' ?>
                                                <?= !$hasActive ? 'disabled' : '' ?>
                                            >
                                            <label class="form-check-label">Active</label>
                                        </div>
                                    </div>

                                    <div class="col-lg-2 col-md-6">
                                        <label class="small-muted d-block">Payment Lock</label>
                                        <div class="form-check form-switch">
                                            <input
                                                class="form-check-input"
                                                type="checkbox"
                                                name="require_paid[<?= $cid ?>]"
                                                <?= !empty($item['require_paid']) ? 'checked' : '' ?>
                                                <?= !$hasRequirePaid ? 'disabled' : '' ?>
                                            >
                                            <label class="form-check-label">Require Paid</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>

            <div class="d-flex justify-content-end mt-3 mb-4">
                <button class="btn btn-primary">
                    Save Release Settings
                </button>
            </div>
        </form>

    <?php endif; ?>
</div>

<?php
$__layoutClosed = false;
foreach (['admin_layout_bottom.php','layout_bottom.php','admin_footer.php','footer_admin.php'] as $f) {
    $p = __DIR__ . '/../../includes/' . $f;
    if (is_file($p)) {
        require_once $p;
        $__layoutClosed = true;
        break;
    }
}
if (!$__layoutClosed) echo '</div>';