<?php
session_start();
// export csv
//error_reporting(0);


function exportMysqlToCsv($filename,$table_name,$name)
{
	
	try {

   $conn = dbConnection();
// Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $sql_query = "SELECT * FROM ".$table_name;
	
	
	
	if($table_name=='customer')
	{
	 $all_row_ids = implode(',',$_SESSION['all_row_ids']);
	 $sql_query = "SELECT * FROM customer  where account_holder_id in ($all_row_ids) ";
	
	} 
	
	
	if($name  == 'Retained')
	{
	    
	$sql_query = "SELECT  *, (select advisor from customer where account_holder_id = leads.account_holder_id ) as `advisor` , JSON_EXTRACT(`lead_data`, '$.externalid') AS externalid  FROM leads where account_holder_id in ($all_row_ids) ";
		
		
	}
	if($name  == 'NonContactable_Recovery')
	{
		$sql_query = "select *from `temp_filter_customer` where  ( advisor is NULL or advisor = '')  and customer_type = 'Recovery'   and account_holder_id not in (select account_holder_id from payments )     order by  imp_score desc ";
		
	}
	
	if($name  == 'NonContactable_Trace')
	{
		$sql_query = "select *from `temp_filter_customer` where  ( advisor is NULL or advisor = '')  and customer_type = 'Trace'   and account_holder_id not in (select account_holder_id from payments )     order by  imp_score desc ";
		
	}
	
	
	

    // Gets the data from the database
    $result = $conn->query($sql_query);

	
	
	
    $f = fopen('php://temp', 'wt');
    $first = true;

    while ($row = $result->fetch_assoc()) {
        
        	
		if($name  == 'Retained')
		{
			
			 $row['lead_data'] = '';
		}
		
		
		
	  	if($table_name=='leads')
		{
		    
			 $row['account_holder_id']= "'".$row['account_holder_id'];
			  $row['lead_data'] = '';
	  
		}
		
		if($table_name=='account_holder' || $table_name == 'temp_filter_customer')
		{
		    
			 $row['account_holder_id']= "'".$row['account_holder_id'];
	  
		}
		
	if(strpos($name,'PTP')!== FALSE)
		{
				
			$account_holder_id = $row['account_holder_id'];
			
			$updatesQ = mysqli_query($conn,"select *from `updates` where account_holder_id = '$account_holder_id'  and (disposition = 'PTP' or disposition = 'BRPTP' or  disposition = 'FPTP' ) order by id desc limit 1 ");
		   $updatesData = mysqli_fetch_assoc($updatesQ);
											
			
			$row['ptp_date'] = $updatesData['next_update_date'];
			$row['amount'] = $updatesData['amount'];
			
			
		}
		
		
	 
		
		
		
	  array_shift($row);

		
        if ($first) {
            fputcsv($f, array_keys($row));
            $first = false;
        }
		
		//print_r($row);
		
        fputcsv($f, $row);
		
    } // end while

    $conn->close();

    $size = ftell($f);
    rewind($f);
   // $company_initial=$_SESSION['company_initial'];
     header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Length: $size");
    // Output to browser with appropriate mime type, you choose ;)
    header("Content-type: text/x-csv");
    header("Content-type: text/csv");
    header("Content-type: application/csv");
    header("Content-Disposition: attachment; filename= $filename");
    fpassthru($f);
    exit;
	 
	
	} 
	catch(Exception $e) {
    // echo 'Message: ' .$e->getMessage();
}

}

// db connection function
function dbConnection(){
   $servername = "localhost";
      $username="finmarnf";
	  $password="Finman!@123";
	  $dbname="finmarnf_bhawani_crm";
	
	
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    return $conn;
}

//exportMysqlToCsv('product.csv','product');
exportMysqlToCsv($_GET['type'].'_'.$_GET['name'].'.csv',$_GET['type'],$_GET['name']);

//exportMysqlToCsv('product.csv','product');


?>