<?php

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

use common\models\Customer;
use yii\bootstrap5\Html;
use yii\grid\GridView;
use yii\helpers\Url;

$this->title = 'Customers';
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <form method="GET" class="d-flex gap-2 flex-wrap">
        <input type="text" name="search" class="form-control form-control-sm" placeholder="Search name/phone/email"
               value="<?= Html::encode($search) ?>" style="width:200px">
        <select name="type" class="form-select form-select-sm" style="width:160px">
            <option value="">All Types</option>
            <?php foreach (Customer::typeLabels() as $k => $v): ?>
                <option value="<?= $k ?>" <?= $filterType === $k ? 'selected' : '' ?>><?= $v ?></option>
            <?php endforeach; ?>
        </select>
        <button class="btn btn-sm btn-outline-primary">Filter</button>
    </form>
    <a href="<?= Url::to(['/customer/create']) ?>" class="btn btn-primary btn-sm">
        <i class="bi bi-person-plus"></i> New Customer
    </a>
</div>

<div class="card">
    <div class="card-body p-0">
        <?= GridView::widget([
            'dataProvider' => $dataProvider,
            'tableOptions' => ['class' => 'table table-hover mb-0'],
            'columns' => [
                ['class' => 'yii\grid\SerialColumn'],
                'name',
                'phone',
                'email:email',
                [
                    'attribute' => 'customer_type',
                    'format'    => 'raw',
                    'value'     => function ($model) {
                        $color = $model->customer_type === Customer::TYPE_BUSINESS ? 'warning' : 'primary';
                        $label = $model->isMember() ? 'Member' : ucfirst($model->customer_type);
                        return Html::tag('span', $label, ['class' => "badge bg-{$color} text-dark"]);
                    },
                ],
                [
                    'label' => 'Parent',
                    'value' => fn($m) => $m->parentCustomer ? $m->parentCustomer->name : '—',
                ],
                [
                    'attribute' => 'is_active',
                    'format'    => 'raw',
                    'value'     => fn($m) => $m->is_active
                        ? '<span class="badge bg-success">Active</span>'
                        : '<span class="badge bg-secondary">Inactive</span>',
                ],
                [
                    'class'      => 'yii\grid\ActionColumn',
                    'urlCreator' => fn($action, $model) => Url::to(["customer/{$action}", 'id' => $model->id]),
                ],
            ],
        ]) ?>
    </div>
</div>
