<?php

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

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

$this->title = 'Invoices';
$statusColors = ['unpaid' => 'danger', 'partial' => 'warning', 'paid' => 'success', 'cancelled' => 'secondary'];
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <div class="d-flex gap-2 flex-wrap">
        <a href="<?= Url::to(['/invoice/index']) ?>" class="btn btn-sm <?= !$filterStatus ? 'btn-dark' : 'btn-outline-dark' ?>">All</a>
        <?php foreach (Invoice::statusLabels() as $k => $v): ?>
            <a href="<?= Url::to(['/invoice/index', 'status' => $k]) ?>"
               class="btn btn-sm <?= $filterStatus === $k ? 'btn-'.$statusColors[$k] : 'btn-outline-'.$statusColors[$k] ?>">
                <?= $v ?>
            </a>
        <?php endforeach; ?>
    </div>
    <div class="d-flex gap-2">
        <a href="<?= Url::to(['/invoice/outstanding']) ?>" class="btn btn-sm btn-outline-danger">
            <i class="bi bi-exclamation-circle"></i> Outstanding
        </a>
        <a href="<?= Url::to(['/invoice/create']) ?>" class="btn btn-primary btn-sm">
            <i class="bi bi-plus-lg"></i> New Invoice
        </a>
    </div>
</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'],
                'invoice_number',
                ['label' => 'Customer', 'value' => fn($m) => $m->customer ? $m->customer->name : '—'],
                'invoice_date',
                ['attribute' => 'total_amount', 'value' => fn($m) => '₹' . number_format($m->total_amount, 2)],
                ['attribute' => 'paid_amount',  'value' => fn($m) => '₹' . number_format($m->paid_amount, 2)],
                [
                    'label'  => 'Outstanding',
                    'format' => 'raw',
                    'value'  => fn($m) => '<span class="' . ($m->getOutstandingAmount() > 0 ? 'text-danger' : 'text-success') . '">₹' . number_format($m->getOutstandingAmount(), 2) . '</span>',
                ],
                [
                    'attribute' => 'status',
                    'format'    => 'raw',
                    'value'     => fn($m) => Html::tag('span', ucfirst($m->status), [
                        'class' => 'badge bg-' . ($statusColors[$m->status] ?? 'secondary'),
                    ]),
                ],
                [
                    'class'      => 'yii\grid\ActionColumn',
                    'template'   => '{view}',
                    'urlCreator' => fn($action, $model) => Url::to(["invoice/{$action}", 'id' => $model->id]),
                ],
            ],
        ]) ?>
    </div>
</div>
