<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

class SaleBill extends Model
{
    protected $table = "sale_bills";
    protected $fillable = [
        'company_id','client_id','outer_client_id','sale_bill_number','date','time','notes'
        ,'final_total','status','paid','rest','tax','subtotal','deleted'
    ];

    protected $casts = [
        'created_at'  => 'date:Y-m-d'
    ];
    

    public function elements(){
        return $this->hasMany('\App\Models\SaleBillElement','sale_bill_id','id');
    }
    public function extras(){
        return $this->hasMany('\App\Models\SaleBillExtra','sale_bill_id','id');
    }
    public function extra(){
        return $this->hasOne('\App\Models\SaleBillExtra','sale_bill_id','id')->where('action','extra');
    }
    public function discount(){
        return $this->hasOne('\App\Models\SaleBillExtra','sale_bill_id','id')->where('action','discount');
    }
    public function company(){
        return $this->belongsTo('\App\Models\Company','company_id','id');
    }
    public function outerClient(){
        return $this->belongsTo('\App\Models\OuterClient','outer_client_id','id');
    }
    public function client(){
        return $this->belongsTo('\App\Models\Client','client_id','id');
    }



    public function getUpdatedAtAttribute(){
        $profit = 0 ;
        $elements = SaleBillElement::where('sale_bill_id',$this->id)->get();
        foreach($elements as $element){
            $product_id = $element->product_id;
            $product = Product::FindOrFail($product_id);
            $profit += (($element->quantity ) * (($element->product_price) - $product->purchasing_price * $element->elements_unit->quantity )); 
        }   
        return  $profit; 

    }


    public function scopeActive($query){
        return $query->where('deleted',0);
    }


    public function scopeDeleted($query){
        return $query->where('deleted',1);
    }

}
