<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Business extends Model
{
    use HasFactory;

    protected $fillable = [
        'shop_name',
        'phone_number',
        'password',
        'plan_type',
        'plan_expiry_date',
        'plan_status',
    ];

    protected $hidden = [
        'password',
    ];

    protected function casts(): array
    {
        return [
            'password' => 'hashed',
            'plan_expiry_date' => 'date',
        ];
    }

    public function products(): HasMany
    {
        return $this->hasMany(Product::class);
    }

    public function sales(): HasMany
    {
        return $this->hasMany(Sale::class);
    }

    public function repairs(): HasMany
    {
        return $this->hasMany(Repair::class);
    }

    public function secondHands(): HasMany
    {
        return $this->hasMany(SecondHand::class);
    }

    public function unlockOrders(): HasMany
    {
        return $this->hasMany(UnlockOrder::class);
    }

    public function payments(): HasMany
    {
        return $this->hasMany(Payment::class);
    }

    public function subscriptions(): HasMany
    {
        return $this->hasMany(Subscription::class);
    }

    public function isExpired(): bool
    {
        return $this->plan_expiry_date?->isPast() ?? false;
    }

    public function canCreateOrder(): bool
    {
        if ($this->isExpired()) {
            return false;
        }

        if ($this->plan_type === 'free') {
            $ordersToday = $this->unlockOrders()->whereDate('created_at', today())->count();
            return $ordersToday < 5;
        }

        return true;
    }

    public function assignTrial(): void
    {
        $this->update([
            'plan_type' => 'free',
            'plan_expiry_date' => today()->addDays(7),
            'plan_status' => 'active',
        ]);

        $this->subscriptions()->create([
            'plan_type' => 'free',
            'expiry_date' => today()->addDays(7),
            'status' => 'active',
        ]);
    }
}