<?php
include 'header.php';
error_reporting(0);
require_once('vendor/php-excel-reader/excel_reader2.php');
require_once('vendor/SpreadsheetReader.php');
//require __DIR__ . '/cromepdf/autoload.php';
//use daandesmedt\PHPHeadlessChrome\HeadlessChrome;

$current_date=date('Y-m-d');
if (isset($_POST["import"]))
{
	$report=array();
	$earray=array();
	$successRecordUpdate=0;
	$notFound=0;
	$rejected=0;

  $allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
  
  if(in_array($_FILES["file"]["type"],$allowedFileType)){	  

        $targetPath = 'temp/'.$_FILES['file']['name'];
        move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);
        $Reader = new SpreadsheetReader($targetPath);
		
        $sheetCount = count($Reader->sheets());
		
        for($i=0;$i<$sheetCount;$i++)
        {
            $Reader->ChangeSheet($i);
            foreach ($Reader as $Row)
            {
				$reg_date = preg_replace('!\s+!', ' ',$Row[0]);
				$reg_no = preg_replace('!\s+!', ' ',$Row[1]);
				$chassis_no = preg_replace('!\s+!', ' ',$Row[2]);
				//$short_chassis_no=substr($chassis_no,9,8);
				$short_chassis_no=$chassis_no;
				//echo "<br>Ch No:".$short_chassis_no;
				$short_reg_no=substr($reg_no,0,3);
				$new_reg_date=date('Y-m-d',strtotime($reg_date));
                if (!empty($reg_date) || !empty($reg_no) || !empty($chassis_no)) {
					$bdd=new DB();
					$regNoRow=$bdd->getOne("SELECT * FROM `customer` WHERE registration_no='".$reg_no."' and (status='hsrp' or status='Register')");
					$bdd->disconnect();
					if(!empty($regNoRow)){
						$earray=array("Receipts Date"=>$reg_date,"Vehicle Registration Number"=>$reg_no,"Chasis Number"=>$chassis_no,"Report"=>"Already Updated");
						array_push($report,$earray);
						
					}else{
					$bdd=new DB();
					$chassisNoRow=$bdd->getOne("SELECT customer_id,registration_no,reg_date FROM customer WHERE status='SemiSuccessfull' and chassis_no='".$short_chassis_no."'");
					$bdd->disconnect();
					if(!empty($chassisNoRow)){
						//if($short_reg_no=="NEW" || $short_reg_no=="GJ/"){
						if(!ctype_alnum($reg_no) || $short_reg_no=="NEW" || $reg_date=="-" || strlen($reg_no)>10){
							
							$rejected++;
							$earray=array("Receipts Date"=>$reg_date,"Vehicle Registration Number"=>$reg_no,"Chasis Number"=>$chassis_no,"Report"=>"Rejected");
							array_push($report,$earray);
							
						}else{
								$current_hsrp_time=date('Y-m-d H:i:s',strtotime('24 hour'));
								
								$bdd=new DB();
								$bdd->execute("UPDATE customer SET hsrp_time='$current_hsrp_time',registration_no='".$reg_no."', reg_date='".$new_reg_date."',complete_chassis_no='".$chassis_no."',status='hsrp' WHERE customer_id='".$chassisNoRow['customer_id']."'");
								$bdd->disconnect();
								
								$bdd=new DB();
								$existingEntries = $bdd->getOne("SELECT * FROM modification WHERE CId =".$chassisNoRow['customer_id']);
								$bdd->disconnect();
/*$headlessChromer = new HeadlessChrome();
$headlessChromer->setUrl("http://localhost:8080/scanner/z1.php?id={$chassisNoRow['customer_id']}");
$headlessChromer->setBinaryPath('C:\Program Files\Google\Chrome\Application\chrome');
$headlessChromer->setOutputDirectory(__DIR__);
$headlessChromer->toPDF('output.pdf');*/

								if ($existingEntries > 0) {
									$bdd=new DB();
									$resu=$bdd->execute("UPDATE modification SET Semi = '$Uname',Semi_date='$current_datetime' WHERE CId =".$chassisNoRow['customer_id']);
									$bdd->disconnect();
								} else {
									$user_id=$chassisNoRow['customer_id'];
									$bdd=new DB();
									$insertResult = $bdd->execute("INSERT INTO modification (Semi,Semi_date, CId) VALUES ('$Uname','$current_datetime',$user_id)");
									$bdd->disconnect();
								}
								$earray=array("Receipts Date"=>$reg_date,"Vehicle Registration Number"=>$reg_no,"Chasis Number"=>$chassis_no,"Report"=>"Update");
								array_push($report,$earray);
								$successRecordUpdate++;
								
						}
					}else{
						$fla = "Can not find";
						$earray=array("Receipts Date"=>$reg_date,"Vehicle Registration Number"=>$reg_no,"Chasis Number"=>$chassis_no,"Report"=>"Can not find");
							array_push($report,$earray);
						$notFound++;
					}
					}
                }
             }
		}		
		//$redirect = "excel_report.php?".http_build_query($report);
		$_SESSION['report']=$report;
		//echo 'data'.$report;
		//print_r($report);
		header("Location: excel_report.php" );
		
  }else{ 
	$type = "error";
	$message = "Invalid File Type. Upload Excel File.";
  }
}
?>
<style>
.outer-container {
	background: #F0F0F0;
	border: #e0dfdf 1px solid;
	padding: 40px 20px;
	border-radius: 2px;
}
.btn-submit {
	background: #333;
	border: #1d1d1d 1px solid;
    border-radius: 2px;
	color: #f0f0f0;
	cursor: pointer;
    padding: 5px 20px;
    font-size:0.9em;
}
#response {
    padding: 10px;
    margin-top: 10px;
    border-radius: 2px;
    display:none;
}

.success {
    background: #c7efd9;
    border: #bbe2cd 1px solid;
}

.error {
    background: #fbcfcf;
    border: #f3c6c7 1px solid;
}

div#response.display-block {
    display: block;
}

.tutorial-table {
    margin-top: 40px;
    font-size: 0.8em;
	border-collapse: collapse;
	width: 100%;
}

.tutorial-table th {
    background: #f0f0f0;
    border-bottom: 1px solid #dddddd;
	padding: 8px;
	text-align: left;
}

.tutorial-table td {
    background: #FFF;
	border-bottom: 1px solid #dddddd;
	padding: 8px;
	text-align: left;
}
</style>
<div class="row">
	<div class="col-sm-12"><button class="btn btn-blue btn-block">Import Data</button></div>
	<div class="col-sm-12">&nbsp</div>
	<div class="col-sm-12">
    <div class="outer-container">
		<!--<div><a href="uploads/item_sample.xlsx"><h4>Click here for sample file</h4></a></div>-->
        <form action="" method="post"
            name="frmExcelImport" id="frmExcelImport" enctype="multipart/form-data">
            <div>
                <label>Choose Excel
                    File</label> <input type="file" name="file"
                    id="file" accept=".xls,.xlsx">
                <button type="submit" id="submit" name="import"
                    class="btn-submit" style="margin-top:10px;">Import</button>
            </div>
        </form>
    </div>
    <div id="response" class="<?php if(!empty($type)) { echo $type . " display-block"; } ?>"><?php if(!empty($message)) { echo $message; } ?>
	</div>
    
	</div>
</div>
</div>
</div>
</div>
    
<?php
include "footer.php";
?>
