<?php

//Check session!!Token!!Where are they!!!

require_once('../core/init.php');

//set headers
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename='.Config::get('document/csv').'.csv');

//create file
$output = fopen('php://output','w');
fwrite($output, chr(0xEF).chr(0xBB).chr(0xBF));

$db = DB::getInstance();
$where = [];

// $VIEW_report_sales = <<<EOD
// SELECT  'ranking' as `ranking`,`b`.`zh_name` AS  `cms_category` , CONCAT(  `a`.`zh_name` ,  ' / ',  `a`.`name` ) AS  `product_name` ,
//   `a`.`price` AS  `price` , IFNULL( SUM(  `c`.`amount` ) , 0 ) AS  `total_amount` , IFNULL( SUM( (`c`.`amount` * ROUND(  `c`.`price` , 0 ) ) ) , 0
// ) AS  `total_income` 
// FROM (
// (
// `productstable`  `a` 
// LEFT JOIN  `cms_categories`  `b` ON ( (
// `a`.`cms_category` =  `b`.`id`
// ) )
// )
// LEFT JOIN  `bought_item`  `c` ON ( (
// `a`.`id` =  `c`.`product_id`
// ) )
// )
// RIGHT JOIN  `orders` AS  `d` ON  `c`.`paypal_id` =  `d`.`paypal id` AND `d`.`status` <> 'bank' AND `d`.`status` <> 'perpare'
// EOD;

// function is_sale(){
//     return $_GET['reportName'] === 'VIEW_report_sales';
// }


// foreach($_GET as $key=>$JSON){
//     if($key === 'reportName'){
//         $reportName = $JSON;
//         continue;
//     }
//     if($key === 'row'){
//         $row = $JSON;
//         continue;
//     }
//     if($key === 'sortBy'){
//         //sortBy have the same format as $where
//         $sortBy = json_decode($JSON);
//         continue;
//     }
//     if($key === 'rowsPerPage'){
//         $rowsPerPage = json_decode($JSON)[1];
//         if(empty($rowsPerPage)) $rowsPerPage = 20; 
//         continue;
//     }

//     $val = json_decode($JSON);
//     //Look for the report.php,
//     //it post some json to this page which contain operators(=,>=,like,etc) and values
//     if(!empty($val[1])){
//         //Avoid array marge for duplicate index ('datetime')
//         if($key === 'start_date' || $key === 'end_date'){
//             $key = 'datetime';
//             if(is_sale()) $key = '`d`.`time`';
//         }
        
//         $where[] = [$key,$val[0],$val[1]];
//     }
// }

// if(is_sale()){
//     //Cant find a way to create a static view for sales report(it depend on a time period provide by user)
//     //Trying to handcraft a query by php in the most ugly way.And it will need a speacial treatment to create ranking numbers,
//     //which slow down the query if I build it with mysql.
//     $having = [];
//         foreach($where as $key=>$val){
//             if($val[0] != '`d`.`time`'){
//                 unset($where[$key]);
//                 $having[] = $val;
//             }
//         }
//         //Rearrange the $where's index order.(after unset some of it element)
//         $where = array_values($where);
//     $sqlResult = $db->where($where)->groupBy('`a`.`name`')->having($having)->sort($sortBy[0],$sortBy[1])->query($VIEW_report_sales)->results();

// }else{
//     $sqlResult = $db->where($where)->sort($sortBy[0],$sortBy[1])->get($_GET['reportName'])->results();
// }

$sqlResult = $db->get('clients')->results();

if($sqlResult){

    $title = [];

    //A translation class
    $lang = new Lang();

    foreach($sqlResult[0] as $indexName=>$val){
        $title[] = $lang->tran($indexName);
    };

    //first row as title
    fputcsv($output,$title);

    //fill the form
    foreach($sqlResult as $row){
        fputcsv($output,(array)$row);
    }

}else{
    echo "ERROR:,Fail to make a query with database,please contact Artech.";
}
