<?php

namespace App\Livewire\Billing;

use App\Enums\BillingCycle;
use App\Enums\SubscriptionStatus;
use App\Livewire\Concerns\WithDataTable;
use App\Models\SaasProduct;
use App\Models\Subscription;
use Illuminate\Database\Eloquent\Builder;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;

/**
 * Every subscription across the portfolio.
 *
 * Deliberately read-only: changing one is done from the shop it belongs to,
 * where the reviewer can see the account's whole history first.
 */
#[Title('Subscriptions')]
class Subscriptions extends Component
{
    use WithDataTable;

    #[Url(except: '')]
    public string $status = '';

    #[Url(except: '')]
    public string $cycle = '';

    #[Url(except: '')]
    public string $productId = '';

    #[Url(except: false)]
    public bool $trialsOnly = false;

    protected function searchableColumns(): array
    {
        return ['tenant.business_name', 'tenant.owner_name', 'tenant.owner_phone'];
    }

    protected function defaultSort(): array
    {
        return ['ends_at', 'asc'];
    }

    protected function sortableColumns(): array
    {
        return ['ends_at', 'starts_at', 'amount', 'created_at', 'status'];
    }

    protected function filterProperties(): array
    {
        return ['status', 'cycle', 'productId', 'trialsOnly'];
    }

    public function updatedStatus(): void
    {
        $this->resetPage();
    }

    public function updatedCycle(): void
    {
        $this->resetPage();
    }

    public function updatedProductId(): void
    {
        $this->resetPage();
    }

    public function updatedTrialsOnly(): void
    {
        $this->resetPage();
    }

    protected function baseQuery(): Builder
    {
        return Subscription::query()->with(['tenant', 'plan', 'tenant.product']);
    }

    protected function applyFilters(Builder $query): Builder
    {
        if ($this->status !== '') {
            $query->where('status', $this->status);
        }

        if ($this->cycle !== '') {
            $query->where('billing_cycle', $this->cycle);
        }

        if ($this->productId !== '') {
            $query->where('saas_product_id', (int) $this->productId);
        }

        if ($this->trialsOnly) {
            $query->where('is_trial', true);
        }

        return $query;
    }

    public function rows()
    {
        return $this->applyDataTable($this->applyFilters($this->baseQuery()))
            ->paginate($this->perPage);
    }

    public function render()
    {
        return view('livewire.billing.subscriptions', [
            'rows' => $this->rows(),
            'statuses' => SubscriptionStatus::options(),
            'cycles' => BillingCycle::options(),
            'products' => SaasProduct::orderBy('name')->pluck('name', 'id'),
        ]);
    }
}
