<?php

/**
* 
*/
class Manage
{
	
	private $con;

	function __construct()
	{
		include_once("../config/connection.php");
		$this->db = new Database();
		
	}

	public function addRecordFunction($pid, 
					  $purchase_date,
                      $purchase_party,
                      $purchase_product,
                      $drum_qty,
                      $total_drum_qty,
                      $purchase_rate,
                      $purchase_condition,
                      $purchase_dalal,
                      $purchase_remarks,
                      $tokenSecretUser){
		if ($pid==0) {
			$query="Call  sp_insert_sauda('".$purchase_date."','".$purchase_party."',".$purchase_product.",".$drum_qty.",".$total_drum_qty.",'".$purchase_rate."','".$purchase_condition."','".$purchase_dalal."','".$purchase_remarks."',$tokenSecretUser,@return)";
		}
		else{
			$query="Call  sp_update_sauda(".$pid.",'".$purchase_date."','".$purchase_party."',".$purchase_product.",".$drum_qty.",".$total_drum_qty.",'".$purchase_rate."','".$purchase_condition."','".$purchase_dalal."','".$purchase_remarks."',$tokenSecretUser,@return)";
		}
		$this->con = $this->db->connect();
		$result=mysqli_query($this->con,  $query);
		
		$row = $result->fetch_object();
		$main_id =intval($row->vintReturn);
		if ($result) {
		 	return $main_id;
		 }else{
			return 0;
		 }
	}

	public function manageSelectedRecordWithPagination($option,$sqlCount,$sql,$pno,$setRecordNumberToShow){
		$this->con = $this->db->connect();
	 	$option=trim($option);
	 	$a = $this->pagination($this->con,$sqlCount,$pno,$setRecordNumberToShow);
	 	$sql=$sql." ".$a["limit"];
	 	/*$sqlCount="SELECT COUNT(int_purchase_order_id) FROM vw_purchase_order";
		if($option==0){
			$a = $this->pagination($this->con,$sqlCount,$pno,$setRecordNumberToShow);
			$sql="SELECT `int_purchase_order_id`, `dat_transaction`, `int_number`, `txt_formatted_number`, `int_party_id`, `party_name`, `int_product_id`, `product_name`, `txt_party_document_no`, `dec_rate`, `dec_total_gross_weight`, `dec_total_tare_weight`, `dec_total_net_weight`, `dec_total_product_value`, `dec_total_freight_value`, `dec_total_tax_value`, `txt_remarks`, 
			`int_by_user_id` FROM `vw_purchase_order` order by int_purchase_order_id desc ".$a["limit"];
		}*/
		$this->con = $this->db->connect();
		$result = $this->con->query($sql) or die($this->con->error);
		$rows = array();
		if($result->num_rows > 0){
			while ($row = $result->fetch_assoc()) {
				$rows[] = $row;
				//echo $row;
			}
		}
		
		$resultCount = $this->con->query($sqlCount) or die($this->con->error);
		$totalRecords=0;
		while ($row = $resultCount->fetch_assoc()) {
				$totalRecords = $row;
				//echo $row;
			}
		return ["rows"=>$rows,"pagination"=>$a["pagination"],"totalRecords"=>$totalRecords];

	}

	private function pagination($con,$sqlQuery,$pno,$n){
		$query = $con->query($sqlQuery);
		//$row = mysqli_fetch_assoc($query);
		$row = mysqli_fetch_row($query); 
		//$totalRecords = 100000;
		$pageno = $pno;
		$numberOfRecordsPerPage = $n;
		//echo $row[0],$n;
		$last = ceil($row[0]/$numberOfRecordsPerPage);
		//echo $last;

		$pagination = "<ul class='pagination font-weight-normal'>";

		if ($last != 1) {
			if ($pageno > 1) {
				$previous = "";
				$previous = $pageno - 1;
				$pagination .= "<li class='page-item'><a class='page-link' pn='".$previous."' href='#' aria-label='Previous'> <span aria-hidden='true'>&laquo;</span><span class='sr-only'>Previous</span> </a></li></li>";
			}
			for($i=$pageno - 5;$i< $pageno ;$i++){
				if ($i > 0) {
					$pagination .= "<li class='page-item'><a class='page-link' pn='".$i."' href='#'> ".$i." </a></li>";
				}
				
			}
			$pagination .= "<li class='page-item'><a class='page-link' pn='".$pageno."' href='#' style='color:#333;'> $pageno </a></li>";
			for ($i=$pageno + 1; $i <= $last; $i++) { 
				$pagination .= "<li class='page-item'><a class='page-link' pn='".$i."' href='#'> ".$i." </a></li>";
				if ($i > $pageno + 4) {
					break;
				}
			}
			if ($last > $pageno) {
				$next = $pageno + 1;
				$pagination .= "<li class='page-item'><a class='page-link' pn='".$next."' href='#' aria-label='Next'> <span aria-hidden='true'>&raquo;</span><span class='sr-only'>Next</span> </a></li>";
			}
		}
	//LIMIT 0,10
		//LIMIT 20,10
		$limit = "LIMIT ".($pageno - 1) * $numberOfRecordsPerPage.",".$numberOfRecordsPerPage;

		return ["pagination"=>$pagination,"limit"=>$limit];
	}
	public function showNoOfRecords($rows,$pageno,$totalRecords,$setRecordNumberToShow)
	{
		$noOfSetRecords= count($rows);
		$startRecordNo=1;
		$lastRecordNo=$noOfSetRecords;
		$showRecords='<span id="showNoOfRecords">';
		foreach ($totalRecords as $totalRecord){
			$totalRecordsCount= $totalRecord;
		}
		$last = ceil($totalRecordsCount/$setRecordNumberToShow);
		if ($pageno>1){
			
				$startRecordNo	=	(($lastRecordNo*$pageno) - $noOfSetRecords) + 1;
				$lastRecordNo 	= 	$startRecordNo + $noOfSetRecords -1;
				if($pageno == $last){
					$startRecordNo	=	$totalRecordsCount - $noOfSetRecords +1;
					$lastRecordNo 	= 	$totalRecordsCount;
			}
			
		}
		$showRecords .="<li class='p-2'>Showing ".$startRecordNo."-".$lastRecordNo."  of  ".$totalRecordsCount."</span></li></ul>";
		return $showRecords;
	}
	
   	public function showRows($rows,$pageno,$pagination,$showRecords)
	{
		if (count($rows) > 0) {
		$n = (($pageno - 1) * 5)+1;
		foreach ($rows as $row) {
			
			?>
				<tr class="text-left">
			        
			      	<!--<td ><a  href="https://wa.me/91'.$row["whatsapp_number"].'?text=Date:'.date_format(date_create($row['dat_sauda']),'d-m-Y').'%20%0AProduct : '.$row['product_name'].'%20%0AParty : '.$row['party_name'].'%20%0ADrums : '.$row['int_drums'].'%20%0ARate : '.$row['dec_rate'].'%20%0A" target="new" class="dropdown-ite bn editButton w-auto mx-2 p-2 whatsapp"><i class="fas fa-whatsapp " style="font-size:18px"></i> </a></td>
			      	-->
			      	<td ><span class="date text-end"><?php echo date_format(date_create($row['dat_sauda']),'d-m-Y');?></span></td>
			      	<td><span class="product"> <?php echo $row['product_name'];?></span></td>
			        <td><a  href="#" eid="<?php echo $row['int_sauda_id']; ?>" data-toggle="modal" data-target="#myModal" class=" editButton"><span class="party_name" ><?php echo $row['party_name'];?></span></a></td>
					<td><span class="number"><?php echo $row["int_drums"]; ?></span></td>
					<td><span class="number"><?php echo $row["dec_rate"]; ?></span></td>
					<td><span class="number"><?php echo $row["txt_dalal"]; ?></span></td>
					<td><span class="party_name" ><?php echo $row["txt_condition"]; ?></span></td>
					<td><span class="number"><?php echo $row["txt_remark"]; ?></span></td>
			       	<td>
                        <a  href="#" eid="<?php echo $row['int_sauda_id']; ?>" data-toggle="modal" data-target="#myModal" class="btn editButton px-2 my-2"><i class='fas fa-edit' style='font-size:12px'></i> Edit</a>
			       		<!--<div class="dropdown show">
						  <a class="btn btn-sm" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
						    <i class='fas fa-ellipsis-v' style='font-size:12px'></i>
						  </a>

						  <div class="dropdown-menu" >
						  	<a  href="#" eid="<?php echo $row['int_purchase_order_id']; ?>" data-toggle="modal" data-target="#myModal" class="dropdown-item btn editButton"><i class='fas fa-edit' style='font-size:12px'></i> Edit</a>
						    <a href="#"  data-did="<?php echo $row['int_purchase_order_id']; ?>"  class="dropdown-item btn btn-danger btn-sm showModalDelete"><i class='fas fa-trash' style='font-size:12px'></i> Delete</a>
						    
						  </div>
						</div>-->
			       	</td>
			        
			        
			      </tr>
			<?php
		}
			$n++;
		}
		?>
			<tr  id="pagination" class="p-1"><th colspan="20"><?php echo $pagination; ?><?php echo $showRecords; ?></th></tr>
		<?php
		exit();
	}
	public function showCards($rows,$pageno,$pagination,$showRecords)
	{
		if (count($rows) > 0) {
		$n = (($pageno - 1) * 5)+1;
		?>
		<div class="row">
		<?php
		foreach ($rows as $row) {
			
			?>
				<div class=" p-2" >
					
						<div class='card card-default shadow' id="cardSelect" >
							<!-- <div class="">
									<input type="checkbox" class="form-check-input selectCmb" id="del_<?php echo $row['id']; ?>"  />
								</div> -->
							<div class="card-body">
								
								<div class="row p-1" >
									<h6 class='col-sm-10'>Gst</h6>
									<div class="col-sm-1  dropdown dropdown-sm  show   ">
									  <a class=" btn btn-sm float-right" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
									    <i class='fas fa-ellipsis-v' style='font-size:12px'></i>
									  </a>

									  <div class="dropdown-menu" >
									  	<a  href="#" eid="<?php echo $row['int_purchase_order_id']; ?>" data-toggle="modal" data-target="#myModal" class="dropdown-item btn btn-info btn-sm editButton"><i class='fas fa-edit' style='font-size:12px'></i> Edit</a>
									    <a href="#"  data-did="<?php echo $row['int_purchase_order_id']; ?>"  class="dropdown-item btn btn-danger btn-sm showModalDelete"><i class='fas fa-trash' style='font-size:12px'></i> Delete</a>
									    
									  </div>
									</div>
								</div>
								<hr class='featurette-divider mt-0'>
								<div class='card-text'>
									<p>Rate: <?php echo $row['gst_rate']; ?></p>
									
								</div>
							</div>
							<!-- <div class="card-footer ">
								

						        <a  href="#" eid="<?php echo $row['id']; ?>" data-toggle="modal" data-target="#myModal" class=" btn btn-light btn-sm edit_gst"><i class='fas fa-edit' style='font-size:12px'></i> </a>
							    <a href="#" did="<?php echo $row['id']; ?>" class=" btn btn-light btn-sm del_gst"><i class='fas fa-trash' style='font-size:12px'></i> </a>
							</div> -->
						</div>
					
				</div>
			<?php
		}
			$n++;
		}
		?>
			</div>
			<div class="row">
				<div class="col-sm-12">
					<span ><?php echo $pagination; ?><span>
						<?php echo $showRecords; ?>
				</div>
			</div>
		<?php
		exit();
	}
	public function manageSelectedRecordDrums($purchase_order_id){
		$this->con = $this->db->connect();
	 	
		
		$sql="SELECT `int_purchase_order_detail_id`, `int_purchase_order_id`, `dbl_gross_weight`, `dbl_tare_weight`, `dbl_net_weight`, `int_user_id` FROM `tbl_purchase_order_detail` where int_purchase_order_id=".$purchase_order_id;
		
		$this->con = $this->db->connect();
		$result = $this->con->query($sql) or die($this->con->error);
		$rows = array();
		if($result->num_rows > 0){
			while ($row = $result->fetch_assoc()) {
				$rows[] = $row;
				//echo $row;
			}
		}
		
		//$resultCount = $this->con->query($sqlCount) or die($this->con->error);
		
		return ["rows"=>$rows];

	}
	public function showRowsDrums($rows)
	{
		if (count($rows) > 0) {
		//$n = (($pageno - 1) * 5)+1;
			$row_id=0;
		foreach ($rows as $row) {
			$row_id=$row['int_purchase_order_detail_id'];
			?>
				<tr class="text-right" id="<?php echo $row_id; ?>">
			        <td style="display:none;"><input type="text" name="p_id" class="p_id" value="<?php echo $row['int_purchase_order_detail_id'];?>">
			        	<input type="text" name="int_purchase_order_id" class="int_purchase_order_id" value="<?php echo $row['int_purchase_order_id'];?>"></td>
			      
			      	<td class="editable"><?php echo $row['dbl_gross_weight'];?></td>
			        <td class="editable"><?php echo $row["dbl_tare_weight"]; ?></td>
			        <td class="editable"><?php echo $row["dbl_net_weight"]; ?></td>
			       	<!-- <td>
			       		<a href="#"  data-did="<?php echo $row['int_purchase_order_detail_id']; ?>"  class="dropdown-item btn btn-danger btn-sm showModalDelete"><i class='fas fa-trash' style='font-size:12px'></i> Delete</a>
			       	</td> -->
			        
			        
			      </tr>
			<?php
		}
			//$n++;
		}
		exit();
	}
	public function deleteFunction($id){
		$this->con = $this->db->connect();
		$query="Call sp_delete_purchase_order('".$id."',@return)";/*------delete drums also--------*/
		
		$result=mysqli_query($this->con,$query);
		$row = $result->fetch_object();
		$result1 =intval($row->vintReturn);
		//return $result1;
		if ($result1==$id) {
			return 1;
		}else{
			return 0;
		}

	}




	public function getSingleRecord($table,$pk,$id){
		$this->con = $this->db->connect();
		$pre_stmt = $this->con->prepare("SELECT * FROM ".$table." WHERE ".$pk."= ? LIMIT 1");
		$pre_stmt->bind_param("i",$id);
		$pre_stmt->execute() or die($this->con->error);
		$result = $pre_stmt->get_result();
		if ($result->num_rows == 1) {
			$row = $result->fetch_assoc();
		}
		return $row;
	}
	public function runQuery($query) {
		$this->con = $this->db->connect();
        $result = mysqli_query($this->con, $query);
        if($result){
	        while($row=mysqli_fetch_assoc($result)) {
	            $resultset[] = $row;
	        }
	        if(!empty($resultset))
	            return $resultset;
	    }
    }
	
}
if (isset($_GET["getParty"])) {
    $data='<select>';
	$m = new Manage();
	$rows = $m->runQuery("SELECT `int_party_id`, `txt_name` FROM `tbl_parties`");
	foreach ($rows as $row) {
		//echo "<option value='".$row["int_party_id"]."'>".$row["txt_name"]."</option>";
		$data.= "<option value='".$row["txt_name"]."'/>";
	}
	 $data.='</select>';
	echo json_encode($data);
	exit();
}
if (isset($_GET["getProduct"])) {
	$m = new Manage();
	$rows = $m->runQuery("SELECT `int_product_id`, `txt_product_name` FROM `tbl_products` where int_valid_purchase=1");
	foreach ($rows as $row) {
		echo "<option value='".$row["int_product_id"]."'>".$row["txt_product_name"]."</option>";
	}
	exit();
}
if (isset($_POST["addFunctionRequest"])) {
	$m = new Manage();
	//$rows = $m->runQuery("select int_party_id,txt_name from tbl_parties where txt_name ='".$_POST['purchase_party']."'");
	$result = $m->addRecordFunction(
							$_POST['pid'],    
							$_POST['purchase_date'],
		                    $_POST['purchase_party'],
		                    $_POST['purchase_product'],
		                    $_POST['drum_qty'],
		                    $_POST['total_drum_qty'],
		                    $_POST['purchase_rate'],
		                    $_POST['purchase_condition'],
		                    $_POST['purchase_dalal'],
							$_POST['purchase_remarks'],
							$_POST['tokenSecretUser']);
							

	echo json_encode($result);
	exit();
}
/*if (isset($_POST["addFunctionRequestDrum"])) {
	$m = new Manage();
	$result = $m->addRecordFunctionDetail(
							$_POST['pid_drum'],
			                $_POST['pid'],
			                $_POST['purchase_drum_gross_wt'],
			                $_POST['purchase_drum_tare_wt'],
			                $_POST['purchase_drum_net_wt'],
							$_POST['tokenSecretUser']);

	echo json_encode($result);
	exit();
}*/

if (isset($_GET["manageListRequest"])) {
    if($_GET['search_option']){
		$search_option=$_GET['search_option'];
		$sqlCount="SELECT count(int_sauda_id) FROM `vw_sauda` where party_name LIKE '".$search_option."%' or product_name LIKE '".$search_option."%'";
		$sql="SELECT * FROM `vw_sauda` where party_name LIKE '".$search_option."%' or product_name LIKE '".$search_option."%' order by `int_sauda_id` desc";
	}
	else{
		$sqlCount="SELECT count(int_sauda_id) FROM `vw_sauda` ";
		$sql="SELECT * FROM `vw_sauda` order by `int_sauda_id` desc";
	}
	$m = new Manage();
	$result = $m->manageSelectedRecordWithPagination($_GET["search_option"],$sqlCount,$sql,$_GET["pageno"],20);
	$rows = $result["rows"];
	$pageno=$_GET["pageno"];
	$pagination = $result["pagination"];
	$totalRecords=$result['totalRecords'];
	$showRecords = $m->showNoOfRecords($rows,$_GET["pageno"],$totalRecords,50);
	$m->showRows($rows,$pageno,$pagination,$showRecords);
	
	
}
if (isset($_GET["manageCardRequest"])) {
	$m = new Manage();
	if($_GET['search_option']){
		$search_option=$_GET['search_option'];
		$qry="SELECT * FROM `vw_sauda` where party_name LIKE '".$search_option."%' or product_name LIKE '".$search_option."%' order by `int_sauda_id` desc";
	}
	else{
    	$qry="SELECT * FROM `vw_sauda` order by `int_sauda_id` desc";
	}
	$rows=$m->runQuery($qry);
	$j=0;
	$data='';
	$active='active';
	foreach($rows as $row){
		
		 if($j==0){
			 $data.='<div class="carousel-item '.$active.'">
				<div class="row">';	
		 }
		 $data.='<div class="col-sm-4 py-1">
					<div class="card card-default shadow mx-auto my-2 ">						
						<div class="card-body pb-0 px-3">
							<div class="row " >
								<div class="col-6 text-left">
									<span class="date text-end">'.date_format(date_create($row['dat_sauda']),'d-m-Y').'</span>
								</div>
								<div class="col-6 text-right">
									<span class="product">'.$row['product_name'].' </span>
								</div>
								<div class="col-6 text-left">
									<span class="party_name">  '.$row['party_name'].' </span>
								</div>
								<div class="col-6 text-right">
									<span class="party_name">Dalal : '.$row['txt_dalal'].' </span>
								</div>
								<div class="col-4 text-left">
									<span class="number"> Drums : '.$row['int_drums'].' </span>
								</div>
								<div class="col-8 text-right">
									<span class="number"> Quantity: '.$row['dec_quantity'].' kg </span>
								</div>
								<div class="col-12 text-left">
									<span class="number"> Rate : '.$row['dec_rate'].' per kg </span>
								</div>
								
							</div>
						</div>
						<div class="card-footer bg-tranaparent flex-end row m-0 flex-row-reverse">
							<a  href="https://wa.me/91'.$row["whatsapp_number"].'?text=Date:'.date_format(date_create($row['dat_sauda']),'d-m-Y').'%20%0AProduct : '.$row['product_name'].'%20%0AParty : '.$row['party_name'].'%20%0ADrums : '.$row['int_drums'].'%20%0ARate : '.$row['dec_rate'].'%20%0A"  target="new" class="dropdown-ite bn editButton w-auto mx-2 whatsapp"><i class="fas fa-whatsapp" style="font-size:18px"></i> </a>
							
							<a  href="#" eid='.$row['int_sauda_id'].' data-toggle="modal" data-target="#myModal" class="dropdown-ite bt editButton w-auto mx-2 "><i class="fas fa-edit" style="font-size:18px"></i> </a>
						</div>
					</div>
			</div>';
			$j++;
			$active='';
		if($j==3){
			 $j=0;
		 }
		 if($j==0){
			 $data.='</div>
			 </div>';
		 }
		 
	}
	echo $data;
}
//Delete 
if (isset($_GET["deleteRequest"])) {//////////////////////////for deleting particular record
	$m = new Manage();
	$result = $m->deleteFunction($_GET["id"]);
	echo $result;
	exit();
}
if (isset($_GET["deleteSelectedRequest"])) {//////////////////////////for deleting particular record
	$m = new Manage();
	
	if(isset($_GET['records'])) {
		
		foreach ($_GET['records'] as $id) {
			$result = $m->deleteFunction($id);
			//echo $id;
		}
	}
	
	echo $result;
	exit();
}
//Update Product
if (isset($_GET["fillFormRequest"])) {////////////////////////////for filling edit form
	$m = new Manage();
	$result = $m->getSingleRecord("vw_sauda","int_sauda_id",$_GET["id"]);
	if($result['dat_sauda']){
	    $date=$result['dat_sauda'];	    
		$result['dat_sauda']=date_format(date_create($date),'Y-m-d');
	}
//	echo 'date_format(date_create('.$date.'),"Y-m-d")';
	echo json_encode($result);
	exit();
}

?>