<?php 
ob_start();
session_start();
include("../inc/config.php");
include("../inc/session.php");
?>
<?php


function xss_clean($data)
    {
        $data = trim($data);
        // Fix &entity\n;
        $data = str_replace(array('&amp;', '&lt;', '&gt;'), array('&amp;amp;', '&amp;lt;', '&amp;gt;'), $data);
        $data = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $data);
        $data = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $data);
        $data = html_entity_decode($data, ENT_COMPAT, 'UTF-8');

        // Remove any attribute starting with "on" or xmlns
        $data = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data);

        // Remove javascript: and vbscript: protocols
        $data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data);
        $data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $data);
        $data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $data);

        // Only works in IE: <span style="width: expression(alert('Ping!'));"></span>
        $data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
        $data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
        $data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $data);

        // Remove namespaced elements (we do not need them)
        $data = preg_replace('#</*\w+:\w[^>]*+>#i', '', $data);

        do {
            // Remove really unwanted tags
            $old_data = $data;
            $data = preg_replace('#</*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|i(?:frame|layer)|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|title|xml)[^>]*+>#i', '', $data);
        } while ($old_data !== $data);

        // we are done...
        return $data;
    }


$requestData= $_REQUEST;

$condition = '';

    //  Request data with default values
    $from_date = $_POST['start_date'] ?? '2025-04-01';
    $to_date = $_POST['end_date'] ?? date('Y-m-d');
    $new_client = $_POST['new_client'] ?? 0;
    $branch_id = $_POST['branch_id'] ?? 0;
    $company_id = $_POST['company_id'] ?? 0;
    $client_id = $_POST['client_id'] ?? 0;
    $customer_id = $_POST['customer_id'] ?? 0;
    $status = $_POST['status'] ?? 0;

        
    if($from_date!=''){
      $condition .= " AND STR_TO_DATE(e.validUpto, '%d/%m/%Y %h:%i:%s %p') <= '$from_date'";

    }
    

/*Fetch Database column Details*/
        $columns = array( 
            0 => 'p.id',
            3 => 'p.cscs_awb',
            4 => 'e.ewbNo',
            7 => 'p.ewbn_expiry',
            9 => 'p.ewayBillDate'
        );
/*Fetch Database column Details*/        
        
        
    $statement = $pdo->prepare("SELECT e.*, 
               p.invoice_date, 
               p.invoice_no, 
               CASE 
                   WHEN p.invoice_no = e.docNo THEN 'generated' 
                   ELSE 'not generated' 
               END AS rhd_ewaybill,
               CASE 
                   WHEN v.pid IS NOT NULL THEN 1 
                   ELSE 0 
               END AS vehicle_updated 
        FROM ewaybills e
        LEFT JOIN pickup_entry p ON p.invoice_no = e.docNo
        LEFT JOIN vehicle_update_details v ON v.pid = e.ewbNo
        WHERE  1=1  $condition ORDER BY p.id DESC");    
    $statement->execute();
	$query = $statement->fetchAll(PDO::FETCH_ASSOC);
	$totalData = $statement->rowCount();
    $totalFiltered = $totalData;   

/*Fetch Filter Data Start*/    
        $sql="SELECT e.*, 
               p.invoice_date, 
               p.invoice_no, 
               CASE 
                   WHEN p.invoice_no = e.docNo THEN 'generated' 
                   ELSE 'not generated' 
               END AS rhd_ewaybill,
               CASE 
                   WHEN v.pid IS NOT NULL THEN 1 
                   ELSE 0 
               END AS vehicle_updated 
        FROM ewaybills e
        LEFT JOIN pickup_entry p ON p.invoice_no = e.docNo
        LEFT JOIN vehicle_update_details v ON v.pid = e.ewbNo
        WHERE  1=1 $condition";
        if( !empty($requestData['search']['value']) ) 
        {   
        	$sql.=" AND ( e.ewbNo LIKE '%".$requestData['search']['value']."%' ";    
        	$sql.=" OR e.docNo LIKE '%".$requestData['search']['value']."%' ";
        	$sql.=" OR e.ewbNo LIKE '%".$requestData['search']['value']."%') ";
        }
    
        $sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."   ".$requestData['order'][0]['dir']."  LIMIT ".$requestData['start']." ,".$requestData['length']."   ";
        $statement = $pdo->prepare($sql);
        $statement->execute();
		$query = $statement->fetchAll(PDO::FETCH_ASSOC);
		error_log($sql);
/*Fetch Filter Data End*/

// print_r($sql); die;
// Counters
$rhdGeneratedCount = 0;
$rhdNotGeneratedCount = 0;
$vehicleUpdatedCount = 0;
$vehicleNotUpdatedCount = 0;


$data = array();
$i=$requestData['start']+1;
foreach($query as $row ) {  
    
    if ($row["rhd_ewaybill"] === 'generated') {
        $rhdGeneratedCount++;
    } else {
        $rhdNotGeneratedCount++;
    }

    if ($row["vehicle_updated"] == 1) {
        $vehicleUpdatedCount++;
    } else {
        $vehicleNotUpdatedCount++;
    }

    
    
	$nestedData=array(); 
	$nestedData[] = $i;
	$nestedData[] = xss_clean($row["ewbNo"]);
	$nestedData[] = xss_clean($row["genGstin"]);
	$nestedData[] = xss_clean($row["docNo"]);
	$nestedData[] = xss_clean($row["docDate"]);
	$nestedData[] = xss_clean($row["ewbDate"]);
	$nestedData[] = xss_clean($row["validUpto"]);
	$nestedData[] = xss_clean($row["rhd_ewaybill"]);
	$nestedData[] = xss_clean($row["vehicle_updated"]);

	$data[] = $nestedData;
	$i++;
}

	

$json_data = array(
			"draw"            => intval( $requestData['draw'] ),   // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw. 
			"recordsTotal"    => intval( $totalData ),  // total number of records
			"recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData
			"data"            => $data,   // total data array
			"counts" => [
                "rhd_generated" => $rhdGeneratedCount,
                "rhd_not_generated" => $rhdNotGeneratedCount,
                "vehicle_updated" => $vehicleUpdatedCount,
                "vehicle_not_updated" => $vehicleNotUpdatedCount
            ]

			);

echo json_encode($json_data);  // send data as json format

?>
        