<?php
namespace App\Services;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

use App\Models\Sales\SalesOrderNosModel;
use App\Models\Sales\SalesModel;

class SalesOrderNosService {
	
	public $trans_type_codes = array(
		'delivery' => 'DLV',
		'pickup' => 'PKU',
		'reservation' => 'RVN',
		'dinein' => 'DIN',
	);

	public function getNextOrderNo($brand_id,$loc_id,$trans_type){
		$next_order_no = null;
		$get_next_ref = SalesOrderNosModel::where('brand_id',$brand_id)->where('loc_id',$loc_id)->where('trans_type',$trans_type)->first();
		
		if(!$get_next_ref){
			// CREATE NEEW TRANS TYPE TO GET NEXT REF
			$next_order_no = $this->createTransType($brand_id,$loc_id,$trans_type); 
		}
		else{
			// RETURN THE NEXT REF NO
			$next_order_no = $get_next_ref->next_order_no;
			// CHECK IF REF IS ALREADY USED
			if(SalesModel::where('brand_id',$brand_id)->where('loc_id',$loc_id)->where('trans_type',$trans_type)->where('ref_no',$next_order_no)->exists()){
				$next_order_no = $this->updateNextTransType($brand_id,$loc_id,$trans_type,$next_order_no);
			}
		}

		return $next_order_no;
	}

	public function updateNextTransType($brand_id,$loc_id,$type,$last_ref){
		DB::beginTransaction();
		try{
			$new_ref = $this->addTransRef($last_ref);
			$trans_type = SalesOrderNosModel::where('brand_id',$brand_id)->where('loc_id',$loc_id)->where('trans_type',$type)->first();
			$trans_type->next_order_no = $new_ref;
			$trans_type->save();
		}
		catch (\Exception $err){
		    DB::rollback();
		    $status = 500;
		    throw $err;
		}
		return $new_ref;
	}

	public function createTransType($brand_id,$loc_id,$type){
		$default_ref = '0000';

		if(isset($trans_type_codes[$type])){
			$default_ref = $type."-".$brand_id."-".$loc_id."-0000";
		}
		
		$new_ref = null;
		DB::beginTransaction();
		try{
			$new_ref = $this->addTransRef($default_ref);
			$trans_type = new SalesOrderNosModel();
			$trans_type->brand_id = $brand_id;
			$trans_type->loc_id = $loc_id;
			$trans_type->next_order_no = $new_ref;
			$trans_type->save();
		}
		catch (\Exception $err){
		    DB::rollback();
		    $status = 500;
		    throw $err;
		}
		return $new_ref;
	}

	public function addTransRef($ref){
		$new_ref = null;
		if (preg_match('/^(\D*?)(\d+)(.*)/', $ref, $result) == 1){
	        list($all, $prefix, $number, $postfix) = $result;
	        $dig_count = strlen($number); // How many digits? eg. 0003 = 4
	        $fmt = '%0' . $dig_count . 'd'; // Make a format string - leading zeroes
	        $nextval =  sprintf($fmt, intval($number + 1)); // Add one on, and put prefix back on
	        $new_ref=$prefix.$nextval.$postfix;
	    }		
	    return $new_ref;
	}
}
