<?php
/** @var yii\web\View $this */
/** @var common\models\Plan $model */
/** @var bool $isNew */

use common\models\Plan;
use yii\helpers\Html;
use yii\helpers\Url;

$this->title = $isNew ? 'Add Program' : 'Edit: ' . $model->name;

$iconOptions = [
    'bi-trophy'          => 'Trophy (Sports)',
    'bi-heart-pulse'     => 'Heart Pulse (Health)',
    'bi-flower1'         => 'Flower (Lifestyle)',
    'bi-gender-female'   => 'Female (Women / Fertility)',
    'bi-briefcase'       => 'Briefcase (Corporate)',
    'bi-person-walking'  => 'Walking (Active)',
    'bi-stars'           => 'Stars (Premium)',
    'bi-leaf'            => 'Leaf (Nutrition)',
    'bi-egg-fried'       => 'Egg (Diet)',
    'bi-clipboard-pulse' => 'Clipboard (Clinical)',
];
?>

<div style="margin-bottom:1.5rem;display:flex;align-items:center;gap:.75rem">
    <a href="<?= Url::to(['/webcms/plan/index']) ?>" class="btn-cms-secondary">
        <i class="bi bi-arrow-left"></i> Back
    </a>
    <h2 style="font-size:1.3rem;font-weight:700;color:#0f172a;margin:0"><?= Html::encode($this->title) ?></h2>
</div>

<?php if ($model->hasErrors()): ?>
<div style="background:#fef2f2;border:1px solid #fecaca;color:#dc2626;border-radius:10px;padding:.85rem 1.1rem;margin-bottom:1.5rem;font-size:.88rem">
    <i class="bi bi-exclamation-circle me-2"></i>
    <?php foreach ($model->getFirstErrors() as $err): ?>
        <?= Html::encode($err) ?><br>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<?php $form = \yii\widgets\ActiveForm::begin(['id' => 'plan-form', 'options' => ['novalidate' => true]]); ?>

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

    <!-- Left column -->
    <div style="display:flex;flex-direction:column;gap:1.5rem">

        <!-- Program identity -->
        <div class="cms-card">
            <div class="cms-card-header"><h5><i class="bi bi-card-text me-2" style="color:var(--cms-active)"></i>Program Identity</h5></div>
            <div class="cms-card-body" style="display:flex;flex-direction:column;gap:1.2rem">
                <div style="display:grid;grid-template-columns:1fr 140px;gap:1rem;align-items:end">
                    <div>
                        <label class="form-label-cms">Program Name *</label>
                        <?= $form->field($model, 'name', ['template' => '{input}{error}'])
                            ->textInput(['class' => 'cms-input', 'placeholder' => 'e.g. Sports Nutrition Program']) ?>
                    </div>
                    <div>
                        <label class="form-label-cms">Display Order</label>
                        <?= $form->field($model, 'sort_order', ['template' => '{input}{error}'])
                            ->textInput(['class' => 'cms-input', 'type' => 'number', 'min' => '0', 'placeholder' => '0']) ?>
                        <div class="form-hint">Lower = first</div>
                    </div>
                </div>

                <div>
                    <label class="form-label-cms">Short Description</label>
                    <div class="form-hint" style="margin-bottom:.4rem">1–2 sentences shown under the program name.</div>
                    <?= $form->field($model, 'description', ['template' => '{input}{error}'])
                        ->textarea(['class' => 'cms-input', 'rows' => 2, 'placeholder' => 'A brief overview of what this program is about...']) ?>
                </div>

                <div>
                    <label class="form-label-cms">Who It's For</label>
                    <div class="form-hint" style="margin-bottom:.4rem">One line — shown as a subheading on the card.</div>
                    <?= $form->field($model, 'who_it_for', ['template' => '{input}{error}'])
                        ->textInput(['class' => 'cms-input', 'placeholder' => 'e.g. Athletes, competitive players & active individuals']) ?>
                </div>
            </div>
        </div>

        <!-- What's included -->
        <div class="cms-card">
            <div class="cms-card-header"><h5><i class="bi bi-list-check me-2" style="color:var(--cms-active)"></i>What's Included</h5></div>
            <div class="cms-card-body">
                <div class="form-hint" style="margin-bottom:.6rem">Enter one feature per line. Each line becomes a bullet point on the website.</div>
                <?= $form->field($model, 'features', ['template' => '{input}{error}'])
                    ->textarea([
                        'class'       => 'cms-input',
                        'rows'        => 7,
                        'placeholder' => "Performance-focused meal planning\nPre/post training nutrition\nSupplement guidance\nWeekly progress check-ins\nRecovery nutrition strategies",
                        'style'       => 'font-size:.875rem;line-height:1.8',
                    ]) ?>
                <div class="form-hint">Each line = one bullet. Blank lines are ignored.</div>
            </div>
        </div>

        <!-- Internal / admin fields -->
        <div class="cms-card" style="border-color:#e0e7ef">
            <div class="cms-card-header" style="background:#f8fafc">
                <h5><i class="bi bi-lock me-2" style="color:#94a3b8"></i>Internal Details <span style="font-size:.72rem;color:#94a3b8;font-weight:400">(not shown on website)</span></h5>
            </div>
            <div class="cms-card-body" style="display:grid;grid-template-columns:1fr 1fr;gap:1rem">
                <div>
                    <label class="form-label-cms">Internal Price (₹)</label>
                    <div class="form-hint" style="margin-bottom:.4rem">For your reference only — not displayed publicly.</div>
                    <?= $form->field($model, 'price', ['template' => '{input}{error}'])
                        ->textInput(['class' => 'cms-input', 'type' => 'number', 'step' => '0.01', 'min' => '0', 'placeholder' => '2999']) ?>
                </div>
                <div id="duration-wrap">
                    <label class="form-label-cms">Duration (months)</label>
                    <div class="form-hint" style="margin-bottom:.4rem">Shown on the card if filled.</div>
                    <?= $form->field($model, 'duration_months', ['template' => '{input}{error}'])
                        ->textInput(['class' => 'cms-input', 'type' => 'number', 'min' => '1', 'max' => '120', 'placeholder' => '3']) ?>
                </div>
                <div>
                    <label class="form-label-cms">Program Type *</label>
                    <?= $form->field($model, 'plan_type', ['template' => '{input}{error}'])
                        ->dropDownList(Plan::typeLabels(), ['class' => 'cms-input', 'id' => 'plan-plan_type']) ?>
                    <div class="form-hint">Subscription = ongoing. One-Time = single session/package.</div>
                </div>
            </div>
        </div>

    </div>

    <!-- Right sidebar -->
    <div style="display:flex;flex-direction:column;gap:1rem">

        <!-- Icon picker -->
        <div class="cms-card">
            <div class="cms-card-header"><h5>Program Icon</h5></div>
            <div class="cms-card-body">
                <div id="icon-grid" style="display:grid;grid-template-columns:repeat(5,1fr);gap:.4rem;margin-bottom:.75rem">
                    <?php foreach ($iconOptions as $val => $label): ?>
                    <label title="<?= Html::encode($label) ?>"
                           style="display:flex;align-items:center;justify-content:center;
                                  width:100%;aspect-ratio:1;border-radius:8px;cursor:pointer;
                                  border:2px solid <?= $model->icon === $val ? 'var(--cms-active)' : '#e2e8f0' ?>;
                                  background:<?= $model->icon === $val ? '#f0fdf4' : '#f8fafc' ?>;
                                  transition:border-color .15s,background .15s"
                           class="icon-opt">
                        <input type="radio" name="Plan[icon]" value="<?= $val ?>"
                               <?= $model->icon === $val ? 'checked' : '' ?>
                               style="display:none">
                        <i class="bi <?= $val ?>" style="font-size:1.3rem;color:<?= $model->icon === $val ? 'var(--cms-active)' : '#64748b' ?>"></i>
                    </label>
                    <?php endforeach; ?>
                </div>
                <div class="form-hint">Selected icon appears on the program card.</div>
            </div>
        </div>

        <!-- Visibility -->
        <div class="cms-card">
            <div class="cms-card-header"><h5>Visibility</h5></div>
            <div class="cms-card-body">
                <label style="display:flex;align-items:center;gap:.6rem;cursor:pointer;font-size:.9rem;color:#334155;font-weight:500">
                    <?= $form->field($model, 'is_active', ['template' => '{input}'])
                        ->checkbox(['style' => 'width:17px;height:17px;accent-color:var(--cms-active);cursor:pointer']) ?>
                    Show on website
                </label>
                <div class="form-hint" style="margin-top:.5rem">Uncheck to hide without deleting.</div>
            </div>
        </div>

        <!-- Preview -->
        <div class="cms-card" style="background:#f0fdf4;border-color:#bbf7d0">
            <div class="cms-card-header" style="background:transparent;border-color:#bbf7d0"><h5 style="color:#166534">Live Preview (approximate)</h5></div>
            <div class="cms-card-body" style="padding:1rem">
                <div style="background:#fff;border-radius:14px;padding:1.2rem;border:1px solid #e2e8f0">
                    <div id="prev-icon" style="width:48px;height:48px;border-radius:50%;background:#d0edda;display:flex;align-items:center;justify-content:center;margin-bottom:.75rem">
                        <i class="bi <?= $model->icon ?: 'bi-leaf' ?>" style="font-size:1.4rem;color:#2d6a4f" id="prev-icon-i"></i>
                    </div>
                    <div id="prev-name" style="font-weight:700;color:#16291f;font-size:.95rem;margin-bottom:.3rem"><?= Html::encode($model->name ?: 'Program Name') ?></div>
                    <div id="prev-who" style="font-size:.78rem;color:#52b788;margin-bottom:.6rem"><?= Html::encode($model->who_it_for ?: 'Who it\'s for') ?></div>
                    <div id="prev-features" style="font-size:.78rem;color:#374040;line-height:1.7">
                        <?php foreach (array_slice($model->getFeatureList(), 0, 3) as $f): ?>
                        <div>✓ <?= Html::encode($f) ?></div>
                        <?php endforeach; ?>
                        <?php if (count($model->getFeatureList()) > 3): ?>
                        <div style="color:#94a3b8">+ <?= count($model->getFeatureList()) - 3 ?> more...</div>
                        <?php endif; ?>
                        <?php if (empty($model->getFeatureList())): ?>
                        <div style="color:#cbd5e1">Features will appear here</div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <button type="submit" class="btn-cms-primary" style="width:100%;padding:.8rem;font-size:.95rem;display:flex;align-items:center;justify-content:center;gap:.4rem">
            <i class="bi bi-<?= $isNew ? 'plus-circle' : 'check-circle' ?>"></i>
            <?= $isNew ? 'Create Program' : 'Save Changes' ?>
        </button>
        <a href="<?= Url::to(['/webcms/plan/index']) ?>" class="btn-cms-secondary" style="width:100%;justify-content:center">Cancel</a>
    </div>

</div>

<?php \yii\widgets\ActiveForm::end(); ?>

<script>
(function () {
    // Icon picker highlight
    document.querySelectorAll('.icon-opt').forEach(function (label) {
        label.addEventListener('click', function () {
            document.querySelectorAll('.icon-opt').forEach(function (l) {
                l.style.borderColor = '#e2e8f0';
                l.style.background  = '#f8fafc';
                l.querySelector('i').style.color = '#64748b';
            });
            label.style.borderColor = 'var(--cms-active)';
            label.style.background  = '#f0fdf4';
            label.querySelector('i').style.color = 'var(--cms-active)';
            // update preview
            var iconClass = label.querySelector('i').className.replace('font-size:1.3rem;color:var(--cms-active)', '');
            document.getElementById('prev-icon-i').className = label.querySelector('i').className;
        });
    });

    // Live preview name & who_it_for
    var nameInput   = document.getElementById('plan-name');
    var whoInput    = document.getElementById('plan-who_it_for');
    var prevName    = document.getElementById('prev-name');
    var prevWho     = document.getElementById('prev-who');
    if (nameInput) nameInput.addEventListener('input', function () { prevName.textContent = this.value || 'Program Name'; });
    if (whoInput)  whoInput.addEventListener('input',  function () { prevWho.textContent  = this.value || "Who it's for"; });
})();
</script>
