<?php


namespace App\Models\UserManagement;


use App\Models\LocalizationManagement\Address;
use App\Models\LocalizationManagement\Bootables\Addressable;
use App\Models\OrderManagement\Order;
use App\Models\OrderManagement\OrderProduct;
use App\Models\PaymentManagement\Traits\HasPayments;
use App\Models\PaymentManagement\Traits\HasPaymentTransactions;
use App\Models\ProductManagement\Product;
use App\Models\ProductManagement\Rating;
use App\Models\ProductManagement\Review;
use App\Models\SettingManagement\Status;
use Database\Factories\CustomerFactory;

class Customer extends User {

    use HasPaymentTransactions,HasPayments,Addressable;

    protected $table = "user_mgt__customers";
    protected $guarded = ['id'];


    public function guardName(){
        return "customer";
    }

    protected static function newFactory(){
        return CustomerFactory::new();
    }

    public function getFullDefaultAddressAttribute(){
        $address = $this->addresses()->firstWhere("default",true);
        return ($address) ? $address->fullTitle ?? "---" : "---";
    }


    public function registerMediaCollections(): void{
        $this->addMediaCollection('customers')
            ->singleFile() // ne doit contenir qu'un seul fichier sur la collection ( utilisateur n'a qu'un seul avatar )
//            ->useFallbackUrl(get_gravatar($this->email)) // retouné lorsque getUrl = null
            ->useFallbackUrl(url("img/avatar.png")) // retouné lorsque getUrl = null
        ;

    }


    public function orders(){
        return $this->hasMany(Order::class,"customer_id")->latest();
    }

    public function ordersPaid(){
        return $this->hasMany(Order::class,"customer_id")
                   ->where('status_code', Status::PAID);
    }

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

    public function orderItems(){
        return $this->hasMany(OrderProduct::class);
    }

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

    public function ratings(){
        return $this->hasMany(Rating::class,"customer_id");
    }

    public function rated(Product $product){
        return $this->ratings->where('product_id', $product->id)->isNotEmpty();
    }

    public function productRating(Product $product){
        return $this->rated($product)
            ? $this->ratings->where('product_id', $product->id)->first()
            : null;
    }

    public function ratedPurches(){
        return $this->belongsToMany(Product::class)
            ->withPivot(['is_paid'])
            ->wherePivot('id_paid', true);

    }

    public function favProduct(){
        return $this->belongsToMany(Product::class, 'favorites')
            ->withTimestamps();
    }



}
