<?php 
include 'header.php';
if(isset($_GET['id']))
{
    // echo $_GET['id'];
    $id=$_GET['id'];
    $Uname = $_GET['Uname'];
	$bdd=new DB();
	$row=$bdd->getOne('SELECT name,contact_no,date,chassis_no,documents,status as stb FROM customer WHERE customer_id='.$id);
    // print_r($row); // aa formate ma showw karvanuc chhe
	$bdd->disconnect();
	$year=date('Y',strtotime($row['date']));
    $month=date('m',strtotime($row['date']));
    $status = $row['stb'];
	$pathA="uploads/".$year."/".$month."/".$row['name']."-".$row['contact_no'].'-'.$row['chassis_no'];
    $documents = $row['documents'];
	// $pathA="scannedImageResult";
	// echo $path;exit;
}

if(isset($_POST['loadImages'])){
	echo "<script>location.href='".$_SERVER["HTTP_REFERER"]."';</script>";
}
if(isset($_POST['clearTemp'])){
	$filesa=glob('ScanedImagesTemp/*');
	foreach($filesa as $fils){
		if(is_file($fils)){
			unlink($fils);
		}else{
			echo 'photos is not deleted from ScanedImagesTemp';
		}
	}
	echo "<script>location.href='".$_SERVER["HTTP_REFERER"]."';</script>";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Scan Image</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.min.js"></script>
<!--Popup Lightbox Js
<script src="js/jquery.popup.lightbox.js"></script>

<link href="css/popup-lightbox.css" rel="stylesheet" />-->
   

    <style>
        img.scanned {
            height: 200px; /** Sets the display size */
            margin-right: 12px;
        }

        div#images {
            margin-top: 20px;
        }

        .table thead tr {
    color: #707070;
    font-weight: normal;
    }
    select.form-control {
        background-color: #FFFFFF;
        border: 1px solid #D5D5D5;
        border-radius: 0 0 0 0;
        color: #858585;
    }

    .form-control {
        display: block;
        width: 100%;
        height: 34px;
        padding: 6px 12px;
        font-size: 14px;
        line-height: 1.428571429;
        background-image: none;
        box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);
        transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
    }
    .xcrud-th th {
        background: #efefef;
        white-space: nowrap;
    }
    
    </style>
</head> 
<?php



$handle = opendir(dirname(realpath(__FILE__)).'/ScanedImagesTemp/');
$scan = array();
while($file = readdir($handle))
{
	//echo $file."<br/>";
    if(strlen($file) > 7 ){
        if(strpos($file, 'not-applicable')!== false) { 
					//echo 'true';
					unlink('./ScanedImagesTemp/'.$file);
					//$GLOBALS['j']++;
				} else {
         			$scan[] = $file;
				}
    }
   
}
$j = 0;
//echo "<pre>"; print_r($scan);exit;
$flag = 'yes';
function SearchArray( $m, $file1) 
{
    foreach($file1 as $f)
    {
	  if ( strstr(trim($f),trim($m["name"]) ) ) {
		  return "yes";
		} 
       
    }
  //  echo $GLOBAL['flag'];
    if(isset($GLOBALS['scan'][$GLOBALS['j']]))
    {
        $ret1=array();
        for($i = 0 ; $i < $m["nop"] ; $i++)
        { 
            if(isset($GLOBALS['scan'][$GLOBALS['j']]))
            {
				
                $ret1[]= $GLOBALS['scan'][$GLOBALS['j']++];
				
            }
        }
        return $ret1;
    }
    return "no";
}
   ?>
<div class="row">
	<div class="col-sm-12"><button class="btn btn-blue btn-block">Scan image</button></div>
	<div class="col-sm-12">&nbsp</div>
	<div class="col-sm-12"></div>
</div>
   <table>
        <tr>
            <th>Customer Name: &nbsp</th><td><?=$row['name']?></td>
        </tr>
        <tr>
            <th>Phone No: &nbsp</th><td><?=$row['contact_no']?></td>
        </tr>
        <tr>
            <th>Chassis No: &nbsp</th><td><?=$row['chassis_no']?></td>
        </tr>

   </table>
   <br>
<form  method="post">
	<input type="submit" name="loadImages" class="btn btn-success xcrud-search-toggle" value="Load Scanned images">
	<input type="submit" name="clearTemp" class="btn btn-danger xcrud-search-toggle" value="Clear Scanned images">
</form>
   <style>
 
 table tr td .btnhide { display:none;}
  table tr:hover td .btnhide { display:inline-block;}
   </style>
  <?php  
  include "connect.php";
        $cid = $_GET['id'];

        $stat = "SELECT status FROM customer where customer_id = $cid";
        $run = $con->query($stat);
        
        $res = $run->fetch_assoc();
        $res['status'] = $row['stb'];
  ?>
   <br><br>
    <form method="post" enctype="multipart/form-data">
    <table class="xcrud-list table table-striped table-hover table-bordered">
        <thead>
            <tr class="xcrud-th">
                <th class="xcrud-column xcrud-action">Menu</th>
				<th>scanned result</th>
                <th>saved Files</th>
            </tr>
        </thead>
    <?php
    $i=0;
     $file1 = array();
	
    foreach (array_filter(glob($pathA.'/*'), 'is_file') as $file)
    {       
        $sentence = str_replace($pathA.'/', ' ', $file);
		
        $fileName = pathinfo($sentence, PATHINFO_FILENAME);
		
        $file1[]=$fileName;
    }
    if(count($file1)<=0)
    {
        $flag="no";
    }
$total_scaned_image=count($scan);
//echo "Total scaned image=".$total_scaned_image;
$file = $file1;

    $menu = array(
        array("name"=>'Declaration',"format"=>"pdf","nop"=>"$total_scaned_image","compulsory"=>'yes'),
        //array("name"=>'Form_20',"format"=>"pdf","nop"=>"1","compulsory"=>'no'),
        //array("name"=>'Permit1',"format"=>"pdf","nop"=>"1","compulsory"=>'no')
    );
	//echo "<pre>";print_r($file);print_r($menu);//exit;
$k =0;
function get_file_index($fname,$file)
{
	for($i=0;$i<count($file);$i++)
	{
		
		if(strstr(trim($file[$i]),trim($fname) ) ) {
		//	echo $i;
		  return $i;
		} 
	}
	return -1;
}

foreach($menu as $m)
{
    $s=SearchArray($m,$file); 
    //print_r($s);
    if($s=="no"){
        $GLOBALS['j']++;
    }
    echo '<tr class="hd1">
		<td>'.$m["name"].(($m["compulsory"]=="yes")?"*":"").'</td>';
    
	if($res['status'] != 'Payment'){
            echo '<td class="hd">';
    
            if($s=="yes" || ($s=="no" && $m["compulsory"]=="yes") ){
			}else{
				$img=$m["name"];
				if($m["compulsory"]=="yes"){
					$flag = 'no';
				} else {
				//echo "before".$_POST["default"];
				//echo "<pre>";print_r($s);exit;
				//if(!isset($_SESSION[$m["name"]]) || (isset($_SESSION[$m["name"]]) && $_SESSION[$m["name"]]=="")){
				
					if(!isset($_SESSION[$m["name"]]))
						$_SESSION[$m["name"]]=$m["name"];
					//echo $_SESSION[$m["name"]]."--";
					if($_SESSION[$m["name"]]!=""){
						if((!isset($_POST["default"]) || (isset($_POST["default"]) && $_POST["default"]=="Yes")) && $m["compulsory"]!="yes"){
							$source = './assets/not-applicable.jpg'; 
							// Store the path of destination file
							$fname=date("his").'not-applicable.jpg';
							$destination = './ScanedImagesTemp/'.$fname; 
							// Copy the file from /user/desktop/geek.txt 
							// to user/Downloads/geeksforgeeks.txt'
							// directory
							if( !copy($source, $destination) ) { 
								echo "File can't be copied! \n"; 
							} 
							else { 
								//echo "File has been copied! \n"; 
								
								$s=array($fname);
								$GLOBALS['j']--;
							}
						}
					}
					echo "<select id='' class='xcrud-input form-control form-control'" ;?> onchange="d_image('<?= $img?>','<?= $m["name"]?>',this.value)" ><i class="glyphicon glyphicon-remove"></i></span><?php echo "><option value='yes' ".(($_SESSION[$m["name"]]==$m["name"])?"selected":"")." >yes</option><option value='no' ".(($_SESSION[$m["name"]]=="")?"selected":"").">no</option></select>";
			}
			// echo $fname;
				//echo "<pre>";print_r($s);echo "</pre>";
				$z=0;
				if($s!="no" && count($s)>0){
					foreach($s as $s1){
						//print_r($s);
						$pop ="ScanedImagesTemp/".$s1;
						//echo $GLOBALS['j'];
						echo '<input type="hidden" id="imgv'.$i.$z.'" name="txt['.$i.'][img][]" value="'.$s1.'"/><a href="javascript:void(0);" onclick="newPopup(\''.$pop.'\');"><img style="width: 70px;" class="tempImage" id="img'.$i.$z.'" src="ScanedImagesTemp/'.$s1.'" alt=""></a>&nbsp<span id="btnTemp'.$i.$z.'"  class="btn btn-danger btnhide" ';?> onclick="delete_image('<?= $s1?>',<?= $i?>,<?= $z++ ?>)" ><i class="glyphicon glyphicon-remove"></i></span><?php 
					}
				}
            }
		echo "</td>";
	}
	
	echo "<td class='hd'>";
	
	if($s=="yes"){
        
        $x=0;
		//echo $file[get_file_index($m['name'],$file)]."<br/>";
        //$path = $pathA.'/'.trim($file[get_file_index($m['name'],$file)]).'.'.$m['format'];
        // echo '<img style="width: 70px;" src='.$path.'>' ;
		
        
        $folder = $pathA.'/';
        //echo $folder;
        $files = scandir($folder);
        $ext ="";
        //print_r($files);

        foreach ($files as $f) {
            if ($f !== '.' && $f !== '..') 
            {
                $fileName = pathinfo($f, PATHINFO_FILENAME);
                
                if(substr($fileName, 0, strlen($m['name'])) === $m['name'])
                {
                    $ext = pathinfo($f, PATHINFO_EXTENSION);
                    $path = $folder .''. $fileName . '.' . $ext ;
                    break;
                }
            }
            
        }

		if ($ext == 'jpg' || $ext == 'JPG') {
			echo '<a href="javascript:void(0);" onclick="newPopup(\''.$path.'\');">
			<img id="orgImg'.$k.'" style="width: 70px;" src="'.$path.'"></a>';
			//if($status == 'Pending')
			//{
			   if($type=="admin" && $res['status'] == 'Payment'){ 
				echo '&nbsp<span id="btnMain'.$k.'"  class="btn btn-danger btnhide" ';?>onclick="delete_file('<?= $path?>',<?= $k++?>,<?= $id?>,'<?=$m['name']?>')"style="float: right;padding: 0px;" ><i class="glyphicon glyphicon-remove"></i></span><?php 
			   }
			   elseif($type=="admin"){ 
				echo '&nbsp<span id="btnMain'.$k.'"  class="btn btn-danger btnhide" ';?>onclick="delete_orignal('<?= $path?>',<?= $k++?>,<?= $id?>,0)"style="float: right;padding: 0px;" ><i class="glyphicon glyphicon-remove"></i></span><?php 
			   }
			//}        
		}else if($ext == 'pdf'){
			echo '<a id="orgImg'.$k.'" href="'.$path.'">PDF</i></a>';
		   // if($status == 'Pending')
			//{
				if($type=="admin" && $res['status'] == 'Payment'){ 
					echo '&nbsp<span id="btnMain'.$k.'"  class="btn btn-danger btnhide" ';?>onclick="delete_file('<?= $path?>',<?= $k++?>,<?= $id?>,'<?=$m['name']?>')"style="float: right;padding: 0px;" ><i class="glyphicon glyphicon-remove"></i></span><?php 
				   }
				   
				elseif($type=="admin"){
			 echo '&nbsp<span id="btnMain'.$k.'"  class="btn btn-danger btnhide" ';?>onclick="delete_orignal('<?= $path?>',<?= $k++?>,<?= $id?>,0)" style="float: right;padding: 0px;"><i class="glyphicon glyphicon-remove"></i></span><?php 
				 }
		   // }
		}
      
    }elseif($s=="no"){
        if($m["compulsory"]=="yes"){
            $flag = 'no';
           // echo $flag;exit;
        }

        //My work ---start---
        
        // Putting input box at saved file field
        if($res['status'] != 'Payment'){
?>
            <div>
                <canvas id="pdf-canvas" style="height:5%;width:5%"></canvas>
                <div id="pre<?=$m['name']?>" style="display:none"></div>
                <input type="file" id="file<?=$m['name']?>" name="file" onchange="checkexe('<?= $m['format']?>','<?=$m['name']?>','convert[<?=$i?>]')" accept=".jpg,.pdf" required>
                <input type="button" class="button" value="Upload" id="but_upload<?=$m['name']?>" onclick="file_upload('<?= $m['name']?>','<?= $pathA?>','0','<?=$_GET['id']?>')">
				

                <div id="full<?=$m['name']?>" style="position:fixed;top:50px;width:50%;height:70%;left:260px;display:none;background:black;">
                    <div>
                        <div id="preview<?=$m['name']?>"></div>
                    </div>
                    <div>
                        <select id="pages<?=$m['name']?>" style="display:none;"></select>
                        <input type="button" class="button" value="Upload" id="but<?=$m['name']?>" onclick="file_upload('<?= $m['name']?>','<?= $pathA?>','0','<?=$_GET['id']?>')">
                        <input type="button" class="button" value="Close" id="reload<?=$m['name']?>" onclick="window.location.reload();">
                    </div> 
                </div>
            </div>

<?php
        }
    }else {
        if($res['status'] != 'Payment'){
			echo 'Not available';
            /*foreach($s as $s1){
                echo 'Not available';
            }*/
        }
    }
	
	echo "</td>";
	
    $i++;
    echo "</tr>";
}
echo '</table>';
// echo $flag;
?>

<input type="hidden" name="flag" value='<?= $flag ?>'>
<input type="hidden" name='id' value='<?= $id ?>'>
<input type="hidden" name='pathA' value='<?= $pathA ?>'>
<!--<input class="xcrud-search-toggle btn btn-primary" type="submit" value="Submit" name="btnsub" onclick="changeIssueDocs('<?=$_GET['id']?>',<?=$_GET['Uname']?>)">-->
<input class="xcrud-search-toggle btn btn-primary" type="submit" value="submitIssueDoc" name="submitIssueDoc">

</form>

</div>
<?php
if(isset($_POST['submitIssueDoc'])){
	$pathA = $_REQUEST['pathA'];
	$id=$_POST['id'];
	
	$destinationPath = $pathA.'/';
	$destinationFilePath = $pathA.'/Declaration.pdf';
	//echo "Path:".$destinationFilePath;
	$is_files_selected=false;
	$file_type="";
	
	if(file_exists($destinationPath."Declaration.jpg") || file_exists($destinationPath."Declaration.pdf")) {
		$is_files_selected=true;
		$file_type="upload";
	}
	if(!empty($_POST['txt'][0]['img'])){
		$is_files_selected=true;
		$file_type="scan";
	}
	
	if($is_files_selected){
		if($file_type=="scan"){
			include_once './generate_pdf/mpdf60/mpdf.php';
			$mpdf = new mPDF();
			$pdf = new mPDF();
			foreach($_POST['txt'][0]['img'] as $img){
				//  echo "<center><img src='ScanedImagesTemp/".$img."' /></center><pagebreak>";   
				$pdf->WriteHTML("<center><img src='ScanedImagesTemp/".$img."' /></center>");
			}  
			$pdf->Output($destinationFilePath,'F');
			
			$filesa=glob('ScanedImagesTemp/*');
			foreach($filesa as $fils){
				if(is_file($fils)){
					unlink($fils);
				}else{
					echo 'photos is not deleted from ScanedImagesTemp';
				}
			}
		}

		$date=date('Y-m-d');
		$bdd=new DB();
		
		$result=$bdd->execute("UPDATE customer SET status='FullSuccessfull',document_issue_date='$date' WHERE customer_id=".$_POST['id']);
		
		$existingEntries = $bdd->getOne("SELECT * FROM modification WHERE CId =". $_POST['id']);
		if ($existingEntries > 0) {
			$resu=$bdd->execute("UPDATE modification SET IssueDocs = $Uname,IssueDocs_date='$current_datetime' WHERE CId=".$_POST['id']);
		} else {
			$user_id = $_POST['id'];
			$insertResult = $bdd->execute("INSERT INTO modification (IssueDocs, IssueDocs_date, CId) VALUES ($Uname,'$current_datetime',$user_id)");
		}
	
		$bdd->disconnect();
		
		echo '<script>alert("file uploaded successfully");location.href="customer?status=IssueDocs"</script>';
	}else{
		echo "<script>alert('Please scan or upload file')</script>";
	}
}
?>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
    function file_upload(name, path, param1, id) {
        var formData = new FormData();
        var fileInput = document.getElementById('file' + name);
        formData.append('file', fileInput.files[0]);
        formData.append('name', name);
        formData.append('path', path);
        formData.append('param1', param1);
        formData.append('id', id);

        $.ajax({
            url: 'IssueUpload.php',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function(response) {
                alert(response);
                window.location.reload();
            },
            error: function(error) {
                console.error('Error uploading file:', error);
            }
        });
    }
	
	function delete_orignal(path,i,id,mid){
        // alert(path);
        if (confirm("Are you sure you want to delete this file ?")) {
            // $("#orgImg" + i + path).val("");
            // alert($("#orgImg" + i).val());
                $.ajax({
                    type: "GET",
                    url: "ImageLap.php",
                    data: ({
                        orgId: path,
						cust_id: id,
						menu_id:mid
                    }),
                    cache: false,
                    success: function(html) {
					//	alert(html);
                        $("#orgImg" + i).remove();
                        $("#btnMain" + i).remove();
                        window.location.reload();
                    }
                });
            } else {
                return false;
            }
    }

    function newPopup(url) {
    popupWindow = window.open(
        url,'popUpWindow','height=700,width=800,left=10,top=10,resizable=yes,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=yes')
    }


    function changeIssueDocs(id,Uname){
        var isConfirmed = confirm("Are you sure you want to send to Issue Docs?");

        if (isConfirmed) {
            dataString='action=changeIssueDocs&id='+id+'&Uname='+Uname;
            $.ajax({
                type:'POST',
                url:'ajax_data.php',
                data:dataString,
                success:function(data){
					alert(data);
                    //value=JSON.parse(data);
                    //alert(value.message);
                    //location.reload();
                }
            });
        } else {
            alert("Canceld")
        }
    }
	
	function delete_image(a,i,j){
        //alert("#imgv" + i + j);
        //$("#imgv" + i +j).val("");
        //alert(a);
        if (confirm("Are you sure you want to delete this image?")) {
            $("#imgv" + i+a).val("");
            // alert($("#imgv" + i+a).val());
                $.ajax({
                    type: "GET",
                    url: "ImageLap.php",
                    data: ({
                        id: a
                        //documents : 
				    }),
                    cache: false,
                    success: function(html) {
                   // alert(html);
				   
                        $("#img" + i +j).remove();
                        $("#btnTemp" + i +j).remove();
                        $("#imgv" + i +j).val("");
                        window.location.reload();
                    }
                });
            } else {
                return false;
            }

    }

</script>
