<?php
ob_start();
session_start();
include "../inc/config.php";
include "../inc/session.php";
include "../inc/functions.php";
$allPermissions = $_SESSION['permission'];

$requestData= $_REQUEST;

$conditions='';

$to_branch=$_POST['to_branch'] ?? 0;
$from_branch=$_POST['from_branch'] ?? 0;
$coloader=$_POST['coloader'] ?? 0;
$from_date=$_POST['from_date'] ?? date('Y-m-d');
    $to_date=$_POST['to_date'] ?? date('Y-m-d');
    
    $type=$_POST['type'] ?? 1;

    if($to_branch!='all' && $to_branch!='' && $to_branch!='0'){
        $conditions.=" and manifest.destination='".$to_branch."'";
    }
    if($from_branch!='all' && $from_branch!='' && $from_branch!='0'){
        $conditions.=" and manifest.origin='".$from_branch."'";
    }
    if($coloader!='all' && $coloader!='' && $coloader!='0'){
        $conditions.=" and manifest.coloader_id='".$coloader."'";
    }
    
    $conditions.=" and manifest.entry_date BETWEEN '$from_date' AND '$to_date' and manifest_type=$type ";
    
    if($session['id']!=1 && $session_branch_ids!='0'){
        $conditions.= " and manifest.origin IN ($session_branch_ids)";
    }
    
    if($session['id']!=1 && $session_branch_ids!='0'){
        $conditions.= " and manifest.destination IN ($session_branch_ids)";
    }

/*Fetch Database column Details*/
        $columns = array( 
            0 =>'id', 
            1 =>'id', 
            2 =>'id',
            3 =>'id'
        );
/*Fetch All Data Start*/        
        
    	$statement = $pdo->prepare("SELECT manifest.* FROM `manifest` where 1=1 ".$conditions);
		$statement->execute();
		$query = $statement->fetchAll(PDO::FETCH_ASSOC);
		$totalData = $statement->rowCount();
        $totalFiltered = $totalData;
/*Fetch All Data End*/       
        
/*Fetch Filter Data Start*/    
         $sql="SELECT manifest.*,
         (select name from tbl_branch where id=manifest.origin) as from_branch,
         (select name from tbl_branch where id=manifest.destination) as to_branch,
         (select name from tbl_coloader where id=manifest.coloader_id) as coloader_name FROM `manifest` where 1=1 ".$conditions;
        if( !empty($requestData['search']['value']) ) 
        {   
        	$sql.=" AND ( manifest.driver_name LIKE '%".$requestData['search']['value']."%' ";    
        	$sql.=" OR manifest.driver_name LIKE '%".$requestData['search']['value']."%' ";
        	$sql.=" OR manifest.driver_name LIKE '%".$requestData['search']['value']."%' ) ";
        }
        	 
        $statement = $pdo->prepare($sql);
        $statement->execute();
		$query = $statement->fetchAll(PDO::FETCH_ASSOC);
        $totalFiltered = $statement->rowCount();
        
/*Fetch Filter Data End*/       
        


        $sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."   ".$requestData['order'][0]['dir']."  LIMIT ".$requestData['start']." ,".$requestData['length']."   ";
       //error_log($sql);
        $statement = $pdo->prepare($sql);
        $statement->execute();
		$query = $statement->fetchAll(PDO::FETCH_ASSOC);

$data = array();
$i=$requestData['start']+1;
foreach( $query as $row ) {  // preparing an array
	$nestedData=array(); 
 	$nestedData[] = $i;
 	
 	$_details='';
        
        	
        if($row["status"]==0){	
            $s= "<a class='btn btn-danger btn-xs'><i class='fa fa-edit'></i> In-Active</a>";
        }else{
            $s= "<a class='btn btn-success btn-xs'><i class='fa fa-eye'></i> Active</a>";
        }
       
 	
 	$action='';
 	$action.="<a href='manifest-print.php?id=".id_encrypt($row['id'])."' target='_blank' class='btn btn-warning btn-xs mr-2'><i class='fa fa-print'></i> Print Manifest</a>";
 	

 	
 	$bo=0;$wt=0;
 	  //  $statement = $pdo->prepare("SELECT manifest.*,
    //      (select sum(pickup_entry.boxes) from pickup_entry where pickup_entry.id in (".$row['ids'].")) as box,
    //      (select sum(a_weight) from pickup_entry where id in (".$row['ids'].")) as wt FROM `manifest` where id=".$row['id']);
        // $statement->execute();
        
        // Assuming $row['ids'] is an array of IDs
        $idsArray = explode(',', $row['ids']);
        $placeholders = implode(',', array_fill(0, count($idsArray), '?'));
        
        // Prepare the SQL with placeholders
        $sql = "SELECT manifest.*,
        (SELECT SUM(pickup_entry.boxes) FROM pickup_entry WHERE pickup_entry.id IN ($placeholders)) AS box,
        (SELECT SUM(a_weight) FROM pickup_entry WHERE id IN ($placeholders)) AS wt
        FROM manifest
        WHERE id = ?";
        
        // Merge all placeholders for ids and add manifest id at the end
        $params = array_merge($idsArray, $idsArray, [$row['id']]);
        
        $statement = $pdo->prepare($sql);
        $statement->execute($params);

		$qu = $statement->fetchAll(PDO::FETCH_ASSOC);
		if($qu){
		    $bo=$qu[0]['box'];
		    $wt=$qu[0]['wt'];
		}
 	
 	
 	
 	$nestedData[] = $action;
 	$nestedData[] = "<span class='label_title'>".$row["from_branch"]."</span>";
 	$nestedData[] = "<span class='label_title'>".$row["to_branch"]."</span>";
 	$nestedData[] = "<span class='label_title'>".$row["entry_date"]."</span>";
 	$nestedData[] = "<span class='label_title'>".nl2br($row["no_of_entry"])."</span>";
 	$nestedData[] = "<span class='label_title'>".nl2br($bo)."</span>";
 	$nestedData[] = "<span class='label_title'>".nl2br($wt)."</span>";
 	$nestedData[] = "<span class='label_title'>".nl2br($row["coloader_name"])."</span>";
 	$nestedData[] = "<span class='label_title'>".nl2br($row["vehicle_no"])."</span>";
 	$nestedData[] = "<span class='label_title'>".nl2br($row["driver_name"])."</span>";
 	$nestedData[] = "<span class='label_title'>".nl2br($row["driver_mobile_no"])."</span>";
	$nestedData[] = $s;
	$data[] = $nestedData;
	$i++;
}

$json_data = array(
			"draw"            => intval( $requestData['draw'] ),  
			"recordsTotal"    => intval( $totalData ), 
			"recordsFiltered" => intval( $totalFiltered ), 
			"data"            => $data  
			);

echo json_encode($json_data);  

?>