<?php

namespace App\Models;

use App\Services\StripeSync;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Product extends Model
{
    protected $fillable = [
        'name', 'slug', 'description', 'image', 'price_cents', 'currency',
        'active', 'stripe_product_id', 'stripe_price_id', 'sort',
    ];

    protected $casts = ['active' => 'boolean'];

    public function scopeActive(Builder $query): Builder
    {
        return $query->where('active', true)->orderBy('sort');
    }

    public function price(): string
    {
        return Str::upper($this->currency).' $'.number_format($this->price_cents / 100, 2);
    }

    protected static function booted(): void
    {
        static::saved(fn (Product $product) => StripeSync::product($product));
    }
}
