<?php
namespace App\Http\Controllers;

use App\Http\Controllers\MainController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Services\SalesService;
use App\Services\CustomersService;
use App\Services\SalesOrderNosService;
use App\Models\Sales\SalesModel;

class SalesController extends MainController{

	public $salesSrv;
	public $customersSrv;
	public $salesOrderNosSrv;
	
	public function __construct(
	  SalesService $salesSrv,
	  SalesOrderNosService $salesOrderNosSrv,
	  CustomersService $customersSrv
	){
	  $this->salesSrv = $salesSrv;
	  $this->salesOrderNosSrv = $salesOrderNosSrv;
	  $this->customersSrv = $customersSrv;
	}

	public function order(Request $request){
		$json = []; $status = 200; $error = "";

		$cart_details = json_decode($request->details);
		$cart_items = json_decode($request->items);
		$cart_charges = json_decode($request->charges);

		$mininum_order = 500;

		$customer = null;
		$employee_id = null;
		if(!$request->user && $request->temp_user){
			## IF TEMP CUSTOMER GET TEMP CUSTOMER DETAILS
			$customer = $this->customersSrv->getTempCustomer($request->temp_user,$cart_details);
		}
		else if($request->user){
			## IF CUSTOMER IS REGISTERED GET CUSTOMER DETAILS
			$customer = $this->customersSrv->getCustomer($request->user);
			if(isset($customer->login_details->id) && $customer->login_details->id != ""){
				$employee_id = $customer->login_details->id;
			}
			$json['employee_id'] = $employee_id;
		}

		## IF CUSTOMER IS NOT FOUND SEND ERROR
		if(!$customer){
			$error = "Invalid user.";
			return $this->apiResponse($json,$status,$error);
		}

		$merged = $this->salesSrv->mergeItems($cart_items);
		$items = $merged['items'];
		$cart_total = $merged['total_amount'];

		# COMPILE CHARGES
		$charges = [];
		if(!empty($cart_charges)){
			foreach ($cart_charges as $chg) {
				$charges[] = ['code'=>$chg->code,'description'=>$chg->description,'amount'=>$chg->amount]; 
				$cart_total += $chg->amount;
			}
		}

		$payments = [];
		# SAVE PAYMENT DETAILS
		if(isset($request->payments)){
			$cart_payments = json_decode($request->payments);
			foreach ($cart_payments as $py) {
				$approve_code = '';
				if(isset($py->approve_code))
					$approve_code = $py->approve_code;
				$payments[] = ['type'=>$py->type, 'amount'=>$py->amount,'code'=>$py->ref_id,'approve_code'=>$approve_code];
			}
		}

		$this->transDB(function() use(&$json,&$error,$customer,$cart_details,$items,$charges,$payments,$employee_id){
			try{
				## IF CUSTOMER IS FOUND
				$saved = $this->salesSrv->save($customer->person_id,$cart_details,$items,$charges,$payments,$employee_id);
				$json['sales'] = $saved['sales'];
				$error = $saved['error'];
			}
			catch (\Exception $e) {
				DB::rollback();
				$error_msg = $e->getMessage();
				$error_line = $e->getLine();
				$error_file = $e->getFile();
				// $this->logError($e,$this->trans_type,$request->client_id,$request->user,"Generate Workorder");
				$error = $error_msg." - ".$error_line." - ".$error_file;
				// $error = "Failed to place order.";
			}
		});

		$json['customer'] = $customer;
		$json['items'] = $cart_items;
		$json['details'] = $cart_details;

		return $this->apiResponse($json,$status,$error);
	}

	public function orderMultiple(Request $request){
		$json = []; $status = 200; $error = "";

		$cart_details = json_decode($request->details);
		$cart_items = json_decode($request->items);
		$cart_charges = json_decode($request->charges);
		$promos = json_decode($request->promos);
		$mininum_order = 500;
		$customer = null;
		$employee_id = null;
		if(!$request->user && $request->temp_user){
			## IF TEMP CUSTOMER GET TEMP CUSTOMER DETAILS
			$customer = $this->customersSrv->getTempCustomer($request->temp_user,$cart_details);
		}
		else if($request->user){
			## IF CUSTOMER IS REGISTERED GET CUSTOMER DETAILS
			$customer = $this->customersSrv->getCustomer($request->user);
			if(isset($customer->login_details->id) && $customer->login_details->id != ""){
				$employee_id = $customer->login_details->id;
			}
			$json['employee_id'] = $employee_id;
		}

		## IF CUSTOMER IS NOT FOUND SEND ERROR
		if(!$customer){
			$error = "Invalid user.";
			return $this->apiResponse($json,$status,$error);
		}

		$merged_brand_store = $this->salesSrv->mergeItemsByBrandStore($cart_items);
		// $json['merged_brand_store'] = $merged_brand_store;
		// return $this->apiResponse($json,$status,$error);

		// $items = $merged['items'];
		// $cart_total = $merged['total_amount'];

		# COMPILE CHARGES
		$charges = [];
		$km_away = 0;
		$total_tip = 0;
		if(!empty($cart_charges)){
			foreach ($cart_charges as $chg) {
				$charge = ['store_id'=>$chg->store_id,'brand_id'=>$chg->brand_id,'code'=>$chg->code,'description'=>$chg->description,'amount'=>$chg->amount]; 
				
				if(isset($chg->km_away)){
					$charge['km_away'] = (double)$chg->km_away;
					$km_away = (double)$chg->km_away;
				}

				$charges[] = $charge;
			}
		}

		$payments = [];
		# SAVE PAYMENT DETAILS
		if(isset($request->payments)){
			$cart_payments = json_decode($request->payments);
			foreach ($cart_payments as $py) {
				$approve_code = '';
				if(isset($py->approve_code))
					$approve_code = $py->approve_code;
				$payments[] = ['store_id'=>$py->store_id,'brand_id'=>$py->brand_id,'type'=>$py->type, 'amount'=>$py->amount,'code'=>$py->ref_id,'approve_code'=>$approve_code];
			}
		}

		$this->transDB(function() use(&$json,&$error,$customer,$cart_details,$merged_brand_store,$charges,$payments,$employee_id,$km_away,$promos){
			try{
				## IF CUSTOMER IS FOUND
				$sales_saved = [];
				$no_of_brands = count($merged_brand_store);
				$sale_id = 0;

				$sales = SalesModel::orderBy('sale_id', 'DESC')->first();
				if($sales){
					$sale_id = $sales->sale_id+1;
				}else{
					$sale_id++;
				}
				if(strlen((string)$sale_id) == 1){
					$zero_str = "0000";
				}elseif(strlen((string)$sale_id) == 2){
					$zero_str = "000";
				}else{
					$zero_str = "00";
				}
				foreach ($merged_brand_store as $code => $mbs) {
					// echo "<pre>",print_r($mbs),"</pre>";die();
					// if($cart_details->sale_type == 1){
					// 	$order_no = $mbs['brand_code'].'-'.$mbs['location_code'].'-1'.$zero_str.($sale_id);	
					// }else{
					if($no_of_brands > 1){
						$order_no = $mbs['location_code'].'-'.$no_of_brands.$zero_str.($sale_id);
					}else{
						$order_no = $mbs['brand_code'].'-'.$mbs['location_code'].'-1'.$zero_str.($sale_id);
						// $order_no = 'MB'.'-'.$mbs['location_code'].'-'.$no_of_brands.'00'.($sale_id+1).'-'.$mbs['brand_name'];
					}
					// }
					$store_id = $mbs['store_id'];
					$brand_id = $mbs['brand_id'];
					$cart_details->store_id = $store_id;
					$items = $mbs['items'];
					$total_amount_per_brand = $mbs['brand_total'];
					$brand_name = $mbs['brand_name'];
					$store_charges = [];
					foreach ($charges as $ch) {
						if($ch['store_id'] == $store_id && $ch['brand_id'] == $brand_id){
							$store_charges[] = $ch;
						}
					}
					$store_payments = [];
					foreach ($payments as $py) {
						if($py['store_id'] == $store_id && $py['brand_id'] == $brand_id){
							$store_payments[] = $py;
						}
					}

					$saved = $this->salesSrv->save($customer->person_id,$cart_details,$items,$store_charges,$store_payments,$employee_id,$order_no,$total_amount_per_brand,$brand_name,$km_away,$promos,$brand_id,$no_of_brands);
					if($saved['error'] != "")
						break;
					else{
						$sale = $saved['sales'];
						if($sale && $cart_details->trans_type == 'reservation'){
							$reserve_details = array(
								'brand_id' => $brand_id,
								'store_id' => $store_id,
								'first_name' => $cart_details->first_name,
								'last_name' => $cart_details->first_name,
								'email' => $cart_details->email,
								'mobile' => $cart_details->phone,
								'guest_no' => $cart_details->guest_no,
								'reserve_date' => $cart_details->deliver_date,
								'reserve_time' => $cart_details->deliver_time,
							);
							$reserve = $this->salesSrv->reserve($customer->person_id,$employee_id,(object)$reserve_details);
						}
						$sales_saved[] = $saved;
					}


				}
				$error = $saved['error'];
			}
			catch (\Exception $e) {
				DB::rollback();
				$error_msg = $e->getMessage();
				$error_line = $e->getLine();
				$error_file = $e->getFile();
				// $this->logError($e,$this->trans_type,$request->client_id,$request->user,"Generate Workorder");
				$error = $error_msg." - ".$error_line." - ".$error_file;
				// $error = "Failed to place order.";
			}
		});

		$json['customer'] = $customer;
		$json['items'] = $cart_items;
		$json['details'] = $cart_details;

		return $this->apiResponse($json,$status,$error);
	}

	public function processIpay88(Request $request){
		$base_url = env("APP_BASE_URL");
		$auth_code = "";

		// $auth_code = "1234";
		// return redirect()->to($base_url."checkout/success?code=".base64_encode($auth_code))->send();

		if(isset($request->Status) && (int)$request->Status == 1 && isset($request->AuthCode) && $request->AuthCode != ""){
			$auth_code = $request->AuthCode;
			return redirect()->to($base_url."checkout/success?code=".base64_encode($auth_code))->send();
		}
		else{
			$errordesc = $request->ErrDesc;
			return redirect()->to($base_url."checkout/fail?error=".$errordesc)->send();
		}
	}

	public function reserve(Request $request){
		$json = []; $status = 200; $error = "";

		$reserve_details = json_decode($request->details);

		$customer = null;
		$employee_id = null;
		if(!$request->user && $request->temp_user){
			## IF TEMP CUSTOMER GET TEMP CUSTOMER DETAILS
			$customer = $this->customersSrv->getTempCustomer($request->temp_user,$cart_details);
		}
		else if($request->user){
			## IF CUSTOMER IS REGISTERED GET CUSTOMER DETAILS
			$customer = $this->customersSrv->getCustomer($request->user);
			if(isset($customer->login_details->id) && $customer->login_details->id != ""){
				$employee_id = $customer->login_details->id;
			}
			$json['employee_id'] = $employee_id;
		}

		## IF CUSTOMER IS NOT FOUND SEND ERROR
		if(!$customer){
			$error = "Invalid user.";
			return $this->apiResponse($json,$status,$error);
		}

		$this->transDB(function() use(&$json,&$error,$customer,$reserve_details,$employee_id){
			try{
				## IF CUSTOMER IS FOUND
				$reserve = $this->salesSrv->reserve($customer->person_id,$employee_id,$reserve_details);
				$json['reserve'] = $reserve['reserve'];
				$error = $reserve['error'];
			}
			catch (\Exception $e) {
				DB::rollback();
				$error_msg = $e->getMessage();
				$error_line = $e->getLine();
				$error_file = $e->getFile();
				// $this->logError($e,$this->trans_type,$request->client_id,$request->user,"Generate Workorder");
				$error = $error_msg." - ".$error_line." - ".$error_file;
				// $error = "Failed to place order.";
			}
		});

		return $this->apiResponse($json,$status,$error);
	}
}
