<?php

namespace App\Models;

use App\Enums\CommercialRegisterType;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Enums\BookingItemStatus;
use App\Enums\BookingStatus;
use App\Enums\PaymentStatus;
use Illuminate\Support\Str;
use Laravel\Sanctum\HasApiTokens;

class ServiceProvider extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, SoftDeletes, CanResetPassword;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'phone',
        'password',
        'logo',
        'nationality_id',
        'id_number',
        'commercial_register_type',
        'commercial_register_number',
        'iban',
        'bank_name',
        'commission_rate',
        'badge_url',
        'is_active',
        'category_id',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'phone_verified_at' => 'datetime',
        'password' => 'hashed',
        "commercial_register_type" => CommercialRegisterType::class
    ];

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

    public function bookingItems()
    {
        return $this->hasMany(BookingItem::class);
    }

    public function upcomingBookingItems()
    {
        return $this->hasMany(BookingItem::class)
            ->whereDate('service_date', '>=', now())
            ->whereIn('status',  [BookingItemStatus::PENDING, BookingItemStatus::CONFIRMED, BookingItemStatus::COMPLETED])
            ->whereHas('booking', function ($query) {
                $query->where('status', BookingStatus::PAID);
            });
    }

    public function cities()
    {
        return $this->belongsToMany(City::class, 'city_service_provider');
    }

    public function nationality()
    {
        return $this->belongsTo(Nationality::class);
    }

    public function reviews()
    {
        return $this->hasManyThrough(Review::class, Product::class);
    }

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function getCompletedAmountAttribute()
    {
        return $this->completedBookingItems()->sum('net_price');
    }
    public function getUnpaidCompletedAmountAttribute()
    {
        return $this->completedBookingItems()->where('is_transfered', false)->sum('net_price');
    }

    public function completedBookingItems()
    {
        return $this->bookingItems()
            ->where('status', BookingItemStatus::COMPLETED)
            ->whereHas('booking', function ($query) {
                $query->where('payment_status', PaymentStatus::PAID);
            });
    }

    //prefix email and phone with deleted-random-string after deletion
    protected static function booted()
    {
        static::deleted(function ($user) {
            $user->email = 'deleted-' . Str::random(4) . '-' . $user->email;
            $user->phone = 'deleted-' . Str::random(4) . '-' . $user->phone;
            $user->save();
        });
    }
}
