<?php
namespace App\Services;
use Carbon\Carbon;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;

use App\Models\Users\CustomersModel;
use App\Models\Sales\SalesModel;
use App\Models\Sales\SalesDetailsModel;
use App\Models\Sales\SalesItemsModel;
use App\Models\Sales\SalesItemsTaxesModel;
use App\Models\Sales\SalesChargesModel;
use App\Models\Sales\SalesPaymentsModel;
use App\Models\Sales\SalesDeliveriesModel;
use App\Models\Sales\SalesRidersModel;
use App\Models\Stores\ReservationsModel;
use App\Models\Stores\ScheduleOrderModel;
use App\Models\Sales\SalesRiderDesignationModel;
use App\Services\SalesService;

class DeliveriesService {
	/*
	 *  
	 * GET the orderS
	 */
	public function get($customer_id=null,$store_id=null,$sale_id=null,$delivery_id=null,$status=null,$types=null,$from=null,$to=null,$max=null,$order_by=array(),$track_no=null){
		$deliveries = null;
		
		$deliveries = SalesDeliveriesModel::with([
			'header_details',
			'header_details.sales_store',
			'header_details.sales_charges',
			'header_details.sales_details',
			'header_details.sales_items.item_details',
			'header_details.sales_item_modifiers_list.modifier_details',
		]);
		if($types != null){
			$deliveries->whereHas('header_details',function($query) use ($types){
				if($types != null){
					if(!is_array($types)) $query->where('transaction_type',$types);
					else $query->whereIn('transaction_type',$types);
				}
			});
		}
		if($track_no != null){
			$deliveries->whereHas('header_details',function($query) use ($track_no){
				if($track_no != null){
					if(!is_array($track_no)) $query->where('order_no',$track_no);
					else $query->whereIn('order_no',$track_no);
				}
			});
		}

		$deliveries->where(function($query) use ($customer_id){
					  	if($customer_id != null) $query->where('customer_id',$customer_id);
					  })
					  ->where(function($query) use ($sale_id,$delivery_id,$from,$to,$status,$store_id,$track_no){
					  	if($sale_id != null){
					  		if(!is_array($sale_id)) $query->where('sale_id',$sale_id);
					  		else $query->whereIn('sale_id',$sale_id);
					  	}					  	
					  	
					  	if($from != null){
					  		if(is_array($from)){
					  			if(isset($from['date']) && $from['date']){
					  				$query->where('deliver_date','>=',$from['date']);
					  			}
					  			if(isset($from['time']) && $from['time'])
					  				$query->where('deliver_time','>=',$from['time']);
					  		}
					  		else
			  					$query->where('deliver_date','>=',$from);
					  	} 
					  	if($to != null){
					  		if(is_array($to)){
					  			if(isset($to['date']) && $to['date'])
					  				$query->where('deliver_date','<=',$to['date']);
					  			if(isset($to['time']) && $to['time'])
					  				$query->where('deliver_time','<=',$to['time']);
					  		}
					  		else
			  					$query->where('deliver_date','>=',$to);
					  	} 

					  	if($status != null){
					  		if(!is_array($status)) $query->where('status',$status);
					  		else $query->whereIn('status',$status);
					  	}
					  	if($delivery_id != null){
					  		if(!is_array($delivery_id)) $query->where('id',$delivery_id);
					  		else $query->whereIn('id',$delivery_id);
					  	}
					  	if($store_id != null){
					  		if(!is_array($store_id)) $query->where('store_id',$store_id);
					  		else $query->whereIn('store_id',$store_id);
					  	}
					  });
		if(!empty($order_by)){			
			foreach ($order_by as $ob) {
				$deliveries->orderBy($ob['col'],$ob['sort']);
			}
		}
		else{
		  $deliveries->orderBy('deliver_date','DESC')->orderBy('deliver_time','ASC');			
		}
		// echo (str_replace_array('?',$deliveries->getBindings(),$deliveries->toSql()));
		if($sale_id != null && !is_array($sale_id)) return $deliveries->first();
		else {
			if($max != null)
				return $deliveries->get()->take($max);
			else
				return $deliveries->get();
		}
	}
	/*
	 *  
	 * gets next sales
	 */
	public function getReserations($customer_id=null,$sale_id=null){
		$reserves = ReservationsModel::where('customer_id',$customer_id);

		$reserves->with([
			'order_details.sales_delivery',
			'store_details.store_menus'
		]);

		$reserves->where(function($query) use ($sale_id){
			if($sale_id != null){
				$query->where('sale_id',$sale_id);
			}
		});
		if($sale_id != null){
			return $reservers->first(); // first object
		}
		else{
			return $reserves->get();// multiple object
		}
	}

	public function after($sale_id,$statuses){
		$deliveries = SalesDeliveriesModel::with(['header_details','header_details.sales_charges','header_details.sales_details','header_details.sales_items.item_details'])		
		->where('sale_id', '>', (int)$sale_id)
		->where(function($query) use ($statuses){
			$query->whereIn('status', $statuses);
		})
		->orderBy('deliver_date','DESC')->orderBy('deliver_time','ASC');	
		// echo (str_replace_array('?',$deliveries->getBindings(),$deliveries->toSql()));
		return $deliveries->get();
	}
	/*
	 *  
	 * Status update
	 */
	public function toStatus($sale_id,$status_to,$employee_id=null,$customer_id=null){
		$update = true;
		$sale_delivery = SalesDeliveriesModel::where('sale_id',$sale_id)->first();		
		if($sale_delivery){
			$last_status = $sale_delivery->status;
			$sale_delivery->status = $status_to;
			$sale_delivery->save();

			# UPDATE SALES MODEL
			if($status_to == 'accepted'){
				SalesModel::where('sale_id',$sale_id)
				->update([
					'received' 	=> 1,
					'accepted_by' => $employee_id
				]);
			}
			else if($status_to == 'dispatched'){
				SalesModel::where('sale_id',$sale_id)
				->update([
					'dispatched' => 1,
					'rider_id' => $employee_id,
				]);
				SalesRiderDesignationModel::insert([
					'rider_id' => $employee_id,
					'sale_id' => $sale_id,
					'date_added' => DB::raw('NOW()'),
					'action' => 1,
				]);
			}
			else if($status_to == 'settled'){
				SalesModel::where('sale_id',$sale_id)
				->update([
					'suspended' => 0,
				]);
			}

			# LOG
			$salesSrv = new SalesService();
			$log = [
				'store_id' 		=> $sale_delivery->store_id,
				'description' 	=> 'Sales order status updated',
				'action' 		=> 'update',
				'from' 			=> $last_status,
				'to' 			=> $status_to,
			];

			if($employee_id != null){
				$log['employee_id'] = $employee_id;
				$log['created_by'] = $employee_id;
				$log['created_type'] = 'employee';
			}
			if($customer_id != null){
				$log['customer_id'] = $customer_id;
				$log['created_by'] = $customer_id;
				$log['created_type'] = 'customer';
			}

			# NOTIFY CUSTOMER
			$notifs = ['person_id' => $sale_delivery->customer_id];
			
			$salesSrv->log($sale_id,$log,[$notifs]);
		}
		else{
			$update = false;
		}
		return $update;
	}
	/*
	 *  
	 * saves the order
	 */
	public function setRider($sale_id,$rider_id){
		$rider = null;
		$delivery = SalesDeliveriesModel::where('sale_id',$sale_id)->first();		
		if($delivery){
			$rider = new SalesRidersModel();
			$rider->sale_id = $sale_id;			
			$rider->delivery_id = $delivery->id;			
			$rider->employee_id = $rider_id;			
			$rider->started_at = DB::raw('NOW()');
			$rider->save();			
		}
		return $rider;
	}
	/*
	 *  
	 * saves the order
	 */
	public function setRiderEnd($sale_id,$rider_id,$reason=""){
		$sale_rider = SalesRidersModel::where('sale_id',$sale_id)
						->where('employee_id',$rider_id)
						->orderBy('started_at','DESC')		
						->first();		
		if($sale_rider){
			$sale_rider->ended_at = DB::raw('NOW()');
			if($reason != ""){
				$sale_rider->deleted = 1;
				$sale_rider->delete_user = $rider_id;
				$sale_rider->delete_reason = $reason;

				SalesRiderDesignationModel::where('rider_id',$rider_id)
					->where('sale_id',$sale_id)
					->update([
						'action' => 2,
					]);
			}
			else $sale_rider->is_delivered = 1;			
			$sale_rider->save();			
		}
		return $sale_rider;
	}
	/*
	 *  
	 * saves the order
	 */
	public function getRiderCurrent($rider_id){
		$delivery = SalesRidersModel::where('employee_id',$rider_id)
					->whereNull('ended_at')
					->where('is_delivered',0)
					->where('deleted',0)
					->orderBy('started_at','DESC')
					->first();		
		return $delivery;			
	}
}
