<?php
	include("includes/dbconfig.php");
	$pagetitle = "Customers";
	require('includes/applicationtop.php');
	require('includes/applicationmenu.php');
	
	if(isset($_GET['id'])){
		$customer_id = $_GET['id'];
	}else{
		$customer_id = NULL;
	}
?>
			<!-- Content Wrapper. Contains page content -->
			<div class="content-wrapper">
				<!-- Content Header (Page header) -->
				<section class="content-header">
					<h1>Customers' Shopping History</h1>
					<ol class="breadcrumb">
					</ol>
				</section>

				<!-- Main content -->
				<section class="content">
					<!-- Default card -->
					<?php
					
						if($_SESSION["connectedusergroup"] == 3 || $_SESSION["connectedusergroup"] == 4 || $_SESSION["connectedusergroup"] == 1)
						{
					?>
					<div class="row">
						<div class="col-md-12">
							<div id="servererrormessage">
							</div>
						</div>
					</div>

					<div class="row">
						<div class="col-md-12">
							<div style="">
                                <?php
								//$customer_id =0;
                                if(isset($_POST['customer_name'])){
									$customer_id = trim($_POST['customer_id']);
                                    $customer_name = trim($_POST['customer_name']);
                                    $customer_phone = trim($_POST['customer_phone']);
                                    $customer_email = trim($_POST['customer_email']);
                                    $customer_claim = trim($_POST['customer_claim']);

                                    DB::$error_handler = false;
		                            DB::$throw_exception_on_error = true;
		
                                    try
                                    {
                                       
                                        $trxnConnextn = new MeekroDB();
                                        $trxnConnextn->startTransaction();

										$trxnConnextn->query("UPDATE customers SET name='{$customer_name}', phone='{$customer_phone}', email='{$customer_email}', claim='{$customer_claim}' where id = '{$customer_id}' ");

                                        $trxnConnextn->commit();
                                    }
                                    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();
                                    }
                                }
                                    
                                ?>
							</div>
						</div>
					</div>
				
					<div class="row">
						<div class="col-md-12">
							<div class="card card-primary" id="customerdetails"  >
								<div class="card-body">
									<?php 
									$personel  = DB::query("SELECT id , first_name , last_name FROM personnel_details  ");
									$shops  = DB::query("SELECT id ,full_name   FROM shop  ");
													
														$customers = DB::query("SELECT id, name, phone, email, claim FROM customers where id = '{$customer_id}'");
														
														foreach ($customers as $customer)
														{  
															$name = $customer['name']; 
															$phone = $customer['phone']; 
															$email = $customer['email']; 
															$claim = $customer['claim']; 
														 echo '<h3 class="alert alert-info"> Shoping History for  '.$name.' ,  '.$phone.'  </h3>';
														}
													?>
													
									
									 
									 
										<h4 class="alert alert-success">Cash Sales  </h4>
										<?php
										             $debt_total  =0;
					                                 $grand_total_spent  =0;
													 $credit_count = 0;
													 $attendants = DB::query("SELECT id, first_name , last_name FROM personnel_details  ");
												 
													
													$customers = DB::query("SELECT * FROM cash_receipt where customer_id = '{$customer_id}' ");
													if(sizeof($customers) >0){
														//print_r($customers);
														
														foreach ($customers as $customer)
														{ 
														 $grand_total_spent  += $customer['amount'];
														 
													  //if($credit_count <1){
													
													?>
										
											<table class="table table-hover"  id="">
												
												<tbody>
													
													<tr>
														<td> Date Created </td>
													
														<td><b>ReceiptNo</td>
														<td><b>Item</td>
													
														<td>Amount</td>
													
														<td>Cancelled </td>
													 
														<td>Attendant</td>
														<td>Branch</td>
													</tr>
												 
													
													<?php  
														
													  //}$credit_count += 1;
													  
													  $item_info = ' N /A'; 
													  //cash_sale_item
													 
													  $cash_item_data = DB::query('SELECT id  FROM  cash_receipt WHERE  receipt_number = "'.$customer['receipt_number'].'"  limit 1');
													 $chain  = ' '; 
													  
														
														  
														echo '<tr class = "info ">
														<td>'.$customer['created_date'].' </td>
														
														<td>'.$customer['receipt_number'].' </td>
														<td>..... </td>
														<td>'.$customer['bill'].' </td> 
														 
														<td>';
														 
														if($customer['is_cancelled'] == 1){
															echo 'Yes';
															
														}else { echo 'No';}
														
														
														echo ' </td>  <td>';
														 
														foreach($personel as $attentant){
															if($customer['attendant'] ==$attentant['id']){
																echo  $attentant['first_name'];
															}
														}
														echo ' </td><td>';
														foreach($shops as $shop){
															if($customer['shop'] ==$shop['id']){
																echo  $shop['full_name'];
															}
														}
														
														echo ' </td></tr>';
														echo '<tr> <td colspan ="7" ><b>Items under this receipt</b> </td> </tr>';
														
														$item_info2 ='';
														if(sizeof($cash_item_data) >0){
														$get_item_data = DB::query('SELECT price_id , receipt , sell_price , quantity FROM  cash_sale_item WHERE  receipt = '.$cash_item_data[0]['id'].'  ');
														 
														  $sub_total =  $quantity = $counter = 0;
														 
														if(sizeof($get_item_data) >0){
															
															echo '<tr>
																<td>#</td>
																<td  > Name   </td>
																<td> Code   </td> 
																<td> Bar code  </td>
																<td> Unit Price </td>
																<td> Quantity  </td>
																<td> Total  </td>
																</tr>
																 
																';
															foreach($get_item_data  as $item_info){
																 
														$item_data = DB::query('SELECT item  FROM  item_price WHERE  id = '.$item_info['price_id'].' ');
														 
														if(sizeof($item_data) >0){
															 
															 $item_data2 = DB::query('SELECT item_name , item_code , bar_code  FROM stock_item where  id = '.$item_data[0]['item'].' LIMIT 1 ');
															 //echo $chain  = $cash_item_data[0]['id'].'  Item id >>'.$item_data[0]['item']; 
															if(sizeof($item_data2)>0)
															{
																$quantity += $item_info['quantity'];
																$sub_total +=  $item_info['sell_price']*$item_info['quantity'];
																echo '<tr>
																<td>'.( $counter +=1).'</td>
																<td class = "alert alert-danger col-md-3  ">   '.$item_data2[0]['item_name'].' </td>
																<td>   '.$item_data2[0]['item_code'].' </td> 
																<td> '.$item_data2[0]['bar_code'].'</td>
																<td>  '.$item_info['sell_price'].'</td>
																<td>  '.$item_info['quantity'].'</td>
																<td>  '.($item_info['sell_price']*$item_info['quantity']).'</td>
																</tr>
																 
																 
																';
															
															
															     }
															
															
														      }
															}
														  }
														  
														  echo '<tr class = "danger ">
																<td   >Total</td>
																<td>    </td>
																<td>     </td> 
																<td>   </td>
																<td>   </td>
																<td> '.( $quantity).' </td>
																<td> '.$sub_total .' </td>
																</tr>
																 
																';
														}///
														
														 
														}
														 ?>
														 
														 
													</tbody>
													</table>
													<?php }  else echo 'No data found';?>
													<h4 class="alert alert-success">Credit History  </h4>
													<table class="table table-hover"  id="">
													<?php  
													
													$customers = DB::query("SELECT * FROM deposit_sale_item where customer_id = '{$customer_id}'");
													 
													
													 
														
														foreach ($customers as $customer)
														{ 
														  ?><b>
														  <tr>
														<td> Date Created </td>
													
														<td> Item</td>
													
														<td>Amount</td>
													
														<td>Quantity </td>
													 
														<td>Attendant</td>
														<td>Cancelled</td>
													</tr></b>
														  
														  <?php
														 
														 $personel  =' N/A ';
														 $cancelled  =' NO';
														 
												
														foreach ($attendants  as $attendant)
														{
															 if($attendant['id'] == $customer['created_by']){
																$personel  =  $attendant['first_name'].''.$attendant['last_name'];//first_name , last_name
																 
															 }														 
															
														}
														
														//is_cancelled
														if($customer['is_cancelled'] == 1){
															 $cancelled  =' YES';
														}
														/////
														$item_info = ' '; 
														$item_data = DB::query('SELECT item  FROM  item_price where  id = '.$customer['price_id'].' ');
														if(sizeof($item_data) >0){
															 
															 $item_data2 = DB::query('SELECT item_name , item_code , bar_code  FROM stock_item where  id = '.$item_data[0]['item'].' ');
															 
															if(sizeof($item_data2)>0)
															{
																$item_info = ' Name : '.$item_data2[0]['item_name'].' Code : '.$item_data2[0]['item_code'].' Bar code :'.$item_data2[0]['bar_code'].' ';
															}
															
															
														}
														
														/////

														
														
																echo '<tr> 
														<td>'.$customer['created_date'].' </td>
														<td>'.$item_info .' </td> 
														<td>'.$customer['sell_price'].' </td> 
														
														<td>'.$customer['quantity'].' </td>
														<td>'.$personel.' </td>
														
														
														<td> '.$cancelled.'</td>
														</tr>';
														$items = DB::query("SELECT * FROM deposit_receipt where customer_id = '{$customer_id}' and  deposit_id = ".$customer['id']."");
														
														echo '<tr >  <td colspan ="6"> Installments Recorded</td></tr>';
														
														$paid_sum = 0; 
														$count = 0;
														if(sizeof($items) > 0){
														foreach ($items as $item)
														{ if($count < 1){
															?>
																	<tr>
																	<td><b>ReceiptNo</b>  </td>
																
																	<td><b>Date paid</b>  </td>
																
																	<td><b>Ammount paid</b>  </td>
																
																	<td><b>Balance</b>  </td> 
																	 
																</tr>
														<?php
														}
														$count += 1;
														$balance  =0;
														if($item['is_cancelled']  ==0){
															$paid_sum += $item['amount'];
															$balance  = $customer['sell_price'] - $paid_sum ;
															$debt_total    += $balance;
															$grand_total_spent  += $item['amount'];
														}
															
														 
														echo '<tr> <td>'.$item['receipt_number'].' </td> 
														
														<td>'.$item['created_date'].' </td>
														<td>'.$item['amount'].' </td> 
														 
														<td>'.$balance.' </td>
														 
														</tr>';
															
															
														}
														
														   if($balance > 0){
														     echo '<tr >  <td colspan ="4"> TOTAL</td><td > '.$paid_sum.'</td><td > '.$balance.'</td>
															 <td > '; 

															 echo'</td>
															 </tr>';
														    }else  echo '<tr >  <td colspan ="6"> DEBT CLEARED CLEARED</td> </tr>'; 
														 } 
															
															
														}
														
														echo '<tr> <td colspan ="6"> <h4 class="alert alert-success">Customer Claims </h4></td> </tr>';
														
														$claims = DB::query('SELECT *from customer_claims where customer_id = '.$customer_id.'');
													if(sizeof($claims) >0){
													echo '<tr> <td> Date</td>
														
														<td> Item</td>
														<td> Branch</td>
														<td> Served by</td>
														<td>Points</td>
														 </tr>';
													foreach($claims as $claim){
														
														$branch  = $personel  =' N/A ';
														 $cancelled  =' NO';
														 
												
														foreach ($attendants  as $attendant)
														{
															 if($attendant['id'] == $claim['personel']){
																$personel  =  $attendant['first_name'].''.$attendant['last_name'];//first_name , last_name
																 
															 }														 
															
														}
														
														$item_info = ' '; 
														  $item_data2 = DB::query('SELECT item_name , item_code , bar_code  FROM stock_item where  id = '.$claim['product_id'].' ');
															 
															if(sizeof($item_data2)>0)
															{
																$item_info = ' Name : '.$item_data2[0]['item_name'].' Code : '.$item_data2[0]['item_code'].' Bar code :'.$item_data2[0]['bar_code'].' ';
															}
															if(sizeof($shops)>0){
															foreach($shops as $shop){
															if($customer['shop'] ==$shop['id']){
																$branch   = $shop['full_name'];
															  }
														     }
															}
															
															
														 
														
														echo '<tr> <td> '.$claim['date'].'</td>
														
														<td> '.$item_info.'</td>
														<td> '.$branch .'</td>
														<td> '.$personel.'</td>
														<td> '.$claim['claim'].'</td>
														<td> </td>
														 </tr>';
													}
													}
														
														echo '<tr> <td colspan ="5"> <h4>Grand Expenditure </h4></td><td>  <h4>'.$grand_total_spent.'</h4> </td> </tr>';
													 
													
												 
													 
													
									
													?>
												</tbody>
											</table>
											
									 
										
									</div>
									 
								</div><!-- /.card-body -->
							</div><!-- /.card -->
						</div>
						
						
					</div>
					<?php
						}
						else
						{
					?>
					<div class="alert alert-danger alert-dismissable">
						<i class="fa fa-ban-circle"></i>
						Limited Access
					</div>
					<?php
						}
					?>
				</section><!-- /.content -->
			</div><!-- /.content-wrapper -->

			 
		</div><!-- ./wrapper -->
		
		
	<?php include ('includes/general_footer.php')?>
		
		<script src="plugins/bert/jquery.price_format.min.js" type="text/javascript"></script>
		<script src="plugins/bert/storepos.js" type="text/javascript"></script>
		<script src="plugins/bert/cashsalesregister.js" type="text/javascript"></script>
	</body>
</html>