<?php 
if (isset($_SERVER['REMOTE_ADDR'])) {
    die(':)');
}

echo "Cron is running";

$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 apl_employees.id AS ai, apl_employees.firstname AS af, apl_employees.lastname AS al, apl_employees.cooperate_email AS ac, apl_employees.department_id AS ad, messages.line2 AS ml2, messages.line3 AS ml3, messages.line4 AS ml4, messages.barcode_selected AS mb, address.my_address AS am, address.firstname AS af, address.lastname AS al, address.address1 AS aa1, address.address2 AS aa2, address.town AS at, address.postcode AS ap, address.datecreated AS ad
			FROM apl_employees
			JOIN apl_repair_list
			ON apl_employees.id = apl_repair_list.registered_by
			JOIN apl_repair_list
			ON users.id = address.user_id");

    $stmt->execute();

	$filelocation = 'assets_list/exports/';
	$filename     = 'export-'.date('Y-m-d H.i.s').'.csv';
	$file_export  =  $filelocation . $filename;

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

    $csv_fields = array();

	$csv_fields[] = 'id';
	$csv_fields[] = 'firstname';
	$csv_fields[] = 'lastname';
	$csv_fields[] = 'email';
	$csv_fields[] = 'dob';
	$csv_fields[] = 'line1';
	$csv_fields[] = 'line2';
	$csv_fields[] = 'line3';
	$csv_fields[] = 'line4';
	$csv_fields[] = 'barcode_selected';
	$csv_fields[] = 'my_address';
	$csv_fields[] = 'firstname';
	$csv_fields[] = 'lastname';
	$csv_fields[] = 'address1';
	$csv_fields[] = 'address2';
	$csv_fields[] = 'town';
	$csv_fields[] = 'postcode';
	$csv_fields[] = 'datecreated';

	fputcsv($data, $csv_fields);

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        fputcsv($data, $row);
    }

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