<?php
/** @var yii\web\View $this */
/** @var app\models\Tenant $model */
/** @var app\models\TenantBanner[] $banners */
/** @var app\models\ColourScheme[] $colours */
/** @var array[] $courses */
/** @var app\models\TenantBanner $newBanner */
/** @var app\models\ColourScheme $newColour */
/** @var string $activeTab */

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

$this->title  = 'Edit — ' . $model->tenant_name;
$currentLogo  = $model->getLogoUrl();
?>

<div class="page-title">
    <i class="fas fa-edit"></i> <?= Html::encode($model->tenant_name) ?>
    <div style="margin-left:auto; display:flex; gap:8px;">
        <a href="<?= Url::to(['tenant/view', 'id' => $model->id]) ?>" class="lms-btn lms-btn-secondary lms-btn-sm">
            <i class="fas fa-eye"></i> View
        </a>
        <a href="<?= Url::to(['tenant/index']) ?>" class="lms-btn lms-btn-primary lms-btn-sm">
            <i class="fas fa-arrow-left"></i> Back
        </a>
    </div>
</div>

<!-- ===== Tab nav ===== -->
<div class="tenant-tab-nav">
    <button class="tenant-tab-btn" data-tab="details">
        <i class="fas fa-building"></i> Details
    </button>
    <button class="tenant-tab-btn" data-tab="banners">
        <i class="fas fa-images"></i> Banners
        <span class="tenant-tab-count"><?= count($banners) ?></span>
    </button>
    <button class="tenant-tab-btn" data-tab="colours">
        <i class="fas fa-palette"></i> Colour Scheme
        <span class="tenant-tab-count"><?= count($colours) ?></span>
    </button>
    <button class="tenant-tab-btn" data-tab="courses">
        <i class="fas fa-book-open"></i> Courses
        <span class="tenant-tab-count"><?= count($courses) ?></span>
    </button>
</div>

<!-- ================================================================
     TAB: DETAILS
     ================================================================ -->
<div id="tab-details" class="tenant-tab-panel">
<div style="display:grid; grid-template-columns:1fr 280px; gap:20px; align-items:start;">

    <!-- Form -->
    <div class="lms-card">
        <div class="lms-card-header">
            <i class="fas fa-edit"></i> Tenant Details
        </div>
        <div class="lms-card-body">

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

            <div class="lms-form-group" style="margin-bottom:18px;">
                <?= $form->field($model, 'tenant_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-tenant-name', 'style' => 'padding-left:14px;']) ?>
            </div>

            <div style="display:grid; grid-template-columns:1fr 1fr; gap:16px; margin-bottom:18px;">
                <div>
                    <?= $form->field($model, 'tenant_phone', [
                            'options'  => ['tag' => false],
                            'template' => '<label class="lms-label" style="font-weight:600;">{label}</label>{input}{error}',
                        ])->textInput(['class' => 'form-control', 'id' => 'inp-tenant-phone', 'style' => 'padding-left:14px;']) ?>
                </div>
                <div>
                    <?= $form->field($model, 'tenant_email', [
                            'options'  => ['tag' => false],
                            'template' => '<label class="lms-label" style="font-weight:600;">{label}</label>{input}{error}',
                        ])->textInput(['class' => 'form-control', 'id' => 'inp-tenant-email', 'style' => 'padding-left:14px;']) ?>
                </div>
            </div>

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

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

            <!-- Logo -->
            <div class="lms-form-group" style="margin-bottom:18px;">
                <label class="lms-label" style="font-weight:600;">Upload New Logo</label>
                <?php if ($currentLogo): ?>
                <div class="tenant-current-logo-wrap">
                    <img src="<?= Html::encode($currentLogo) ?>" alt="Logo" class="tenant-current-logo">
                    <span style="font-size:12px; color:#888;"><?= Html::encode($model->tenant_logo_name ?: $model->tenant_logo) ?></span>
                </div>
                <?php endif; ?>
                <?= $form->field($model, 'logoFile', ['options' => ['tag' => false], 'template' => '{input}{error}'])
                         ->fileInput(['class' => 'form-control', 'id' => 'logo-file-input', 'accept' => 'image/*']) ?>
                <div class="field-hint">Leave blank to keep current logo. PNG, JPG, GIF, SVG, WEBP — max 2 MB.</div>
            </div>

            <div class="lms-form-group" style="margin-bottom:18px;">
                <?= $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>

            <!-- Audit -->
            <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-clock" style="width:14px;"></i>
                        <?= ($model->created_date_time && $model->created_date_time !== '0000-00-00 00:00:00')
                            ? date('d M Y, H:i', strtotime($model->created_date_time)) : '—' ?>
                    </div>
                </div>
            </div>

            <div>
                <?= Html::submitButton('<i class="fas fa-save"></i> Save Changes', ['class' => 'lms-btn lms-btn-success']) ?>
                <a href="<?= Url::to(['tenant/index']) ?>" class="lms-btn lms-btn-secondary" style="margin-left:8px;">Cancel</a>
                <?= Html::beginForm(['tenant/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 tenant \'<?= Html::encode($model->tenant_name) ?>\'?')">
                    <i class="fas fa-trash"></i> Delete
                </button>
                <?= Html::endForm() ?>
            </div>

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

    <!-- Preview panel -->
    <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="text-align:center; padding:24px 16px;">
            <div style="margin-bottom:14px;">
                <?php if ($currentLogo): ?>
                    <img id="logo-preview-img" src="<?= Html::encode($currentLogo) ?>" alt="Logo" class="tenant-logo-preview-img">
                    <div id="logo-placeholder" class="tenant-logo-preview-placeholder" style="display:none;">
                        <i class="fas fa-building" style="font-size:32px; color:#c8d0e0;"></i>
                    </div>
                <?php else: ?>
                    <img id="logo-preview-img" src="" alt="" class="tenant-logo-preview-img" style="display:none;">
                    <div id="logo-placeholder" class="tenant-logo-preview-placeholder">
                        <i class="fas fa-building" style="font-size:32px; color:#c8d0e0;"></i>
                    </div>
                <?php endif; ?>
            </div>
            <div id="preview-name" style="font-size:16px; font-weight:700; color:#0f3460;"><?= Html::encode($model->tenant_name) ?></div>
            <div id="preview-email" style="font-size:12px; color:#888; margin-top:4px;"><?= Html::encode($model->tenant_email) ?></div>
            <div id="preview-phone" style="font-size:12px; color:#888;"><?= Html::encode($model->tenant_phone) ?></div>
        </div>
    </div>

</div>
</div><!-- /tab-details -->

<!-- ================================================================
     TAB: BANNERS
     ================================================================ -->
<div id="tab-banners" class="tenant-tab-panel">

    <div class="lms-card" style="margin-bottom:20px;">
        <div class="lms-card-header"><i class="fas fa-plus-circle"></i> Add Banner</div>
        <div class="lms-card-body">
            <?php $form = ActiveForm::begin([
                'action'  => ['tenant/add-banner', 'tenantId' => $model->id],
                'options' => ['enctype' => 'multipart/form-data', 'autocomplete' => 'off'],
                'fieldConfig' => ['errorOptions' => ['class' => 'field-error']],
            ]); ?>
            <div style="display:grid; grid-template-columns:1fr 1fr auto; gap:12px; align-items:end;">
                <div>
                    <?= $form->field($newBanner, 'bannerFile', [
                            'options'  => ['tag' => false],
                            'template' => '<label class="lms-label" style="font-weight:600;">{label} <span style="color:#e74c3c;">*</span></label>{input}{error}',
                        ])->fileInput(['class' => 'form-control', 'accept' => 'image/*']) ?>
                </div>
                <div>
                    <?= $form->field($newBanner, 'tenant_banner_name', [
                            'options'  => ['tag' => false],
                            'template' => '<label class="lms-label" style="font-weight:600;">{label}</label>{input}{error}',
                        ])->textInput(['class' => 'form-control', 'placeholder' => 'e.g. Home Banner']) ?>
                </div>
                <div>
                    <?= Html::submitButton('<i class="fas fa-plus"></i> Add', ['class' => 'lms-btn lms-btn-success']) ?>
                </div>
            </div>
            <?php ActiveForm::end(); ?>
        </div>
    </div>

    <?php if (empty($banners)): ?>
        <div class="lms-card">
            <div style="padding:40px; text-align:center; color:#aaa;">
                <i class="fas fa-images" style="font-size:40px; display:block; margin-bottom:12px;"></i>
                No banners yet. Upload the first one above.
            </div>
        </div>
    <?php else: ?>
        <div class="tenant-banner-grid">
            <?php foreach ($banners as $b): ?>
            <div class="tenant-banner-card">
                <?php if ($b->getImageUrl()): ?>
                    <div class="banner-thumb-wrap">
                        <img src="<?= Html::encode($b->getImageUrl()) ?>" alt="<?= Html::encode($b->tenant_banner_name) ?>" class="banner-thumb">
                    </div>
                <?php else: ?>
                    <div class="banner-thumb-wrap banner-no-img">
                        <i class="fas fa-image" style="font-size:28px; color:#d0d7e2;"></i>
                    </div>
                <?php endif; ?>
                <div class="banner-card-body">
                    <div class="banner-title"><?= Html::encode($b->tenant_banner_name) ?: '<span style="color:#ccc;">Untitled</span>' ?></div>
                    <div class="banner-meta" style="font-size:11px; color:#aaa;"><?= Html::encode($b->tenant_banner_image) ?></div>
                </div>
                <div class="banner-card-actions">
                    <?= Html::beginForm(['tenant/delete-banner', 'id' => $b->id], 'post') ?>
                    <?= Html::hiddenInput(Yii::$app->request->csrfParam, Yii::$app->request->csrfToken) ?>
                    <button type="submit" class="lms-btn lms-btn-danger lms-btn-sm"
                            onclick="return confirm('Delete this banner?')" title="Delete">
                        <i class="fas fa-trash"></i>
                    </button>
                    <?= Html::endForm() ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

</div><!-- /tab-banners -->

<!-- ================================================================
     TAB: COLOUR SCHEME (TE)
     ================================================================ -->
<div id="tab-colours" class="tenant-tab-panel">

    <div class="lms-card" style="margin-bottom:20px;">
        <div class="lms-card-header"><i class="fas fa-plus-circle"></i> Add Theme Colour</div>
        <div class="lms-card-body">
            <?php $form = ActiveForm::begin([
                'action'  => ['tenant/add-colour', 'tenantId' => $model->id],
                'options' => ['autocomplete' => 'off'],
                'fieldConfig' => ['errorOptions' => ['class' => 'field-error']],
            ]); ?>
            <div style="display:grid; grid-template-columns:1fr 1fr 170px auto; gap:12px; align-items:end;">
                <div>
                    <?= $form->field($newColour, 'item', [
                            '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', 'placeholder' => 'e.g. primary, header']) ?>
                </div>
                <div>
                    <?= $form->field($newColour, 'field', [
                            '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', 'placeholder' => 'e.g. Primary background']) ?>
                </div>
                <div>
                    <label class="lms-label" style="font-weight:600;">Colour <span style="color:#e74c3c;">*</span></label>
                    <div class="cs-picker-row">
                        <input type="color" id="add-colour-picker" value="#3498db"
                               style="width:38px; height:34px; border:1px solid #d0d7e2; border-radius:6px; cursor:pointer; padding:2px;">
                        <?= $form->field($newColour, 'colour', ['options' => ['tag' => false], 'template' => '{input}{error}'])
                                 ->textInput(['id' => 'add-colour-hex', 'class' => 'form-control', 'style' => 'width:100px; font-family:monospace;', 'maxlength' => 7]) ?>
                    </div>
                </div>
                <div>
                    <?= Html::submitButton('<i class="fas fa-plus"></i> Add', ['class' => 'lms-btn lms-btn-success']) ?>
                </div>
            </div>
            <?php ActiveForm::end(); ?>
        </div>
    </div>

    <?php if (empty($colours)): ?>
        <div class="lms-card">
            <div style="padding:40px; text-align:center; color:#aaa;">
                <i class="fas fa-palette" style="font-size:40px; display:block; margin-bottom:12px;"></i>
                No theme colours defined. Add the first one above.
            </div>
        </div>
    <?php else: ?>
    <div class="lms-card">
        <div class="lms-card-header">
            <i class="fas fa-palette"></i> Theme Colours
            <span class="lms-badge lms-badge-info" style="margin-left:8px;"><?= count($colours) ?></span>
        </div>
        <div class="table-responsive">
            <table class="lms-table">
                <thead>
                    <tr>
                        <th>Item</th>
                        <th>Field / Description</th>
                        <th style="width:160px; text-align:center;">Colour</th>
                        <th style="width:210px;">Edit Colour</th>
                        <th style="width:60px; text-align:center;"></th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($colours as $c): ?>
                <tr>
                    <td style="font-weight:500;"><?= Html::encode($c->item) ?></td>
                    <td style="color:#666; font-size:13px;"><?= Html::encode($c->field) ?></td>
                    <td style="text-align:center;">
                        <div class="cs-colour-cell">
                            <span class="cs-swatch" style="background:<?= Html::encode($c->colour) ?>;"></span>
                            <code class="cs-hex"><?= Html::encode($c->colour) ?></code>
                        </div>
                    </td>
                    <td>
                        <?php $ef = ActiveForm::begin([
                            'action'  => ['tenant/update-colour', 'id' => $c->id],
                            'options' => ['style' => 'display:flex; gap:6px; align-items:center;', 'autocomplete' => 'off'],
                        ]); ?>
                        <?= $ef->field($c, 'colour', ['options' => ['tag' => false], 'template' => '{input}'])
                               ->textInput([
                                   'id'        => 'hex-' . $c->id,
                                   'class'     => 'form-control form-control-sm',
                                   'style'     => 'width:90px; font-family:monospace; font-size:12px;',
                                   'maxlength' => 7,
                               ]) ?>
                        <input type="color" value="<?= Html::encode($c->colour) ?>"
                               style="width:32px; height:30px; border:1px solid #d0d7e2; border-radius:4px; cursor:pointer; padding:2px;"
                               oninput="document.getElementById('hex-<?= $c->id ?>').value=this.value.toUpperCase()">
                        <button type="submit" class="lms-btn lms-btn-primary lms-btn-sm" title="Save"><i class="fas fa-check"></i></button>
                        <?php ActiveForm::end(); ?>
                    </td>
                    <td style="text-align:center;">
                        <?= Html::beginForm(['tenant/delete-colour', 'id' => $c->id], 'post') ?>
                        <?= Html::hiddenInput(Yii::$app->request->csrfParam, Yii::$app->request->csrfToken) ?>
                        <button type="submit" class="lms-btn lms-btn-danger lms-btn-sm"
                                onclick="return confirm('Delete this colour?')" title="Delete">
                            <i class="fas fa-trash"></i>
                        </button>
                        <?= Html::endForm() ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

</div><!-- /tab-colours -->

<!-- ================================================================
     TAB: COURSES
     ================================================================ -->
<div id="tab-courses" class="tenant-tab-panel">

    <div class="lms-card">
        <div class="lms-card-header">
            <i class="fas fa-book-open"></i> Courses for <?= Html::encode($model->tenant_name) ?>
            <span class="lms-badge lms-badge-info" style="margin-left:8px;"><?= count($courses) ?></span>
            <a href="<?= Url::to(['courses/create']) ?>"
               class="lms-btn lms-btn-primary lms-btn-sm" style="margin-left:auto;">
                <i class="fas fa-plus"></i> New Course
            </a>
        </div>

        <?php if (empty($courses)): ?>
            <div style="padding:40px; text-align:center; color:#aaa;">
                <i class="fas fa-book-open" style="font-size:40px; display:block; margin-bottom:12px;"></i>
                No courses assigned to this tenant yet.
                <div style="margin-top:10px;">
                    <a href="<?= Url::to(['courses/create']) ?>" class="lms-btn lms-btn-primary lms-btn-sm">
                        <i class="fas fa-plus"></i> Add First Course
                    </a>
                </div>
            </div>
        <?php else: ?>
        <div class="table-responsive">
            <table class="lms-table">
                <thead>
                    <tr>
                        <th style="width:50px; text-align:center;">#</th>
                        <th>Course Name</th>
                        <th style="width:160px;">Leads By</th>
                        <th style="width:110px; text-align:center;">Start Date</th>
                        <th style="width:110px; text-align:center;">End Date</th>
                        <th style="width:90px; text-align:center;">Status</th>
                        <th style="width:90px; text-align:center;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($courses as $c): ?>
                <tr class="<?= ($c['isActive'] ?? '') === 'N' ? 'row-inactive' : '' ?>">
                    <td style="text-align:center; color:#aaa; font-size:13px;"><?= $c['id'] ?></td>
                    <td style="font-weight:500;"><?= Html::encode($c['course_name']) ?></td>
                    <td style="font-size:13px; color:#666;"><?= Html::encode($c['leads_by'] ?? '') ?: '<span style="color:#ccc;">—</span>' ?></td>
                    <td style="text-align:center; font-size:13px; color:#888;">
                        <?= !empty($c['start_date']) && $c['start_date'] !== '0000-00-00'
                            ? date('d M Y', strtotime($c['start_date'])) : '—' ?>
                    </td>
                    <td style="text-align:center; font-size:13px; color:#888;">
                        <?= !empty($c['end_date']) && $c['end_date'] !== '0000-00-00'
                            ? date('d M Y', strtotime($c['end_date'])) : '—' ?>
                    </td>
                    <td style="text-align:center;">
                        <span class="lms-badge <?= ($c['isActive'] ?? '') === 'Y' ? 'lms-badge-success' : 'lms-badge-danger' ?>">
                            <?= ($c['isActive'] ?? '') === 'Y' ? 'Active' : 'Inactive' ?>
                        </span>
                    </td>
                    <td style="text-align:center;">
                        <a href="<?= Url::to(['courses/update', 'id' => $c['id']]) ?>"
                           class="lms-btn lms-btn-primary lms-btn-sm" title="Edit">
                            <i class="fas fa-edit"></i>
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>

</div><!-- /tab-courses -->

<script>
(function () {
    var activeTab = <?= json_encode($activeTab) ?>;

    function switchTab(name) {
        document.querySelectorAll('.tenant-tab-btn').forEach(function (b) {
            b.classList.toggle('active', b.dataset.tab === name);
        });
        document.querySelectorAll('.tenant-tab-panel').forEach(function (p) {
            p.classList.toggle('active', p.id === 'tab-' + name);
        });
    }

    document.querySelectorAll('.tenant-tab-btn').forEach(function (btn) {
        btn.addEventListener('click', function () { switchTab(this.dataset.tab); });
    });

    switchTab(activeTab);

    // Details tab — logo + name/email/phone preview
    var nameInp  = document.getElementById('inp-tenant-name');
    var emailInp = document.querySelector('[name="Tenant[tenant_email]"]');
    var phoneInp = document.querySelector('[name="Tenant[tenant_phone]"]');
    var fileInp  = document.getElementById('logo-file-input');
    var prevName  = document.getElementById('preview-name');
    var prevEmail = document.getElementById('preview-email');
    var prevPhone = document.getElementById('preview-phone');
    var prevImg   = document.getElementById('logo-preview-img');
    var prevPh    = document.getElementById('logo-placeholder');

    if (nameInp)  nameInp.addEventListener('input',  function () { prevName.textContent  = this.value.trim() || '—'; });
    if (emailInp) emailInp.addEventListener('input', function () { prevEmail.textContent = this.value.trim(); });
    if (phoneInp) phoneInp.addEventListener('input', function () { prevPhone.textContent = this.value.trim(); });
    if (fileInp) {
        fileInp.addEventListener('change', function () {
            var file = this.files[0];
            if (file && file.type.startsWith('image/')) {
                var r = new FileReader();
                r.onload = function (e) {
                    prevImg.src = e.target.result;
                    prevImg.style.display = 'block';
                    if (prevPh) prevPh.style.display = 'none';
                };
                r.readAsDataURL(file);
            }
        });
    }

    // Colours tab — add picker sync
    var addPicker = document.getElementById('add-colour-picker');
    var addHex    = document.getElementById('add-colour-hex');
    if (addPicker && addHex) {
        addPicker.addEventListener('input', function () { addHex.value = this.value.toUpperCase(); });
        addHex.addEventListener('input', function () {
            if (/^#[0-9A-Fa-f]{6}$/.test(this.value.trim())) addPicker.value = this.value.trim();
        });
    }
})();
</script>
