<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Sale extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $guarded = [];

    protected $fillable = [
        'customer_id',
        'supplier_id',
        'tot',
        'date',
        'notes',
        'land_id',
        'user_id',
    ];

    public function customer()
    {
        return $this->belongsTo(Customer::class);
    }

    public function supplier()
    {
        return $this->belongsTo(Supplier::class);
    }

    public function products()
    {
        return $this->belongsToMany(Product::class)->withPivot(
            'quantity',
            'price',
            'total'
        );
    }
    public function ProductSale()
    {
        return $this->hasMany(ProductSale::class)
            // ->where('store_id', auth()->user()->store_id)
        ;
    }

    public function lands()
    {
        return $this->belongsToMany(Land::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

     // Boot method to listen for events
     public static function boot()
     {
         parent::boot();
 
         // Update total_Sale after saving a Sale
         static::saved(function ($Sale) {
             $Sale->updateTotalSale();
         });
 
         // Update total_Sale after deleting a Sale
         static::deleted(function ($Sale) {
             $Sale->updateTotalSale();
         });
     }
 
     // Method to calculate and update total_Sale
     public function updateTotalSale()
     {
         $this->tot = $this->products()->sum('total'); // Sum the 'total' field from related products
         $this->saveQuietly(); // Use saveQuietly to prevent recursive triggering of events
     }
}
