<?php

namespace App;

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

class Expense extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'vendor_id', 'category_id', 'amount','bill_number','billed_at','due_at','status','notes','expense_type','is_book'
    ];

    const UNPAID = 0;
    const PAID = 1;
    const PARTIALLY = 2;

    const CONSTRUCTION = 1;
    const SERVICE = 2;

    public function vendor() {
    	return $this->belongsTo('\App\Vendor');
    }

    public function category() {
    	return $this->belongsTo('\App\ChartOfAccount','category_id');
    }

    public function updateTable($filters) {

        $date=explode('-',$filters['date']);
        $from=Carbon::parse($date[0])->startOfDay();
        $to=Carbon::parse($date[1])->endOfDay();

        $query = Expense::whereBetween('created_at',[$from,$to]);

        foreach($filters as $key => $val) {
            if($key == 'status')
                $query = $query->where('status',$val);
            elseif($key == 'vendor')
                $query = $query->where('vendor_id',$val);
            elseif($key == 'category')
                $query = $query->where('category_id',$val);
        
        }
        
        $result = $query->get();

        $amount = $query->sum('amount');


        return ['allExpenses'=>$result,'amount'=>$amount];
    }

    public function updatePaymentTable($filters) {

        $date=explode('-',$filters['date']);
        $from=Carbon::parse($date[0])->startOfDay();
        $to=Carbon::parse($date[1])->endOfDay();

        $query = ExpensePayment::whereBetween('created_at',[$from,$to]);

        foreach($filters as $key => $val) {
            if($key == 'account')
                $query = $query->where('account_id',$val);
            elseif($key == 'vendor') {
                $query = $query->whereHas('bill',function($query) use($val){
                    $query->where('vendor_id',$val);
                });
                
        }
            elseif($key == 'category') {
                $query = $query->whereHas('bill',function($query) use($val){
                    $query->where('category_id',$val);
                });
                
        }
            

        }
        
        $result = $query->get();

        $amount = $query->sum('amount');

        return ['allPayments'=>$result,'amount'=>$amount];
    }

}
