<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
class Expence extends Model
{
    use HasFactory;
    protected $table = "expence";


    public function fetchAllExpence($customer_id,$startDate = null, $endDate = null,)
    {
        
        $query = Expence::select('expence.*','expence_type.name','users.CustomerName')
        ->leftJoin('users', 'users.CustomerID', 'expence.customer_id')
        ->leftJoin('expence_type', 'expence_type.id', 'expence.expensetype')
        ->orderBy('expence.id', 'desc');
        if ($customer_id  && !empty($customer_id) && $customer_id != 'all') {
            $query->where('expence.customer_id', $customer_id);
        }
        if ($startDate != null && $endDate != null) {
            $startDateFormatted = date('Y-m-d', strtotime($startDate));
            $endDateFormatted = date('Y-m-d', strtotime($endDate));
            $query = $query->where(function ($query) use ($startDateFormatted, $endDateFormatted) {
                $query->where('expence.created_at', '>=', $startDateFormatted)
                    ->where('expence.created_at', '<=', $endDateFormatted);
            });
        }
       
        return $query;
    }
}