<?php
/** @var yii\web\View $this */
/** @var app\models\Course $model */
/** @var array $tenants  [id => name] */

use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
?>

<div style="display:grid; grid-template-columns:1fr 300px; gap:20px; align-items:start;">

    <!-- ===== Main form ===== -->
    <div class="lms-card">
        <div class="lms-card-header">
            <i class="fas fa-<?= $model->isNewRecord ? 'plus-circle' : 'edit' ?>"></i>
            <?= $model->isNewRecord ? 'Course Details' : 'Update Course' ?>
        </div>
        <div class="lms-card-body">

        <?php $form = ActiveForm::begin([
            'id'      => 'course-form',
            'options' => ['enctype' => 'multipart/form-data', 'autocomplete' => 'off'],
            'fieldConfig' => ['errorOptions' => ['class' => 'field-error']],
        ]); ?>

            <!-- Tenant -->
            <div class="lms-form-group" style="margin-bottom:18px;">
                <?= $form->field($model, 'tenant_id', [
                        'options'  => ['tag' => false],
                        'template' => '<label class="lms-label" style="font-weight:600;">{label} <span style="color:#e74c3c;">*</span></label>{input}{error}',
                    ])
                    ->dropDownList(
                        ['' => '— Select Tenant —'] + $tenants,
                        ['class' => 'form-control', 'style' => 'padding-left:14px;']
                    )
                ?>
            </div>

            <!-- Course Name -->
            <div class="lms-form-group" style="margin-bottom:18px;">
                <?= $form->field($model, 'course_name', [
                        'options'  => ['tag' => false],
                        'template' => '<label class="lms-label" style="font-weight:600;">{label} <span style="color:#e74c3c;">*</span></label>{input}{error}',
                    ])
                    ->textInput([
                        'class'       => 'form-control',
                        'id'          => 'inp-course-name',
                        'placeholder' => 'e.g. Compliance Level 2',
                        'style'       => 'padding-left:14px;',
                        'autofocus'   => $model->isNewRecord,
                    ])
                ?>
            </div>

            <!-- Leads By -->
            <div class="lms-form-group" style="margin-bottom:18px;">
                <?= $form->field($model, 'leads_by', [
                        'options'  => ['tag' => false],
                        'template' => '<label class="lms-label" style="font-weight:600;">{label}</label>{input}{error}',
                    ])
                    ->textInput(['class' => 'form-control', 'placeholder' => 'Instructor / facilitator name', 'style' => 'padding-left:14px;'])
                ?>
            </div>

            <!-- Start + End dates -->
            <div style="display:grid; grid-template-columns:1fr 1fr; gap:16px; margin-bottom:18px;">
                <div>
                    <?= $form->field($model, 'start_date', [
                            'options'  => ['tag' => false],
                            'template' => '<label class="lms-label" style="font-weight:600;">{label}</label>{input}{error}',
                        ])
                        ->textInput(['class' => 'form-control', 'type' => 'date', 'style' => 'padding-left:14px;'])
                    ?>
                </div>
                <div>
                    <?= $form->field($model, 'end_date', [
                            'options'  => ['tag' => false],
                            'template' => '<label class="lms-label" style="font-weight:600;">{label}</label>{input}{error}',
                        ])
                        ->textInput(['class' => 'form-control', 'type' => 'date', 'style' => 'padding-left:14px;'])
                    ?>
                </div>
            </div>

            <!-- Notes -->
            <div class="lms-form-group" style="margin-bottom:18px;">
                <?= $form->field($model, 'notes', [
                        'options'  => ['tag' => false],
                        'template' => '<label class="lms-label" style="font-weight:600;">{label}</label>{input}{error}',
                    ])
                    ->textarea(['class' => 'form-control', 'rows' => 4, 'style' => 'padding:10px 14px; resize:vertical;'])
                ?>
            </div>

            <!-- Status -->
            <div class="lms-form-group" style="margin-bottom:20px;">
                <?= $form->field($model, 'isActive', [
                        'options'  => ['tag' => false],
                        'template' => '<label class="lms-label" style="font-weight:600;">{label}</label>{input}{error}',
                    ])
                    ->dropDownList(['Y' => 'Active', 'N' => 'Inactive'], ['class' => 'form-control', 'style' => 'padding-left:14px;'])
                ?>
            </div>

            <hr style="border:none; border-top:1px solid #f0f0f0; margin-bottom:20px;">

            <!-- ===== Banner uploads ===== -->
            <div style="margin-bottom:6px; font-weight:600; color:#555; font-size:13px;">
                <i class="fas fa-images" style="margin-right:6px;"></i> Banners
            </div>

            <?php
            $bannerFields = [
                ['courseBannersFile', 'course_banners', 'Course Banner',  'cbanner'],
                ['bannerOneFile',     'banner_one',     'Banner 1',       'b1'],
                ['bannerTwoFile',     'banner_two',     'Banner 2',       'b2'],
            ];
            foreach ($bannerFields as [$fileAttr, $dbAttr, $label, $prefix]):
                $existingUrl = !$model->isNewRecord ? $model->getFileUrl($dbAttr) : null;
            ?>
            <div class="lms-form-group" style="margin-bottom:16px;">
                <label class="lms-label" style="font-weight:600;"><?= $label ?></label>
                <?php if ($existingUrl): ?>
                    <div class="course-existing-banner-wrap">
                        <img src="<?= Html::encode($existingUrl) ?>" alt="<?= $label ?>" class="course-existing-banner">
                        <span style="font-size:12px; color:#888;"><?= Html::encode($model->$dbAttr) ?></span>
                    </div>
                <?php endif; ?>
                <?= $form->field($model, $fileAttr, ['options' => ['tag' => false], 'template' => '{input}{error}'])
                         ->fileInput(['class' => 'form-control', 'accept' => 'image/*']) ?>
                <div class="field-hint"><?= $existingUrl ? 'Leave blank to keep current.' : 'PNG, JPG, GIF or WEBP — max 5 MB.' ?></div>
            </div>
            <?php endforeach; ?>

            <!-- Audit (update only) -->
            <?php if (!$model->isNewRecord): ?>
            <div style="background:#f8faff; border-radius:8px; padding:12px 16px; margin-bottom:20px; font-size:13px; color:#888;">
                <div style="display:flex; gap:24px; flex-wrap:wrap;">
                    <div>
                        <i class="fas fa-user-plus" style="width:14px;"></i>
                        Created by
                        <strong style="color:#555;">
                            <?= $model->createdBy ? Html::encode($model->createdBy->getFullName()) : "User #{$model->created_by}" ?>
                        </strong>
                    </div>
                    <div>
                        <i class="fas fa-calendar" style="width:14px;"></i>
                        <?= $model->created_date_time && $model->created_date_time !== '0000-00-00'
                            ? date('d M Y', strtotime($model->created_date_time)) : '—' ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <div>
                <?= Html::submitButton(
                    '<i class="fas fa-save"></i> ' . ($model->isNewRecord ? 'Save Course' : 'Update Course'),
                    ['class' => 'lms-btn lms-btn-success']
                ) ?>
                <a href="<?= Url::to(['courses/index']) ?>" class="lms-btn lms-btn-secondary" style="margin-left:8px;">
                    Cancel
                </a>
                <?php if (!$model->isNewRecord): ?>
                <?= Html::beginForm(['courses/delete', 'id' => $model->id], 'post', ['style' => 'display:inline; margin-left:8px;']) ?>
                <?= Html::hiddenInput(Yii::$app->request->csrfParam, Yii::$app->request->csrfToken) ?>
                <button type="submit" class="lms-btn lms-btn-danger"
                        onclick="return confirm('Delete course \'<?= Html::encode($model->course_name) ?>\'?')">
                    <i class="fas fa-trash"></i> Delete
                </button>
                <?= Html::endForm() ?>
                <?php endif; ?>
            </div>

        <?php ActiveForm::end(); ?>
        </div>
    </div>

    <!-- ===== Preview panel ===== -->
    <div>
        <!-- Course preview card -->
        <div class="lms-card">
            <div class="lms-card-header" style="background:#f8f9fa;"><i class="fas fa-eye"></i> Preview</div>
            <div class="lms-card-body" style="padding:20px 16px;">
                <div id="preview-banner-wrap" style="margin-bottom:12px; text-align:center;">
                    <?php $bannerUrl = !$model->isNewRecord ? $model->getFileUrl('course_banners') : null; ?>
                    <?php if ($bannerUrl): ?>
                        <img id="preview-banner-img" src="<?= Html::encode($bannerUrl) ?>" alt=""
                             style="width:100%; max-height:120px; object-fit:cover; border-radius:8px; border:1px solid #e2e8f0;">
                    <?php else: ?>
                        <div id="preview-banner-img" class="course-preview-banner-placeholder">
                            <i class="fas fa-image" style="font-size:28px; color:#d0d7e2;"></i>
                        </div>
                    <?php endif; ?>
                </div>
                <div id="preview-name" style="font-weight:700; font-size:15px; color:#0f3460; text-align:center;">
                    <?= Html::encode($model->course_name) ?: 'Course Name' ?>
                </div>
                <div id="preview-tenant" style="font-size:12px; color:#888; text-align:center; margin-top:4px;"></div>
                <div id="preview-dates" style="font-size:12px; color:#aaa; text-align:center; margin-top:4px;"></div>
            </div>
        </div>

        <!-- Tenant quick-info -->
        <div class="lms-card" style="margin-top:16px;" id="tenant-info-card" style="display:none;">
            <div class="lms-card-header" style="background:#f8f9fa; font-size:12px;">
                <i class="fas fa-building"></i> Selected Tenant
            </div>
            <div class="lms-card-body" id="tenant-info-body" style="padding:12px 16px; font-size:13px; color:#555;">
                <span style="color:#ccc;">Select a tenant to see details.</span>
            </div>
        </div>
    </div>

</div>

<script>
(function () {
    var nameInp   = document.getElementById('inp-course-name');
    var prevName  = document.getElementById('preview-name');
    var prevDates = document.getElementById('preview-dates');
    var tenantSel = document.querySelector('[name="Course[tenant_id]"]');
    var startInp  = document.querySelector('[name="Course[start_date]"]');
    var endInp    = document.querySelector('[name="Course[end_date]"]');

    var tenantMap = <?= json_encode(
        array_column(
            array_map(fn($id, $name) => ['id' => $id, 'name' => $name], array_keys($tenants), $tenants),
            'name', 'id'
        )
    ) ?>;

    if (nameInp) {
        nameInp.addEventListener('input', function () {
            prevName.textContent = this.value.trim() || 'Course Name';
        });
    }

    function updateDates() {
        var s = startInp ? startInp.value : '';
        var e = endInp   ? endInp.value   : '';
        if (s || e) {
            prevDates.textContent = (s || '—') + ' → ' + (e || '—');
        } else {
            prevDates.textContent = '';
        }
    }
    if (startInp) startInp.addEventListener('change', updateDates);
    if (endInp)   endInp.addEventListener('change',   updateDates);
    updateDates();

    if (tenantSel) {
        tenantSel.addEventListener('change', function () {
            var id   = this.value;
            var name = tenantMap[id] || '';
            document.getElementById('preview-tenant').textContent = name;
            document.getElementById('tenant-info-body').innerHTML =
                name ? '<i class="fas fa-building" style="color:#3498db; margin-right:6px;"></i>' + name
                     : '<span style="color:#ccc;">Select a tenant to see details.</span>';
        });
        // trigger on load
        tenantSel.dispatchEvent(new Event('change'));
    }

    // Live banner preview from file input
    var bannerInput = document.querySelector('[name="Course[courseBannersFile]"]');
    if (bannerInput) {
        bannerInput.addEventListener('change', function () {
            var file = this.files[0];
            if (file && file.type.startsWith('image/')) {
                var r = new FileReader();
                r.onload = function (e) {
                    var el = document.getElementById('preview-banner-img');
                    if (el.tagName === 'DIV') {
                        var img = document.createElement('img');
                        img.id    = 'preview-banner-img';
                        img.style = 'width:100%; max-height:120px; object-fit:cover; border-radius:8px; border:1px solid #e2e8f0;';
                        el.parentNode.replaceChild(img, el);
                    }
                    document.getElementById('preview-banner-img').src = e.target.result;
                };
                r.readAsDataURL(file);
            }
        });
    }
})();
</script>
