<?php
include 'header.php';
if(isset($_GET['id']))
{
    // echo $_GET['id'];
    $id=$_GET['id'];
	$bdd = new DB();
	$status_row=$bdd->getOne('SELECT status FROM customer WHERE customer_id='.$id);
	
	if(isset($_GET['type']) && $_GET['type']=='remove'){
		if($status_row['status']=="SemiSuccessfull")
			$bdd->execute('UPDATE customer SET status="Payment",taxReceipt=NULL WHERE customer_id='.$id);
	}
	
    $Uname = $_GET['Uname'];
	
	$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
	
	$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($_GET['type']) && $_GET['type']=='remove'){
		if($status_row['status']=="SemiSuccessfull")
			unlink($pathA.'/taxReceipt.pdf');
	}
	$bdd->disconnect();
}
//new task
//change get to post
    if(isset($_POST['clearTemp'])){
        //$filesa=glob('ScanedImagesTemp/*');
		$filesa=scandir('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>";
    }
    if(isset($_GET['loadImages'])){
        
        echo "<script>location.href='".$_SERVER["HTTP_REFERER"]."';</script>";
    }
    // if(isset($_GET['deleteAllFiles'])){
    //     $filesa=glob($pathA.'/*');
    //     foreach($filesa as $fils)
    //     {
    //         if(is_file($fils)){
    //             unlink($fils);
    //         }else{
    //             echo 'photos is not deleted from scannedImageResult';
    //         }
    //     }
    //     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>

<!--Popup Lightbox CSS-->
<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;
    }
    
	.loader-div {
		display: none;
		position: fixed;
		margin: 0px;
		padding: 0px;
		right: 0px;
		top: 0px;
		width: 100%;
		height: 100%;
		background-color: #fff;
		z-index: 30001;
		opacity: 0.8;
	}
	.loader-img {
		position: absolute;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		margin: auto;
	}
    </style>
</head> 
<?php

// echo $path;exit;

// echo $_FILES["file"]["name"][0];
// echo "<pre>";print_r($_FILES);exit;


$handle = opendir(dirname(realpath(__FILE__)).'/ScanedImagesTemp/');
$scan = array();
while($file = readdir($handle))
{
	//echo "File:".$file."  Lenght:".strlen($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) 
{
	/*echo "Menu:";
	print_r($m);
	echo "<br>file:";
	print_r($file1);*/
   /* if(count($file1)>0){

    }
    else{
        $GLOBALS['flag'] = 'no';
    }*/
    //echo "<pre>";print_r($file1);
    foreach($file1 as $f)
    {
      //  echo $m["name"]."==".$f."<br/>";
	 // echo strstr( trim($m["name"]), trim($f)).trim($m["name"]). trim($f)."<br/>";
	  if ( strstr(trim($f),trim($m["name"]) ) ) {
		  return "yes";
		} 
       /* if($m["name"] == trim($f))
        {
           
          //  $GLOBAL['flag'] == 'yes';
            return "yes";

        }*/
       /* else{
            echo $m["name"]."==".$f."<br/>";
            exit;
            if($m["compulsory"] == 'yes')
            {
               // exit;
                $GLOBALS['flag'] = 'no';
            }
        }*/
      //  exit;
    }
  //  echo $GLOBAL['flag'];
    if(isset($GLOBALS['scan'][$GLOBALS['j']]))
    {
        $ret1=array();
        for($i = 0 ; $i < $m["nop"] ; $i++)
        { 
            if(isset($GLOBALS['scan'][$GLOBALS['j']]))
            {
				/*if (strpos($GLOBALS['scan'][$GLOBALS['j']], 'not-applicable.jpg')) { 
					//echo 'true';
					$GLOBALS['j']++;
				} else {*/
				//echo $GLOBALS['scan'][$GLOBALS['j']];exit;
                $ret1[]= $GLOBALS['scan'][$GLOBALS['j']++];
				//}
            }
        }
        //print_r($ret1);
        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">
		<input type="hidden" name="TaxInvoice_img" readonly>
		<input type="hidden" name="DISCLAIMER_img" readonly>
		<div class="loader-div">
			<img class="loader-img" src="load.gif" />
		</div>
		<div id="compareResultDiv"></div>
	</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>
<!-- <div class="row"> -->
    <!-- <div class="col-sm-1">
        <button type="button" class="btn btn-primary xcrud-search-toggle btn btn-default" onclick="scanToJpg();">Scan</button>
    </div>
    <div class="col-sm-1">
        <form id="form1" action="uploadImages.php" method="POST" enctype="multipart/form-data" target="_blank" >
            <input type="button" class="btn btn-success xcrud-search-toggle btn btn-default" name="sbtbtn" value="Submit" onclick="submitFormWithScannedImages();">
        </form>
    </div>
    <div id="images"></div> -->
        <!-- <div id="server_response"></div> -->
<!-- </div> -->
   <!-- <br><br> -->
   <style>
  /* .btnhide {
  display: none;
}

.hd1:hover + .btnhide {
  display: block;
  color: red;
}*/
 table tr td .btnhide { display:none;}
  table tr:hover td .btnhide { display:inline-block;}
   </style>
  <?php
  include "connect.php";
  if($status == 'Pending' || $status == 'Upload'){?>
    <form  method="post">
    Default:<select name="default"><option <?= (isset($_POST["default"]) && $_POST["default"]=="Yes"?"selected":""); ?>>Yes</option>
    <option  <?= (isset($_POST["default"]) && $_POST["default"]=="No"?"selected":""); ?>>No</option></select><br/>
        <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">
        <!-- <input type="submit" name="deleteAllFiles" class="btn btn-danger xcrud-search-toggle" value="Delete Saved files"> -->
		<button type="button" class="btn btn-info" onclick="getCompareData()">Compare</button>
    </form>
  <?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 action="converted.php" method="post" enctype="multipart/form-data">
		<input type="hidden" name="hidden_compare_data" id="hidden_compare_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>
        <?php
            if($res['status'] != 'Payment' && $res['status'] != 'hsrp' && $res['status'] != 'Insp')
            {
        ?>
                <th>scanned result</th>
        <?php
            }
        ?>
                <th>saved Files</th>
                <th>Convert</th>
        <?php 
            if($res['status'] != 'Payment' && $res['status'] != 'hsrp')
            {    
        ?>        
                <th>Name</th>
        <?php 
            }   
        ?>
            </tr>
        </thead>
    <?php
    $i=0;
     $file1 = array();//('TaxtInvoice', 'Form20', 'Form21', 'Form22');
	
    foreach (array_filter(glob($pathA.'/*'), 'is_file') as $file)
    {       
		$sentence = str_replace($pathA.'/', ' ', $file);
         //$fileName = trim($sentence,'.pdf || .jpg');
        $fileName = pathinfo($sentence, PATHINFO_FILENAME);
		$fileName= trim($fileName);
		if($res['status'] == 'Payment' ){
			//echo "<br>Payemnt<br>";
			if($fileName=='taxReceipt')
				$file1[]=$fileName;
		}else if($res['status'] == 'Insp'){
			if($sentence=='SMCtaxReceipt')
				$file1[]=$fileName;
		}else{			
			$file1[]=$fileName;
		}
    }
    if(count($file1)<=0)
    {
        $flag="no";
    }

//echo "<pre>";print_r($file1);exit;
$file = $file1;
//echo "<pre>";print_r($file);exit;
// $menu = array(
//         array("name"=>'TaxtInvoice',"format"=>"jpg","nop"=>"1"),
//         array("name"=>'Form20',"format"=>"pdf","nop"=>"3"),
//         array("name"=>'Form21',"format"=>"jpg","nop"=>"1"),
//         array("name"=>'Form22',"format"=>"jpg","nop"=>"1"),
//         array("name"=>'Disclamer',"format"=>"jpg","nop"=>"3"),
//         array("name"=>'sign',"format"=>"jpg","nop"=>"1")
//     );


if($status == 'Payment'){
    $menu = array(
        array("name"=>'taxReceipt',"format"=>"pdf","nop"=>"1","compulsory"=>'yes')
    );
}else if($status == 'hsrp' || $status == 'Insp'){
    $menu = array(
        array("name"=>'SMCtaxReceipt',"format"=>"pdf","nop"=>"1","compulsory"=>'yes')
    );
} else {    
    $sql = "SELECT menu_id,menu_name as name, file_format as format, no_of_page as nop,compulsory FROM menu";
    $result = $con->query($sql);
	
    if ($result->num_rows > 0) {
       // $row = $result->fetch_assoc();
       // echo "<pre>";print_r($row);exit;
        while($row = $result->fetch_assoc()) {
			//print_r($row);
            if($status=='Pending'){
                if($row['name']=='IdProof' || $row['name']=='AddressProof' || $row['name']=='SIGN')
                {
                    $menu[]=$row;
                }
            } else if($status=='Upload'){
                $menu[]=$row;
            }
        }
        //echo "<pre>";print_r($menu);
       
    }
}
	//echo "<pre>";print_r($file);print_r($menu);//exit;
$k =0;
function get_file_index($fname,$file)
{
	for($i=0;$i<count($file);$i++)
	{
		//echo strstr( trim($file[$i]),trim($fname) ).$fname.$file[$i]."<br/>";
		
		if(strstr(trim($file[$i]),trim($fname) ) ) {
		//	echo $i;
		  return $i;
		} 
	}
	return -1;
}
//echo get_file_index("IdProof",array("IdProofAadharCard"));exit;
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' && $res['status'] != 'hsrp' && $res['status'] != 'Insp')
            {
            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")
					 {
//echo "in";
						 $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>";
						if($m["name"]=="TaxInvoice"){
							echo "<script>document.getElementsByName('TaxInvoice_img')[0].value='".$s[0]."'</script>";
						}else if($m["name"]=="DISCLAIMER"){
							echo "<script>document.getElementsByName('DISCLAIMER_img')[0].value='".$s[0]."'</script>";
						}
                        $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($res['status'] == 'Payment')
    {
        if($s!="yes")
        {

?>
            <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?>]')">
                <input type="button" class="button" value="Upload" id="but_upload<?=$m['name']?>" onclick="file_upload('convert[<?=$i?>]','<?= $m['name']?>','<?= $pathA?>','null','<?=$_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('convert[<?=$i?>]','<?= $m['name']?>','<?= $pathA?>','null','<?=$_GET['id']?>')">
                        <input type="button" class="button" value="Close" id="reload<?=$m['name']?>" onclick="window.location.reload();">
                    </div> 
                </div>
            </div>

<?php
        }
    }
	
	if($res['status'] == 'hsrp' || $res['status'] == 'Insp')
    {
        if($s!="yes")
        {

?>
            <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?>]')">
                <input type="button" class="button" value="Upload" id="but_upload<?=$m['name']?>" onclick="file_upload('convert[<?=$i?>]','<?= $m['name']?>','<?= $pathA?>','null','<?=$_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('convert[<?=$i?>]','<?= $m['name']?>','<?= $pathA?>','null','<?=$_GET['id']?>')">
                        <input type="button" class="button" value="Close" id="reload<?=$m['name']?>" onclick="window.location.reload();">
                    </div> 
                </div>
            </div>

<?php
        }
    }
    
    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);
        if($status == 'Payment')
        {
    
            $valuesToCheck = array('taxReceipt.pdf');

            $regexPattern = '/^(taxReceipt)\./';

            $matchingFiles = preg_grep($regexPattern, $files);

            if (count($matchingFiles) === count($valuesToCheck)) {
                include "connect.php";
				
				$current_semi_successfull_time=date('Y-m-d H:i:s',strtotime('1 hour'));
				
                $bdd = new DB();
                $row = $bdd->execute("UPDATE customer SET semi_successfull_time='$current_semi_successfull_time',status='SemiSuccessfull' WHERE customer_id=" . $id);
                $bdd->disconnect();

                $bdd=new DB();
                $existingEntries = $bdd->getOne("SELECT * FROM modification WHERE CId =". $id);
                $bdd->disconnect();
                if ($existingEntries > 0) {
                    $bdd=new DB();
                    $resu=$bdd->execute("UPDATE modification SET Payment = $Uname,Payment_date='$current_datetime' WHERE CId=".$id);
                    $bdd->disconnect();
                } else {
                    $bdd=new DB();
                    $insertResult = $bdd->execute("INSERT INTO modification (Payment,Payment_date, CId) VALUES ($Uname,'$current_datetime',$id)");
                    $bdd->disconnect();
                }

                echo "<script>alert('record updated To Semi Successfull');location.href='customer.php?status=Payment';</script>";
            }
        }


        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?>,<?= $m["menu_id"]?>)"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 
				   }if(($type=="admin" && $res['status'] == 'hsrp') || ($type=="admin" && $res['status'] == 'Insp')){
					   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
				   }else if($type=="admin"){
						echo '&nbsp<span id="btnMain'.$k.'"  class="btn btn-danger btnhide" ';?>onclick="delete_orignal('<?= $path?>',<?= $k++?>,<?= $id?>,<?= $m["menu_id"]?>)" 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' && $res['status'] != 'hsrp' && $res['status'] != 'Insp')
        {
?>
            <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?>]')">
                <input type="button" class="button" value="Upload" id="but_upload<?=$m['name']?>" onclick="file_upload('convert[<?=$i?>]','<?= $m['name']?>','<?= $pathA?>','<?= $m['menu_id']?>','<?=$_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('convert[<?=$i?>]','<?= $m['name']?>','<?= $pathA?>','<?= $m['menu_id']?>','<?=$_GET['id']?>')">
                        <input type="button" class="button" value="Close" id="reload<?=$m['name']?>" onclick="window.location.reload();">
<?php
if($type=='admin') {
?>
						<input type="button" class="button" value="Upload All Pages" id="all_page<?=$m['name']?>" onclick="file_upload_all_page('convert[<?=$i?>]','<?= $m['name']?>','<?= $pathA?>','<?= $m['menu_id']?>','<?=$_GET['id']?>')">
<?php } ?>
                    </div> 
                </div>
            </div>

<?php
        }
        // ---End---
    }
    else 
    {
        if($res['status'] != 'Payment' && $res['status'] != 'hsrp' && $res['status'] != 'Insp'){
            foreach($s as $s1)
            {
                echo 'Not available';
            }
        }
    }
    
    echo "</td>";

 echo "<td>";
            if($s=="yes" || $s=="no")
            { 
                //change
                if($s=="no")
                {
                    echo "<select name='convert[{$i}]' id='convert[{$i}]' class='xcrud-input form-control form-control'>
                    <option value='jpg' ".($m["format"]=="jpg"?"selected":"")." >Image</option>
                    <option value='pdf' ".($m["format"]=="pdf"?"selected":"").">PDF</option>
                </select>";
                }
            
            }
            else
            { 
            echo "<select name='convert[{$i}]' id='convert[{$i}]' class='xcrud-input form-control form-control'>
                <option value='jpg' ".($m["format"]=="jpg"?"selected":"")." >Image</option>
                <option value='pdf' ".($m["format"]=="pdf"?"selected":"").">PDF</option>
            </select>";
            }  

            echo "</td>";
            if($res['status'] != 'Payment' && $res['status'] != 'hsrp' && $res['status'] != 'Insp')
            {
            echo "<td>  ";
            if($s=="yes" || $s=="no")
            {}
                else{ 
            
                    //  echo "<pre>";print_r($menu);exit;
                    
            echo " 
			<input type='hidden' name='menu_id[{$i}]' value='".$m["menu_id"]."'/>
			<select name='docName[{$i}]' id='' class='xcrud-input form-control doc_name_list'>
			<option value='' > Choose Doc Name</option>";

                      foreach($menu as $m1)
                      {
            ?>
                        <option value="<?= $m1['name'] ?>" <?= ($m['name'] == $m1['name']) ? 'selected' : ''; ?> > <?= $m1['name'] ?> </option>
            <?php 
                     }  


               echo "</select>";
                } 
            
            echo "</td>";
            
            }
            $i++;
            echo "</tr>";



}
echo '</table>';
// echo $flag;
?>
<?php if($status == 'Pending' || $status == 'Upload')
{?>
<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">
<?php } ?>
</form>
<?php
if($status == 'Pending'){
if($flag=="yes"){
	echo "Ready for Next Step....";
}
else
{
	echo "Please Upload all Complusory files.";
}
}
//echo $flag;
if($status == 'Pending')
{
    if($flag=='yes')
    {
        if($documents=="Half-Done"){
            echo "<script>alert('Files Uploaded');location.href='customer.php?status=Pending';</script>";
        } else {
            include "connect.php";
            $bdd=new DB();
            $row=$bdd->execute('UPDATE customer SET documents="Half-Done" WHERE customer_id='.$id);
            $bdd->disconnect();
            echo "<script>alert('Files Uploaded');location.href='customer.php?status=Pending';</script>"; 
        }
    }
	
} else if($status == 'Upload')
{
    if($flag=='yes')
    {
        if($documents=="All-Done"){
            echo "<script>alert('All Documents Uploaded');location.href='customer.php?status=Upload';</script>";
        } else {
            include "connect.php";
            $bdd=new DB();
            $row=$bdd->execute('UPDATE customer SET documents="All-Done" WHERE customer_id='.$id);
            $bdd->disconnect();
            echo "<script>alert('All Documents Uploaded');location.href='customer.php?status=Upload';</script>";
        }
    }
	
}
	
?>
</div>

<script>
    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;
            }

    }
function d_image(img,nm,st)
    {
        //alert(nm);
        //$("#imgv" + i +j).val("");
        //alert(img);
		if(st=="no")
			img="";
		// alert($("#imgv" + i+a).val());
                $.ajax({
                    type: "GET",
                    url: "ImageLap.php",
                    data: ({
						nm:nm,
                       img:img
                    }),
                    cache: false,
                    success: function(html) {
						//alert(html);
                    }
                });
           

    }
    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 delete_file(path,i,id,name)
    {
        // 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: ({
                        location: path,
                        name: name,
                        id: id
                    }),
                    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')
    }


/*check_doc_name();
function check_doc_name()
{
	//alert(a.value);
	$('.doc_name_list').each(function(){
		 $(".doc_name_list").not(this).find("option[value="+ $(this).val() + "]").attr('disabled', true);
	});
}

   $(document).ready(function(){  
      $(".doc_name_list").on('focus', function () {
        // Store the current value on focus and on change
        previous = this.value;
    }).change(function() {   
    $(".doc_name_list").not(this).find("option[value="+ $(this).val() + "]").attr('disabled', true);
	$(".doc_name_list").find("option[value="+ previous + "]").attr('disabled', false);
  }); 
});  */



    //script to check the file exe
function checkexe(exe,i,id){
    
    const filename = event.target.files[0].name;

    const extension = filename.split('.').pop().toLowerCase();
    
    //const allowedExtensions = exe;

    var id = id;
    var selectElement = document.getElementById(id);
    var selectedValue = selectElement.value;

    if (!selectedValue.includes(extension)) {
        alert(`Please upload ` +  selectedValue  + ` file`);
        document.getElementById("but_upload" + i).disabled = true;
    }else{
        if(extension=="pdf")
        {
            document.getElementById("pages"+i).style.display = "block";
            document.getElementById("full" + i).style.display = "block";

            var sourcefile = document.getElementById('file'+i);
            var source_file = sourcefile.files[0];
            var fileReader = new FileReader();
            fileReader.onload = function() {
                var typedarray = new Uint8Array(this.result);
                pdfjsLib.getDocument({ data: typedarray }).promise.then(function(pdf) {
                    numPages = pdf.numPages;
                    var pagesSelect = document.getElementById('pages'+i);
                    pagesSelect.innerHTML = '';
                    var option = document.createElement('option');
                    option.value = "";
                    option.text = "";
                    pagesSelect.add(option);
                    for (var j = 1; j <= numPages; j++) {
                        var option = document.createElement('option');
                        option.value = j;
                        option.text = 'Page ' + j;
                        pagesSelect.add(option);
                    }
                });
            };
			
            fileReader.readAsArrayBuffer(source_file);
			
            // Preview the PDF file
            var preDiv = document.getElementById('pre'+i);
            var objectURL = URL.createObjectURL(source_file);
            preDiv.innerHTML = '<object data="' + objectURL + '" type="application/pdf" width="100%" height="500px"></object>';

            var previewDiv = document.getElementById('preview'+i);
            var objectURL = URL.createObjectURL(source_file);
            previewDiv.innerHTML = '<object data="' + objectURL + '" type="application/pdf" width="100%" height="500px"></object>';

            
        } 
        document.getElementById("but_upload" + i).disabled = false; 
    }
};

async function blobUrlToBase64(blobUrl) {
    const response = await fetch(blobUrl); // Fetch the Blob from the URL
    const blob = await response.blob(); // Convert response to Blob

    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onloadend = () => resolve(reader.result.split(',')[1]); // Extract base64
        reader.onerror = reject;
        reader.readAsDataURL(blob); // Convert Blob to Base64
    });
}

function file_upload_all_page(format,i,path,menu,Id){
	var blobPdfDiv = document.getElementById("pre"+i);
	const blobUrl = blobPdfDiv.firstChild.data;
	//console.log(blobUrl);
	blobUrlToBase64(blobUrl).then(base64 => {
		//console.log(base64);
		var form = document.createElement('form');
		form.method = 'POST';
		form.action = 'fileup.php?file='+i+'&path='+path+'&id='+Id+'&menuId='+menu+'&status=<?php echo $status;?>'+'&upload_type=all';
		var input = document.createElement('input');
		input.type = 'hidden';
		input.name = 'imageData';
		input.value = base64;
		form.appendChild(input);
		document.body.appendChild(form);
		form.submit();
	});
}
function file_upload(format,i,path,menu,Id)
{
    var id = format;
    var selectElement = document.getElementById(id);
    var selectedValue = selectElement.value;

    if(selectedValue=="pdf"){
        var sourcefile = document.getElementById('file'+i);
        var source_file = sourcefile.files[0];
        var pagenumber = document.getElementById('pages'+i);
        var page_number = parseInt(pagenumber.value);

        var fileReader = new FileReader();
        fileReader.onload = function() {
            var typedarray = new Uint8Array(this.result);
            pdfjsLib.getDocument({ data: typedarray }).promise.then(function(pdf) {
<?php
if($status == 'Payment'){
?>
var blobPdfDiv = document.getElementById('previewtaxReceipt');
const blobUrl = blobPdfDiv.firstChild.data;
//console.log(blobUrl);
blobUrlToBase64(blobUrl).then(base64 => {
	//console.log(base64);
	var form = document.createElement('form');
	form.method = 'POST';
	form.action = 'fileup.php?file='+i+'&path='+path+'&id='+Id+'&menuId='+menu+'&status=<?php echo $status;?>';
	var input = document.createElement('input');
	input.type = 'hidden';
	input.name = 'imageData';
	input.value = base64;
	form.appendChild(input);
	document.body.appendChild(form);
	form.submit();
});
<?php
			}else if($status == 'hsrp' || $status == 'Insp'){
?>
var blobPdfDiv = document.getElementById('previewSMCtaxReceipt');
const blobUrl = blobPdfDiv.firstChild.data;
//console.log(blobUrl);
blobUrlToBase64(blobUrl).then(base64 => {
	//console.log(base64);
	var form = document.createElement('form');
	form.method = 'POST';
	form.action = 'fileup.php?file='+i+'&path='+path+'&id='+Id+'&menuId='+menu+'&status=<?php echo $status;?>';
	var input = document.createElement('input');
	input.type = 'hidden';
	input.name = 'imageData';
	input.value = base64;
	form.appendChild(input);
	document.body.appendChild(form);
	form.submit();
});
<?php
}else{
?>
                if (page_number <= pdf.numPages && page_number >= 1) {
                    pdf.getPage(page_number).then(function(page) {
                        var canvas = document.getElementById('pdf-canvas');
                        var viewport = page.getViewport({ scale: 3 });
                        canvas.width = viewport.width;
                        canvas.height = viewport.height;
                        var context = canvas.getContext('2d');
                        var renderContext = {
                            canvasContext: context,
                            viewport: viewport
                        };
                        page.render(renderContext).promise.then(function() {
                            var dataUrl = canvas.toDataURL('image/png');
							console.log(dataUrl);
                            var form = document.createElement('form');
                            form.method = 'POST';
                            form.action = 'fileup.php?file='+i+'&path='+path+'&id='+Id+'&menuId='+menu;
                            var input = document.createElement('input');
                            input.type = 'hidden';
                            input.name = 'imageData';
                            input.value = dataUrl;
                            form.appendChild(input);
                            document.body.appendChild(form);
                            form.submit();
                        });
                    });
                } else {
                    alert('Invalid page number');
                }
<?php } ?>
            });
        };
        fileReader.readAsArrayBuffer(source_file);
    }
    else{
        var fd = new FormData();
        var path = path;
        var name = i;
        var menuId = menu;
        var Id = Id;
        var files = $('#file' + i)[0].files;
        // Check file selected or not
        if(files.length > 0 )
        {

        fd.append('file',files[0]);
        fd.append('path',path);
        fd.append('name',name);
        fd.append('menuId',menuId); 
        fd.append('id',Id);
        $.ajax({
        url:'uploade.php',
        type:'post',
        data:fd,
        dataType: 'json',
        contentType: false,
        processData: false,
        success:function(response){
        
                if(response.status == 1){
                    var extension = response.extension.toLowerCase();
                    var path = response.path;
                    
                    $('.prevel').hide();
                    if(extension == 'pdf'){
                        $("#fileprev" +  i).attr("href",path);
                        $("#fileprev" + i).show();
                    }else{
                        $("#imgprev" + i).attr("src",path);
                        $("#imgprev" + i).show();
                    }

                }else if(extension == 'pdf' || extension =='jpg'){
                    alert('File not uploaded');
                }
                else{
                    alert('Wrong file format');
                }
                window.location.reload();
        }
        });
        }else{
        alert("Please select a file.");
        }
    }
}
function getCompareData(){
	$(".loader-div").show();
	var compare_data=document.getElementById('hidden_compare_data')
	var inv_img=document.getElementsByName('TaxInvoice_img')[0].value
	var dis_img=document.getElementsByName('DISCLAIMER_img')[0].value
	dataString='action=getCompareData&inv_img='+inv_img+'&dis_img='+dis_img;
	$.ajax({
		type:'POST',
		async: true,
		url:'ajax_data.php',
		data:dataString,
		success:function(data){
			$(".loader-div").hide();
			try {
				value=JSON.parse(data);				
			} catch (e) {
				var valid_data=data.replace(/\\/g, "");
				console.log("Valid Result:"+valid_data);
				try{
					value=JSON.parse(valid_data);
				}catch (e) {
					alert('Scan images result is not proper Output:'+data);
				}
			}
			var data_str="<table border=1><tr><th></th><th>Name</th><th>Chassis</th><th>Engin</th><th>Sale Amount</th><th>Hypo</th></tr>";
			data_str+="<tr><td>DISCLAIMER</td><td>"+value.dname+"</td><td>"+value.dchassis+"</td><td>"+value.dengin+"</td><td>"+value.dsale_amount+"</td><td>"+value.dhypo+"</td></tr>"
			data_str+="<tr><td>TaxInvoice</td><td>"+value.iname+"</td><td>"+value.ichassis+"</td><td>"+value.iengin+"</td><td>"+value.isale_amount+"</td><td>"+value.ihypo+"</td></tr>"
			data_str+="<tr><td>Result</td><td>"+value.is_name+"</td><td>"+value.is_chassis+"</td><td>"+value.is_engin+"</td><td>"+value.is_sale_amount+"</td><td>"+value.is_hypo+"</td></tr>"
			data_str+="</table>";
			$("#compareResultDiv").html(data_str);
			compare_data.value=data.trim();
		},
		error: function () {
			$(".loader-div").hide();
		}
	});
}
</script>