<?php

/** @var yii\web\View $this */
/** @var yii\data\ActiveDataProvider $dataProvider */
/** @var string|null $filterCategory */
/** @var string|null $search */

use yii\bootstrap5\Html;
use yii\grid\GridView;
use yii\helpers\Url;

$this->title = 'Food Library';
$categories = ['Grains', 'Protein', 'Dairy', 'Vegetable', 'Fruit', 'Fat', 'Beverage', 'Other'];
?>

<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
    <form method="GET" class="d-flex gap-2 flex-wrap">
        <input type="text" name="search" class="form-control form-control-sm"
               placeholder="Search food…" value="<?= Html::encode($search) ?>" style="width:180px">
        <select name="category" class="form-select form-select-sm" style="width:160px">
            <option value="">All Categories</option>
            <?php foreach ($categories as $cat): ?>
                <option value="<?= $cat ?>" <?= $filterCategory === $cat ? 'selected' : '' ?>><?= $cat ?></option>
            <?php endforeach; ?>
        </select>
        <button class="btn btn-sm btn-outline-primary">Filter</button>
    </form>
    <div class="d-flex gap-2">
        <a href="<?= Url::to(['/food-library/import']) ?>" class="btn btn-sm btn-outline-secondary">
            <i class="bi bi-upload"></i> CSV Import
        </a>
        <a href="<?= Url::to(['/food-library/create']) ?>" class="btn btn-sm btn-primary">
            <i class="bi bi-plus-lg"></i> Add Food
        </a>
    </div>
</div>

<div class="card">
    <div class="card-body p-0">
        <?= GridView::widget([
            'dataProvider' => $dataProvider,
            'tableOptions' => ['class' => 'table table-hover mb-0 small'],
            'columns' => [
                ['class' => 'yii\grid\SerialColumn'],
                'name',
                'category',
                'serving_size',
                ['attribute' => 'calories', 'value' => fn($m) => number_format($m->calories, 0) . ' kcal'],
                ['attribute' => 'protein',  'value' => fn($m) => $m->protein . 'g'],
                ['attribute' => 'carbs',    'value' => fn($m) => $m->carbs . 'g'],
                ['attribute' => 'fats',     'value' => fn($m) => $m->fats . 'g'],
                [
                    'label'  => 'Scope',
                    'format' => 'raw',
                    'value'  => fn($m) => $m->isGlobal()
                        ? '<span class="badge bg-secondary">Global</span>'
                        : '<span class="badge bg-info text-dark">Private</span>',
                ],
                [
                    'class'      => 'yii\grid\ActionColumn',
                    'template'   => '{update} {delete}',
                    'urlCreator' => fn($action, $model) => Url::to(["food-library/{$action}", 'id' => $model->id]),
                ],
            ],
        ]) ?>
    </div>
</div>
