<?php

namespace App;

use App\ExpenseCategory;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class Expense extends Model
{
    protected $guarded = [];

    public function category()
    {
        return $this->belongsTo(ExpenseCategory::class, 'category_id');
    }

     public function sub_category(){
        return $this->belongsTo(ExpenseSubCategory::class, 'sub_category_id');
    }

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

    public function bank(){
        return $this->belongsTo(BankAccount::class, 'bank_account_id');
    }

    public function todayExpense()
    {
        $expense = Expense::where('expense_date', date('Y-m-d'))->sum('amount');
        return $expense;
    }

    public function monthlyExpense()
    { 
        $expense = Expense::whereBetween('expense_date', [date('Y-m-1'),date('Y-m-t')])->sum('amount');
        return $expense;
    }

    public function totalExpense()
    {
        return Expense::sum('amount');
    }

    // filter
    public function filter($request, $expenses)
    {
        if ($request->start_date) {
            $expenses = $expenses->whereDate('expense_date', '>=' ,$request->start_date);
        } 
        
        if ($request->end_date) {
            $expenses = $expenses->whereDate('expense_date', '<=' ,$request->end_date);
        }
        
        if ($request->category) {
            $expenses = $expenses->where('category_id', $request->category);
        }
        
        if ($request->sub_category) {
            $expenses = $expenses->where('sub_category_id', $request->sub_category);
        }
        if ($request->created_by) {
            $expenses = $expenses->where('user_id', $request->created_by);
        }
        if (!$request->start_date && !$request->end_date&& !$request->category && !$request->sub_category && !$request->created_by) {
            $twoDaysAgo = now()->subDays(2)->toDateString();
            $today = now()->toDateString();
            $expenses = $expenses->whereBetween('expense_date', [$twoDaysAgo, $today]);
        }

        return $expenses;
    }
    
    public function date_to_date($start_date, $end_date)
    {
        $expenses = $this->whereBetween('expense_date', [$start_date, $end_date])->sum('amount');
        // dd($expenses);
        return $expenses;
    }
}
