<?php
	#include("includes/dbconfig.php");
	include('my_functions.php');
 
	 
?>
		 
					<!-- Default box -->
					<?php
						if($_SESSION["connectedusergroup"] == 3 || $_SESSION["connectedusergroup"] == 4 || $_SESSION["connectedusergroup"] == 1)
						{

                            if(isset($_POST['searching'])){

                                $string = $_POST['searching']; 
                                    $results = explode(' : ', $string);
                                    
                                    $customer_id                = $results[0];
                                    $product = $product_id      =  $results[1]; 
                                    $bill = $customer_claim     = $results[2]; 
                                    $product_name              = $results[3]; 
                                    //$product_id = $results[0];  
                                    $receipt_id = 0; 
									 $customer_claim_date = date('Y-m-d');
									 
                                     //get points of customer
                                     $customer_name = '';
                                     //$customer_name =$item['customer_name'];
									 
									 
									 $items = DB::query("SELECT id, customer_name, value_date, bill, claim FROM cash_receipt where customer_id = '{$customer_id}'");
														
									$total_bills = 0;
									$total_claims = 0;
									
									foreach ($items as $item)
									{
                                          $total_claims = $total_claims + ($item['claim']/100)*($item['bill']);
                                          
									}
									
									//get previous claims
									$claims = DB::query("SELECT id, customer_id, claim from customer_claims where customer_id = '{$customer_id}'");
									$previous_claims = 0;
									
									
									foreach ($claims as $claim)
									{
										  $previous_claims = $previous_claims + $claim['claim'];
									}

									 
                                    DB::$error_handler = false;
		                            DB::$throw_exception_on_error = true;
									
									if($customer_claim <= ($total_claims - $previous_claims)){
										try
										{
										   
											$trxnConnextn = new MeekroDB();
                                            $trxnConnextn->startTransaction();
                                            ///////////////////////////////


                                            ////////////////////////////////////

                                             
			$trxnConnextn->query("SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE");
			
			$usershopcode = $trxnConnextn->queryFirstField("SELECT shop_code FROM shop WHERE id=%i LIMIT 1", $_SESSION["connecteduserbranch"]);
			 
            $usereceiptnumberseq = $trxnConnextn->queryFirstField("SELECT receipt_number FROM cash_sale_receipt_number_seq WHERE id=%i", $_SESSION["connecteduserbranch"]);
    		$trxnConnextn->query("UPDATE cash_sale_receipt_number_seq SET receipt_number=%i WHERE id=%i", ($usereceiptnumberseq + 1), $_SESSION["connecteduserbranch"]);
			$receiptnumberseq = $trxnConnextn->queryFirstField("SELECT receipt_number FROM cash_sale_receipt_number_seq WHERE id=%i", $_SESSION["connecteduserbranch"]);
			
		 
			
			$customer_name = $trxnConnextn->queryFirstField("SELECT name FROM customers WHERE id={$customer_id}");
			
            
			$receiptnumber = $usershopcode . str_pad($receiptnumberseq, 10, '0', STR_PAD_LEFT);
			
			$trxnConnextn->insert
			('cash_receipt', 
				array
				(
                    'created_date' => date("Y-m-d H:i:s"),
					'created_by' => $_SESSION["connecteduserid"],
					'value_date' => date("Y-m-d"),
					'receipt_number' => $receiptnumber,
					'shop' => $_SESSION["connecteduserbranch"],
					'customer_name' => $customer_name,
					'bill' => $bill ,
					'amount' => 0,
                    'receipt_mode' => -1,
					'customer_change' => 0,
					'memo' => 'Redemed Points',
					'customer_id' => $customer_id,
					'claim' => 0,
					'attendant' =>  $_SESSION['connecteduserid'],
					'repaired_by' => 0
					 
				)
			);
			$price_id = Item_id_from_item($product_id , $_SESSION["connecteduserbranch"]);
            $receipt_id = $insertedrecord = $trxnConnextn->insertId();
											
											$trxnConnextn->insert
											('customer_claims', 
												array
												(
													'customer_id' => $customer_id,
													'claim' => $bill,
													'date' => $customer_claim_date,
													'product_id' => $product_id,
													'personel' => $_SESSION['connecteduserid'],
                                                    'shop_id' => $_SESSION["connecteduserbranch"],
                                                    'receipt_id' => $insertedrecord,
                                                    'price_id'   =>$price_id,
                                                    'sell_price' =>$bill



												)
											);
											
										 
												$trxnConnextn->insert
												('cash_sale_item', 
													array
													(
														'created_date' => date("Y-m-d H:i:s"),
														'created_by' => $_SESSION["connecteduserid"],
														'shop' => $_SESSION["connecteduserbranch"],
														'receipt' => $insertedrecord,
														'price_id' => $price_id,
														'sell_price' => $bill,
														'quantity' => 1
													)
												);
										 
												
										 
										
											
											
											///////////////////////
	  
											$pricedata = DB::query('SELECT quantity FROM item_stock_level WHERE id ='.$product.''); 
											if(sizeof($pricedata) >0){
												 
													$quantity =  $pricedata[0]['quantity'] - 1 ;
													 
													DB::query('UPDATE item_stock_level SET quantity = '.$quantity.' WHERE id  = '.$product.'');
											}
											
											$trxnConnextn->commit();
                                             

											$insertedrecord = $trxnConnextn->insertId();
											$trxnConnextn->commit();
												
												
											
											/////////////////////
											
									?>
									<div class="row">
										<div class="col-md-12">
											<p style="padding: 5px; background-color: green; color: #fff;">Customer claim successesfully saved. 
                                               <FORM action="Claim_receipts_print.php" method='post'>
                                                <input type="hidden" name="product" value="<?php echo  $product_id ;  ?>" />
                                                <input type="hidden" name="product_name" value="<?php echo  $product_name ;  ?>" />
                                                <input type="hidden" name=" receiptfocus" value="<?php echo  $receipt_id ;  ?>" />
                                               
                                                <button class ="btn btn-info "  type="submit"> Get a receipt </button>



                                            </FORM>
                                        
                                        </p>
										</div>
									</div>
									<div>&nbsp;</div>
									<?php
										}
										catch(MeekroDBException $e)
										{
											$err = $err.$e->getMessage()."<br>";
											$err = $err.$e->getQuery()."<br>";
											$trxnConnextn->rollback();
											$errormessage = "<div class=\"alert alert-danger\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"aria-hidden=\"true\">&times;</button>" . $err . "</div>";
											$server_response[] = array('issaved' => 0, 'message' => $errormessage);
											DB::$error_handler = 'meekrodb_error_handler';
											DB::$throw_exception_on_error = false;
											echo json_encode($server_response);
											exit();
										}	
									}else{
									?>
									<div class="row">
										<div class="col-md-12">
											<p style="padding: 5px; background-color: red; color: #fff;">You are trying to make a claim (<?php echo $customer_claim.'>>>'.$customer_claim; ?>) which is more than the points your have (<?php echo ($total_claims - $previous_claims); ?>).</p>
										</div>
									</div>
									<div>&nbsp;</div>
									<?php	
									}
		
                                    
					?>
						
					<?php
						}
					?>
					
					 
					<?php
						}
						else
						{
					?>
					<div class="alert alert-danger alert-dismissable">
						<i class="glyphicon glyphicon-ban-circle"></i>
						Limited Access
					</div>
					<?php
						}
					?>
				 