<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;

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

class User extends Authenticatable implements MustVerifyEmail
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory, Notifiable, HasApiTokens, SoftDeletes, CanResetPassword;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'first_name',
        'last_name',
        'email',
        'phone',
        'password',
        'firebase_token',
        'pref_lang',
        'is_active'
    ];

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

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    protected function getFullNameAttribute()
    {
        return "{$this->first_name} {$this->last_name}";
    }

    protected function getNameAttribute()
    {
        return "{$this->first_name} {$this->last_name}";
    }

    public function getRefundedAmountAttribute()
    {
        return $this->refundedBookingItems()->sum('price');
    }
    public function getUnpaidRefundedAmountAttribute()
    {
        return $this->refundedBookingItems()->where("is_transfered", false)->sum('price');
    }

    public function refundedBookingItems()
    {
        return $this->bookingItems()
            ->whereIn('status', [BookingItemStatus::CANCELED, BookingItemStatus::DECLINED])
            ->whereHas('booking', function ($query) {
                $query->where('payment_status', PaymentStatus::PAID);
            });
    }


    public function routeNotificationForFcm()
    {
        return $this->firebase_token;
    }

    public function notifications(): MorphMany
    {
        return $this->morphMany(DatabaseNotification::class, 'notifiable')
            ->orWhere(function ($query) {
                $query->where('type', PromotionNotification::class)
                    ->where("notifiable_type", self::class)
                    ->where('created_at', '>=', $this->created_at);
            })
            ->latest();
    }

    public function myNotifications(): MorphMany
    {
        return $this->morphMany(DatabaseNotification::class, 'notifiable')
            ->latest();
    }

    public function cartItems()
    {
        return $this->hasMany(CartItem::class)->whereHas('product', function ($query) {
            $query->scopes('available');
        })->with(["product" => [
            'media',
            'category',
            'cities',
        ]]);
    }

    public function bookings()
    {
        return $this->hasMany(Booking::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 favorites()
    {
        return $this->hasMany(Favorite::class);
    }

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

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

    //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();
        });
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }
}
