<?php

namespace App\Livewire\Datatable\Studio\Loyalty;

use App\Models\Customer;
use App\Traits\Datatable\WithAppendColumn;
use App\Traits\Datatable\WithConfiguration;
use App\Traits\Datatable\WithPrependColumn;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Blade;
use Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Views\Column;

class CustomersTable extends DataTableComponent
{
    use WithAppendColumn, WithConfiguration, WithPrependColumn;

    protected $model = Customer::class;

    public function columns(): array
    {
        return [
            Column::make('Nama', 'name')->searchable(),

            Column::make('Nomor Telepon', 'phone_number')->searchable(),

            Column::make('Jenis Kelamin', 'gender')
                ->format(fn ($value) => Blade::render(
                    '<flux:badge color="'.$value->color().'">'
                        .$value->label()
                        .'</flux:badge>'
                ))
                ->html(),

            Column::make('Member?', 'user.id')
                ->format(function ($row) {
                    $isMember = ! is_null($row);

                    $color = $isMember ? 'green' : 'red';
                    $label = $isMember ? 'Member' : 'Bukan Member';

                    return Blade::render('<flux:badge color="'.$color.'">'.$label.'</flux:badge>');
                })
                ->html(),

            Column::make('Terdaftar Sejak', 'user.created_at')
                ->format(fn ($value) => $value ? Carbon::parse($value)->diffForHumans() : '')
                ->searchable()
                ->sortable(),

            Column::make('Aksi')
                ->label(function ($row) {
                    $actions = '';

                    if (auth()->user()->can('update customer')) {
                        $actions .= view('components.datatables.edit-modal', [
                            'id' => $row->hash,
                            'method' => 'update',
                            'modalTitle' => 'Ubah Customer',
                        ])->render();
                    }

                    if (auth()->user()->can('delete customer')) {
                        $actions .= view('components.datatables.delete', [
                            'id' => $row->hash,
                            'deleteRoute' => route('studio.loyalty.customer.delete', $row->hash),
                        ])->render();
                    }

                    return $actions;
                })
                ->html(),
        ];
    }

    public function builder(): Builder
    {
        return Customer::select('customers.id', 'name', 'phone_number', 'gender')->with('user');
    }
}
