<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Auth;
use DB;
use EF;

class Vendor extends Model
{
   	private $generic_condition;

    public function __construct()
    {
       $this->setCondition(['is_recycle' => '0']);
    }

    public function setCondition($condition = [])
    {
        $this->generic_condition = $condition;
    }

    public function getCondition()
    {
        return $this->generic_condition;
    }

    public function getAllVendors()
    {
    	return Vendor::where($this->getCondition())->orderBy('id','asc')->get();
    }

    public function getVendorById($id)
    {
    	return Vendor::find($id);
    }

    public function storeVendor($object)
    {
    	DB::transaction(function () use ($object) {

    		$vendor = new Vendor;

    		// $vendor->user_id 	  = $object['user'];

            $vendor->branch_id    = Auth::user()->branch_id;
    		$vendor->vendor_name  = $object['vendor_name'];
    		$vendor->code 		  = $object['code'];
    		$vendor->ntn_number   = $object['ntn_number'];
    		$vendor->person_name  = $object['person_name'];
    		$vendor->cnic 		  = $object['cnic'];
    		$vendor->contact      = $object['contact'];
    		$vendor->photo        = EF::uploadFile($object['photo']);

    		$vendor->save();

    		return with($vendor);

		});
    }

    public function updateVendor($object)
    {
        DB::transaction(function () use ($object) 
        {
            $vendor =  Vendor::find($object['vendor']);

            if(isset($vendor->id))
            {
    			$vendor->vendor_name  = $object['vendor_name'];
	    		$vendor->code 		  = $object['code'];
	    		$vendor->ntn_number   = $object['ntn_number'];
	    		$vendor->person_name  = $object['person_name'];
	    		$vendor->cnic 		  = $object['cnic'];
	    		$vendor->contact      = $object['contact'];
    		    $vendor->photo        = EF::uploadFile($object['photo'],$vendor->photo);


	    		$vendor->update();

            }

            

            return with($vendor);

        });
    }

    public function removeVendor($id)
    {
        DB::transaction(function () use ($id) 
        {
            $vendor =  Vendor::find($id);

            if(isset($vendor->id))
            {
                $vendor->is_recycle = '1';

                $vendor->update();

            }

            return with($vendor);

        });
    }



    public function countUnpaidVendorPayments()
    {
        return $this->hasMany(VendorPayment::class)->where($this->getCondition() + ['status' => 'Unpaid'])->count();
    }

    public function countTotalVendorPayments()
    {
        return $this->hasMany(VendorPayment::class)->where($this->getCondition())->count();
        
    }

    public function branch()
    {
        return $this->belongsTo(Branch::class,'branch_id')->where($this->getCondition())->withDefault();
        
    }


}
