<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Request;

class Purchase extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $guarded = [];

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

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

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

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


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

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

    public function purchases()
    {
        return $this->belongsToMany(Purchase::class);
    }

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

    public function store(Request $request)
    {
        // ... your existing logic to create the purchase ...

        $newlyCreatedPurchase = Purchase::latest()->first(); // Assuming you want to edit the latest purchase

        return redirect()->route('filament.admin.resources.panel.purchases.edit', ['record' => $newlyCreatedPurchase->id]);
    }

    // Boot method to listen for events
    public static function boot()
    {
        parent::boot();

        // Update total_purch after saving a purchase
        static::saved(function ($purchase) {
            $purchase->updateTotalPurch();
        });

        // Update total_purch after deleting a purchase
        static::deleted(function ($purchase) {
            $purchase->updateTotalPurch();
        });
    }

    // Method to calculate and update total_purch
    public function updateTotalPurch()
    {
        $this->tot_imp = $this->products()->sum('total'); // Sum the 'total' field from related products
        $this->saveQuietly(); // Use saveQuietly to prevent recursive triggering of events
    }
}
