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


function exportMysqlToCsv($filename,$table_name,$from_date,$to_date)
{
	
	try {

   $conn = dbConnection();
// Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $sql_query = "SELECT * FROM ".$table_name;



    if($table_name=='updates')
	{
	 	 
	 $sql_query = "SELECT * FROM updates  where  ( date(update_date) >= date('$from_date')  and date(update_date) <= date('$to_date') )  ";
	
	}

    
   if($table_name=='leads')
	{
		$sql_query = 'SELECT *, JSON_EXTRACT(`lead_data`, "$.externalid") AS externalid  FROM leads ';
			
	}


	if($table_name == 'call_evaluation')
		{
			 $questionsArray = array('Greetings, Self Introduction, Brand Introduction/Lender name done?',
					'Did agent check the Reason for Delinquency (RFD) and probed?','Did agent Call recording status informed?',
					'Did agent follow the negotiation hierarchy for BKT 30-90 (Norm/RB/Stab)? This applies for Bucket X EMI negotiation also.',
					'Did agent handled objection effectively and displayed ownership on call?',
					'Did agent offer appropriate programmed as per given guidelines. (LPF/Knock off/settlement)?',
					'Did agent use effective articulation of Whats in it for me? - CIBIL Impact and Zest relationship',
					'Appropriate codes marked (RFD/NCD/ Disposition Code) Crisp and articulate documentation (Post call notes)',
					'Active listening (Fail to listen actively or Making the customer repeat the information)',
					'Appropriate Acknowledgement/Responses/Tone/Energy/Enthusiasm(Rate of speech and tone modulation) used on call?');

		}



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

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

    while ($row = $result->fetch_assoc()) {
		
		if($table_name=='leads')
		{
		    
			 $row['account_holder_id']= "'".$row['account_holder_id'];
			 	  $row['lead_data'] = '';
	  
		}
		
		if($table_name=='account_holder')
		{
		    
			 $row['account_holder_id']= "'".$row['account_holder_id'];
	  
		}
	 
		
		
		
		
		if($table_name == 'call_evaluation')
		{
			 for($question_no = 2;$question_no<=12;$question_no++)
			 {
				 
				 $val =  $row['question_'.$question_no];
				 $row['question_'.$question_no] = '';
				 unset($row['question_'.$question_no]);
				  $column_name =  $questionsArray[$question_no - 2];  
			
				 
				 $row[$column_name] = $val;
			         
			   
			 }
			 
		}
	 
	 
		
		
		
		
		
		
		
		
		
		
		
		
		
	  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;
}



  $from_date = '';
  $to_date = '';
  
  if(isset($_GET['from_date']))
  {
	 $from_date = $_GET['from_date']; 
	 $to_date = $_GET['to_date']; 
  }


//exportMysqlToCsv('product.csv','product');
exportMysqlToCsv($_GET['type'].'.csv',$_GET['type'],$from_date,$to_date);

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


?>