<?php

/** @var yii\web\View $this */
/** @var common\models\Customer[] $customers */
/** @var common\models\DietPlan[] $templates */

use common\models\DietPlanMeal;
use yii\bootstrap5\Html;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;

$this->title = 'New Diet Plan';
?>

<form id="diet-plan-form" method="POST" action="<?= Url::to(['/diet-plan/create']) ?>">
    <?= Html::hiddenInput(Yii::$app->request->csrfParam, Yii::$app->request->csrfToken) ?>

    <div class="row g-3">
        <!-- Plan Details -->
        <div class="col-lg-4">
            <div class="card mb-3">
                <div class="card-header bg-white fw-semibold">Plan Details</div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Customer <span class="text-danger">*</span></label>
                        <select name="DietPlan[customer_id]" class="form-select" required>
                            <option value="">— Select Customer —</option>
                            <?php foreach ($customers as $c): ?>
                                <option value="<?= $c->id ?>"><?= Html::encode($c->name) ?> (<?= $c->phone ?>)</option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Title <span class="text-danger">*</span></label>
                        <input type="text" name="DietPlan[title]" class="form-control" placeholder="e.g. Weight Loss Plan - Week 1" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea name="DietPlan[description]" class="form-control" rows="3" placeholder="Goals, notes…"></textarea>
                    </div>
                    <div class="row g-2">
                        <div class="col-6">
                            <label class="form-label">Start Date</label>
                            <input type="date" name="DietPlan[start_date]" class="form-control">
                        </div>
                        <div class="col-6">
                            <label class="form-label">End Date</label>
                            <input type="date" name="DietPlan[end_date]" class="form-control">
                        </div>
                    </div>
                    <div class="mt-3">
                        <label class="form-label">Status</label>
                        <select name="DietPlan[status]" class="form-select">
                            <option value="draft">Draft</option>
                            <option value="active">Active</option>
                        </select>
                    </div>
                    <div class="mt-3 form-check">
                        <input class="form-check-input" type="checkbox" name="DietPlan[is_template]" value="1" id="is-template"
                               onchange="document.getElementById('template-name-wrap').style.display=this.checked?'block':'none'">
                        <label class="form-check-label" for="is-template">Save as Template</label>
                    </div>
                    <div id="template-name-wrap" style="display:none" class="mt-2">
                        <input type="text" name="DietPlan[template_name]" class="form-control" placeholder="Template name">
                    </div>

                    <?php if (!empty($templates)): ?>
                    <hr>
                    <label class="form-label">Load from Template</label>
                    <select id="template-selector" class="form-select">
                        <option value="">— Load Template —</option>
                        <?php foreach ($templates as $t): ?>
                            <option value="<?= $t->id ?>"><?= Html::encode($t->template_name ?: $t->title) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Nutrition Summary -->
            <div class="card">
                <div class="card-header bg-white fw-semibold">Daily Totals</div>
                <div class="card-body">
                    <div class="row text-center g-2" id="nutrition-summary">
                        <div class="col-6">
                            <div class="fs-5 fw-bold text-danger" id="total-cal">0</div>
                            <div class="text-muted small">kcal</div>
                        </div>
                        <div class="col-6">
                            <div class="fs-5 fw-bold text-primary" id="total-pro">0g</div>
                            <div class="text-muted small">Protein</div>
                        </div>
                        <div class="col-6">
                            <div class="fs-5 fw-bold text-warning" id="total-carb">0g</div>
                            <div class="text-muted small">Carbs</div>
                        </div>
                        <div class="col-6">
                            <div class="fs-5 fw-bold text-success" id="total-fat">0g</div>
                            <div class="text-muted small">Fats</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Meal Builder -->
        <div class="col-lg-8">
            <div class="card">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <span class="fw-semibold">Meals</span>
                    <div class="d-flex gap-2">
                        <select id="add-meal-type" class="form-select form-select-sm" style="width:180px">
                            <?php foreach (DietPlanMeal::mealTypeLabels() as $k => $v): ?>
                                <option value="<?= $k ?>"><?= $v ?></option>
                            <?php endforeach; ?>
                        </select>
                        <button type="button" class="btn btn-sm btn-primary" onclick="addMealSection()">
                            <i class="bi bi-plus-lg"></i> Add Meal
                        </button>
                    </div>
                </div>
                <div class="card-body" id="meals-container">
                    <p class="text-muted text-center py-4" id="empty-msg">
                        <i class="bi bi-clipboard2-plus fs-2 d-block mb-2 opacity-25"></i>
                        Click "Add Meal" to start building the diet plan.
                    </p>
                </div>
            </div>
        </div>
    </div>

    <div class="d-flex gap-2 mt-3">
        <button type="submit" class="btn btn-primary">
            <i class="bi bi-check-lg"></i> Save Diet Plan
        </button>
        <a href="<?= Url::to(['/diet-plan/index']) ?>" class="btn btn-outline-secondary">Cancel</a>
    </div>
</form>

<script>
const SUGGEST_URL = '<?= Url::to(['/api/diet/suggest']) ?>';
let mealIndex = 0;

const mealLabels = <?= json_encode(DietPlanMeal::mealTypeLabels()) ?>;
const mealSections = {}; // mealType => sectionEl

function addMealSection() {
    const mealType = document.getElementById('add-meal-type').value;
    const label = mealLabels[mealType] || mealType;

    document.getElementById('empty-msg')?.remove();

    if (!mealSections[mealType]) {
        const section = document.createElement('div');
        section.className = 'mb-4';
        section.id = `section-${mealType}`;
        section.innerHTML = `
            <div class="d-flex justify-content-between align-items-center mb-2">
                <h6 class="mb-0 text-uppercase text-muted fw-bold small letter-spacing-1">
                    <i class="bi bi-sunrise"></i> ${label}
                </h6>
                <button type="button" class="btn btn-sm btn-outline-success"
                    onclick="addFoodRow('${mealType}')">
                    <i class="bi bi-plus"></i> Add Food
                </button>
            </div>
            <div id="rows-${mealType}"></div>
        `;
        document.getElementById('meals-container').appendChild(section);
        mealSections[mealType] = section;
    }

    addFoodRow(mealType);
}

function addFoodRow(mealType) {
    const idx = mealIndex++;
    const container = document.getElementById(`rows-${mealType}`);

    const row = document.createElement('div');
    row.className = 'meal-row border rounded p-2 mb-2 bg-light';
    row.id = `meal-row-${idx}`;
    row.innerHTML = `
        <input type="hidden" name="meals[${idx}][meal_type]" value="${mealType}">
        <input type="hidden" name="meals[${idx}][food_library_id]" id="fid-${idx}" value="">
        <input type="hidden" name="meals[${idx}][calories]" id="cal-${idx}" value="0">
        <input type="hidden" name="meals[${idx}][protein]"  id="pro-${idx}" value="0">
        <input type="hidden" name="meals[${idx}][carbs]"    id="carb-${idx}" value="0">
        <input type="hidden" name="meals[${idx}][fats]"     id="fat-${idx}" value="0">
        <input type="hidden" name="meals[${idx}][sort_order]" value="${idx}">

        <div class="row g-2 align-items-end">
            <div class="col-md-4">
                <label class="form-label form-label-sm mb-1">Food</label>
                <div class="position-relative">
                    <input type="text" class="form-control form-control-sm food-search"
                           placeholder="Search food…"
                           autocomplete="off"
                           oninput="searchFood(this, ${idx})"
                           onfocus="searchFood(this, ${idx})"
                           id="food-search-${idx}">
                    <ul class="list-group position-absolute w-100 shadow suggest-list" id="suggest-${idx}"
                        style="display:none;z-index:1050;max-height:200px;overflow-y:auto"></ul>
                    <div class="small text-muted mt-1" id="food-info-${idx}"></div>
                </div>
                <input type="text" name="meals[${idx}][food_name]" id="fname-${idx}"
                       class="form-control form-control-sm mt-1" placeholder="Or enter manually"
                       style="display:none">
            </div>
            <div class="col-md-2">
                <label class="form-label form-label-sm mb-1">Qty</label>
                <input type="number" name="meals[${idx}][quantity]" id="qty-${idx}"
                       class="form-control form-control-sm" value="100" min="1"
                       onchange="recalcRow(${idx})">
            </div>
            <div class="col-md-2">
                <label class="form-label form-label-sm mb-1">Unit</label>
                <select name="meals[${idx}][unit]" class="form-select form-select-sm">
                    <option value="g">g</option>
                    <option value="ml">ml</option>
                    <option value="piece">piece</option>
                    <option value="tsp">tsp</option>
                    <option value="tbsp">tbsp</option>
                    <option value="cup">cup</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label form-label-sm mb-1">Notes</label>
                <input type="text" name="meals[${idx}][notes]" class="form-control form-control-sm"
                       placeholder="Preparation notes">
            </div>
            <div class="col-md-1 text-end">
                <button type="button" class="btn btn-sm btn-outline-danger"
                        onclick="removeMealRow(${idx}, '${mealType}')">
                    <i class="bi bi-trash"></i>
                </button>
            </div>
        </div>
        <div class="small text-muted mt-1 meal-nutrition" id="nutrition-${idx}"></div>
    `;

    container.appendChild(row);
}

// Per-row food data cache
const rowFoodData = {};
let searchTimers = {};

async function searchFood(input, idx) {
    const q = input.value.trim();
    const suggestEl = document.getElementById(`suggest-${idx}`);

    if (q.length < 2) { suggestEl.style.display = 'none'; return; }

    clearTimeout(searchTimers[idx]);
    searchTimers[idx] = setTimeout(async () => {
        try {
            const res  = await fetch(`${SUGGEST_URL}?q=${encodeURIComponent(q)}`);
            const data = await res.json();
            suggestEl.innerHTML = '';

            if (!data.length) {
                suggestEl.style.display = 'none';
                // Show manual input
                document.getElementById(`fname-${idx}`).style.display = 'block';
                document.getElementById(`fid-${idx}`).value = '';
                return;
            }

            data.forEach(food => {
                const li = document.createElement('li');
                li.className = 'list-group-item list-group-item-action small py-1 px-2';
                li.innerHTML = `<strong>${food.name}</strong> <span class="text-muted">${food.category || ''}</span> <small class="float-end">${food.calories} kcal</small>`;
                li.onclick = () => selectFood(idx, food, input);
                suggestEl.appendChild(li);
            });

            suggestEl.style.display = 'block';
        } catch(e) {}
    }, 300);
}

function selectFood(idx, food, input) {
    rowFoodData[idx] = food;
    input.value = food.name;
    document.getElementById(`fid-${idx}`).value    = food.id;
    document.getElementById(`fname-${idx}`).style.display = 'none';
    document.getElementById(`suggest-${idx}`).style.display = 'none';
    document.getElementById(`food-info-${idx}`).innerHTML =
        `<span class="text-success">${food.calories} kcal | P: ${food.protein}g | C: ${food.carbs}g | F: ${food.fats}g</span> <em class="text-muted">per 100g</em>`;
    recalcRow(idx);
}

function recalcRow(idx) {
    const food = rowFoodData[idx];
    if (!food) return;

    const qty    = parseFloat(document.getElementById(`qty-${idx}`)?.value || 100);
    const factor = qty / 100;

    const cal  = +(food.calories * factor).toFixed(1);
    const pro  = +(food.protein  * factor).toFixed(1);
    const carb = +(food.carbs    * factor).toFixed(1);
    const fat  = +(food.fats     * factor).toFixed(1);

    document.getElementById(`cal-${idx}`).value  = cal;
    document.getElementById(`pro-${idx}`).value  = pro;
    document.getElementById(`carb-${idx}`).value = carb;
    document.getElementById(`fat-${idx}`).value  = fat;

    document.getElementById(`nutrition-${idx}`).innerHTML =
        `<span>${cal} kcal &nbsp;|&nbsp; Protein: ${pro}g &nbsp;|&nbsp; Carbs: ${carb}g &nbsp;|&nbsp; Fats: ${fat}g</span>`;

    updateTotals();
}

function updateTotals() {
    let totCal = 0, totPro = 0, totCarb = 0, totFat = 0;
    document.querySelectorAll('[id^="cal-"]').forEach(el => { totCal += parseFloat(el.value || 0); });
    document.querySelectorAll('[id^="pro-"]').forEach(el => { totPro += parseFloat(el.value || 0); });
    document.querySelectorAll('[id^="carb-"]').forEach(el => { totCarb += parseFloat(el.value || 0); });
    document.querySelectorAll('[id^="fat-"]').forEach(el => { totFat += parseFloat(el.value || 0); });

    document.getElementById('total-cal').textContent  = totCal.toFixed(0);
    document.getElementById('total-pro').textContent  = totPro.toFixed(1) + 'g';
    document.getElementById('total-carb').textContent = totCarb.toFixed(1) + 'g';
    document.getElementById('total-fat').textContent  = totFat.toFixed(1) + 'g';
}

function removeMealRow(idx, mealType) {
    document.getElementById(`meal-row-${idx}`)?.remove();
    delete rowFoodData[idx];
    updateTotals();

    // Remove section if empty
    const rowsEl = document.getElementById(`rows-${mealType}`);
    if (rowsEl && !rowsEl.children.length) {
        document.getElementById(`section-${mealType}`)?.remove();
        delete mealSections[mealType];
    }

    if (!Object.keys(mealSections).length) {
        const empty = document.createElement('p');
        empty.id = 'empty-msg';
        empty.className = 'text-muted text-center py-4';
        empty.innerHTML = '<i class="bi bi-clipboard2-plus fs-2 d-block mb-2 opacity-25"></i>Click "Add Meal" to start building the diet plan.';
        document.getElementById('meals-container').appendChild(empty);
    }
}

// Close suggest lists on outside click
document.addEventListener('click', e => {
    if (!e.target.classList.contains('food-search')) {
        document.querySelectorAll('.suggest-list').forEach(el => el.style.display = 'none');
    }
});
</script>
