<?php
                           


$hostname = 'localhost';
$username = 'supportf_user';
$password = 'cO?.dTHbAXo{';
$myDatabase = 'supportf_db';
try {
$conn = new PDO('mysql:host=localhost;dbname='.$myDatabase, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $conn->prepare("SELECT t1.asset_id, t1.asset_user, t1.designation, t2.location_name, t3.device_name, t4.brand_name, t1.model_product_no, t1.tagging_no, t1.date_requested, t1.date_received, t1.date_issued, 
t1.asset_status, t1.remarks, t5.firstname, t5.lastname 

FROM apl_asset AS t1 
LEFT JOIN apl_asset_location AS t2
ON t1.user_location = t2.location_id 

LEFT JOIN apl_device_asset AS t3
ON t1.device_id = t3.device_id

LEFT JOIN apl_asset_brand AS t4
ON t1.brand_id = t4.brand_id

LEFT JOIN apl_employees AS t5
ON t1.userid = t5.id");


$stmt->execute();
$filelocation = 'reports/exports/';
$filename = 'export-'.date('Y-m-d H.i.s').'.txt';
$file_export = $filelocation . $filename;

$data = fopen($file_export, 'w');

$csv_fields = array();
$csv_fields[] = 'asset_id';
$csv_fields[] = 'asset_user';
$csv_fields[] = 'designation';
$csv_fields[] = 'location_name';
$csv_fields[] = 'device_name';
$csv_fields[] = 'brand_name';
$csv_fields[] = '"model_product_no"';
$csv_fields[] = '"tagging_no"';
$csv_fields[] = 'date_requested';
$csv_fields[] = 'date_received';
$csv_fields[] = 'date_issued';
$csv_fields[] = 'asset_status';
$csv_fields[] = 'remarks';
$csv_fields[] = 'firstname';
$csv_fields[] = 'lastname';


  
  fputcsv($data, $csv_fields);

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
       fputcsv($data, $row);
      //  fputcsv($data, array_map(function($v){return number_format($v, 0, '', '');}, $row));
    }

} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}





/*
fputcsv($data, $csv_fields);

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        fputcsv($data, $row);
        // header("Content-Type: application/vnd.ms-excel");
       // header('Content-Disposition: attachment; filename= "filename.txt"');
        echo $data.$csv_fields;
    }

} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}


fputcsv($data, $csv_fields);

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        
        fputcsv($data, $row);
        header('Content-Type: application/csv');
        header('Content-Disposition: attachment; filename= "filename.csv"');
        echo $data.$csv_fields; 
       // readfile("/tmp/filename.csv");
        exit();
    }

} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

*