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


$requestData = $_REQUEST;


/*Fetch Database column Details*/
        $columns = array( 
            0 =>'id', 
            1 =>'id', 
            2 =>'id',
            3 =>'id',
            4 =>'id',
            5 =>'id',
            6 =>'id',
            7 =>'id',
            8 =>'id',
            9 =>'id'
           
        );
        
$conditions="";

$status = $_POST['status'];
$customer_id = $_POST['customer_id'];
$scheme_type = $_POST['scheme_type'];

if($status!=""){
    
    if($status==0){
        $conditions.=" and cs.scheme_completed_date!='0000-00-00'";
    }else if($status==1){
        $conditions.=" and cs.scheme_completed_date='0000-00-00'";
    }
}
if($customer_id!=""){
    $conditions.=" and cs.customer_id=".$customer_id;
}
if($scheme_type!=""){
    $conditions.=" and tbl_schemes.type=".$customer_id;
}

        
$sql_query = "SELECT cs.*,
            	c.customer_name, c.mobile_no, tbl_schemes.name as scheme_name, 
            	tbl_schemes.type as scheme_type,
                cu.name as created_user_name, uu.name as updated_user_name,
                COALESCE(payment_counts.payment_paid_month_counts, 0) AS payment_paid_month_counts,
                payment_counts.total_paid_scheme_weight,
                (SELECT COALESCE(SUM(amount),0) FROM `tbl_payments` p WHERE p.accounts=3 and p.scheme_id=cs.id) as paid_total_amount
                FROM `tbl_customer_scheme` cs
                LEFT JOIN tbl_customers c ON c.id=cs.customer_id
                LEFT JOIN tbl_schemes ON tbl_schemes.id=cs.scheme_id
                LEFT JOIN tbl_users cu ON cu.id=cs.created_by
                LEFT JOIN tbl_users uu ON uu.id=cs.updated_by
                LEFT JOIN (
                    SELECT scheme_id, COUNT(DISTINCT month) AS payment_paid_month_counts, SUM(scheme_weight) as total_paid_scheme_weight
                    FROM tbl_payments
                    WHERE accounts = 3
                    GROUP BY scheme_id
                ) AS payment_counts ON payment_counts.scheme_id = cs.id"; 
  
  
  
  
  
  
  
        
/*Fetch All Data Start*/        
    	$statement = $pdo->prepare("$sql_query
    	WHERE cs.id!=0 AND cs.soft_delete=0 ".$conditions." ORDER BY cs.id DESC");
		$statement->execute();
		$query = $statement->fetchAll(PDO::FETCH_ASSOC);
		$totalData = $statement->rowCount();
        $totalFiltered = $totalData;
/*Fetch All Data End*/       
        
/*Fetch Filter Data Start*/    
        $sql = "$sql_query
    	        WHERE cs.id!=0 AND cs.soft_delete=0 ".$conditions;
         
        if( !empty($_REQUEST['search']) ) {   
        	$sql.=" AND ( c.customer_name LIKE '%".$_REQUEST['search']."%' ";  
        	$sql.=" OR cs.scheme_no LIKE '%".$_REQUEST['search']."%' ";
        	$sql.=" OR c.mobile_no LIKE '%".$_REQUEST['search']."%' ) ";
        }
        
/*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=1;
foreach( $query as $row ) {  // preparing an array
	$nestedData=array(); 
	$action= "<div class='text-center'><div class='btn-group'>";
	 
	 
	                    $action.=" <a style='padding: 6px;margin-right: 3px;' href='modal/scheme-view-modal.php?id=".$row["id"]."' data-toggle='ajax-modal' title='View Details' class='tip btn btn-primary btn-xs'>
		                    <i class='fa fa-eye'></i>
		                </a>";
		                
	 	                $action.="<a style='padding: 6px;margin-right: 3px;' href='customers-scheme-edit.php?id=".$row["id"]."' title='Edit Customer Scheme' class='tip btn btn-warning btn-xs'>
		                    <i class='fa fa-edit'></i>
		                </a> ";
		                
		                $action.="<a style='padding: 6px;margin-right: 3px;' href='scheme-payment-add.php?id=".$row["id"]."' title='Payments' class='tip btn btn-success btn-xs'>
		                    <i class='fa fa-inr' style='width: 14px;font-size: 12px;'></i>
		                </a> ";
		                
		                $action.="<a style='padding: 6px;margin-right: 3px;' target='_blank' href='customers-scheme-print.php?id=".$row["id"]."' title='Print Customer Scheme' class='tip btn btn-info btn-xs'>
							<i class='fa fa-print'></i>
						</a> ";
		                
		                
		                $action.=" <button style='padding: 6px;margin-right: 3px;' title='Delete Customers Scheme' onClick='delete_Details(".$row["id"].")' class='tip btn btn-danger btn-xs'>
		                    <i class='fa fa-trash-o'></i>
		                </button>";
		                
		                $action.=" <a style='padding: 6px;margin-right: 3px;' title='Scheme Report' href='reports-scheme.php?scheme=".$row['scheme_no']."' class='tip btn btn-info btn-xs'>
		                    <i class='fa fa-external-link'></i>
		                </a>";
	           
		                

		                
	$action.="</div></div>";
	
	
	$payment_pending_months = $row["scheme_months"]-$row["payment_paid_month_counts"];
	
	if($row['scheme_type']==2){
	    $scheme_type = "info";
	}else{
	    $scheme_type = "warning";
	}
	
	
	$customer_details = "";
	
	$nestedData[] = $action;	
	
	$nestedData[] = "<div class='text-center'>".$i."</div>";
	
	$nestedData[] = "<div class='text-center'>".$row["customer_name"]." - ".$row["mobile_no"]."</div>";

	
	$nestedData[] = "<div class='text-center'>
	                    <span class='btn btn-primary btn-xs' style='font-size: 12px; font-weight: 700; font-family: system-ui;'><i class='fa fa-inr'></i> ".number_format($row['scheme_amount'],2)."</span>
	                    <span class='btn btn-info btn-xs' style='font-size: 12px; font-weight: 700; font-family: system-ui;'><i class='fa fa-inr'></i> ".number_format($row['scheme_amount']*$row["scheme_months"],2)."</span>
	                 </div>";
	
	$nestedData[] = "<div class='text-center'>".$row['scheme_no']."</div>";
	
	$nestedData[] = "<div class='text-center'><span class='btn btn-primary btn-xs' style='font-size: 12px; font-weight: 700; font-family: system-ui;'><i class='fa fa-inr'></i> ".number_format($row['paid_total_amount'],2)."</span></div>";
	
	
	
	
	if($row['scheme_type']==2){
	    $nestedData[] = "<div class='text-center'>".$row["total_paid_scheme_weight"]."</div>";
	}else{
	    $nestedData[] = "<div class='text-center'> - </div>";
	}
	
	$nestedData[] = "<div class='text-center'>".$row["payment_paid_month_counts"]." / ".$payment_pending_months."</div>";
	
	
	$nestedData[] = "<div class='text-center'><span class='btn btn-".$scheme_type." btn-xs'>".$row["scheme_name"]." - ".$row["scheme_months"]." Months</span></div>";
	

	if($row["status"]==1 && $row["scheme_completed_date"]!=0 && $row['scheme_completed_date']!="" && $row['scheme_completed_date']!="0000-00-00"){
	    $nestedData[] ="<div class='text-center'><span class='btn btn-danger btn-xs'><i class='fa fa-check'></i> Completed</span></div>";
	}else{
	    /*$nestedData[] ="<div class='text-center'><span class='btn btn-danger btn-xs' onclick='DynamicActive(".$row["id"].")'><i class='fa fa-eye-slash'></i> In-Active</span></div>";*/
	    $nestedData[] ="<div class='text-center'><span class='btn btn-success btn-xs'><i class='fa fa-spinner'></i> Inprocess</span></div>";
	}
        	
        	
	$data[] = $nestedData;
	$i++;
	

}

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

echo json_encode($json_data); 




?>