<?php

class PBReusableModel_CSVExport extends CI_Model {

	const ANALYTICS = 'taw_log';

    function __construct() {
        parent::__construct();
		$this->load->helper('date');
        $this->load->helper('file');
		$this->load->model('PBReusableModel_Analytics','analytics');
    }

    function download_send_headers($filename) {
		// disable caching
		$now = gmdate("D, d M Y H:i:s");
		header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
		header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
		header("Last-Modified: {$now} GMT");

		// force download
		header("Content-Type: application/force-download");
		header("Content-Type: application/octet-stream");
		header("Content-Type: application/download");

		// type
		header("Content-type: text/csv");

		// disposition / encoding on response body
		header("Content-Disposition: attachment;filename={$filename}");
		header("Content-Transfer-Encoding: binary");
	}

	function array2csv(array &$array)
	{
		if (count($array) == 0) {
			return null;
		}
		ob_start();
		$df = fopen("php://output", 'w');
		fputcsv($df, array_keys(reset($array)));
		foreach ($array as $row) {
			fputcsv($df, $row);
		}
		fclose($df);
		return ob_get_clean();
	}

	public function convertToZip($filename) {
        $zip = new ZipArchive;
        if ($zip->open('/var/www/vhosts/pixelbeard.co/api-taw.pixelbeard.co/TAW_Analytics.zip', ZipArchive::CREATE) === TRUE)
        {
            $zip->addFile($filename);
            $zip->close();
            return true;
        } else {
            return false;
        }
    }

    public function exportCSVUsingParams() {

        $filename_with_date = 'TAW_Analytics_'.date('Ymdh:i:s').'.csv';

//        header("Content-Description: File Transfer");
//        header("Content-Disposition: attachment; filename=$filename");
//        header("Content-Type: application/csv; ");
////        echo ini_get('max_execution_time');
////        exit;
        $params_array = $this->input->post();
        $filters = $params_array['filter'];
//		$this->db->select('date,partner_id,user_id,type,variable,secondary_variable');
//        $this->db->from(self::ANALYTICS);
////		$this->db->order_by('date DESC');
//
		$count = 0;
        foreach ($filters as $analytic) {
			if($count == 0) {
				$where_string = "(type = '$analytic'";
			} else {
				$where_string .= " OR type = '$analytic'";
			}
			$count = $count+1;
			if($count == count($filters)) {
				$where_string .= ") ";
			}

        }
//		$this->db->where($where_string);
//
//		if (isset($params_array['from_date'])) {
//			$this->db->where('date >=', $params_array['from_date']);
//		}
//        if (isset($params_array['to_date'])) {
//			$this->db->where('date <=', $params_array['to_date']);
//		}
//		$query = $this->db->get();
//		$analytics = $query->result();
//
//
////        echo ini_get('max_execution_time');
////        exit;
//
//		$data = array();
//		foreach ($analytics as $analytic) {
//			$odata = array();
//			foreach ($analytic as $key => $val) {
//				$odata[$key] = $val;
//			}
//			array_push($data, $odata);
//		}
        if (file_exists('/var/www/vhosts/pixelbeard.co/api-taw.pixelbeard.co/TAW_Analytics.zip')) {
            unlink('/var/www/vhosts/pixelbeard.co/api-taw.pixelbeard.co/TAW_Analytics.zip');
        }

        $filename = "/tmp/".$filename_with_date;
		$sql = "SELECT * INTO OUTFILE '" . $filename . "' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' FROM taw_log where ".$where_string." AND (date BETWEEN '".$params_array['from_date']."' AND '".$params_array['to_date']."')";
        $this->db->query($sql);
//        sleep(5);
//
        if (file_exists($filename))
        {
            return array(
                'success' => true,
                'filename' => $filename
            );
        }
        return false;
        exit;
//        $this->download_send_headers("TAW_Analytics_Export2.csv");
//		$this->download_send_headers("TAW_Analytics_Export_" . date("Y-m-d") . ".csv");
//        echo ini_get('max_execution_time');



//        $config['upload_path']   = './csv/';
//        $config['allowed_types'] = 'csv';
//        $config['file_name'] = '_'.time();
//        $this->load->library('upload', $config);
//        $image = '';
//        if ( ! $this->upload->do_upload($this->array2csv($data))) {
//            $error = array('error' => $this->upload->display_errors());
//            var_dump($error);
//            echo "boo";
//        } else {
////            $file_data = array('upload_data' => $this->upload->data());
////            $image = 'https://aircharge.pixelbeard.co/images/buttons/'.$file_data['upload_data']['file_name'];
//            echo "yay";
//        }




//        if(write_file('./var/www/vhosts/pixelbeard.co/api-taw.pixelbeard.co/csv/data.csv', $this->array2csv($data), 'r+')) {
//            echo "yay";
//        } else {
//            echo "boo";
//        }
        // file creation
//        $file = fopen('php://output', 'w');
//
//        $header = array("Username","Name","Gender","Email");
//        fputcsv($file, $header);
//        foreach ($data as $key=>$line){
//            fputcsv($file,$line);
//        }
//        fclose($file);
//        exit;

//        $this->array2csv($data);
////		die();
//        exit;
//        return true;
    }
}
