<?php
session_start();
if(!isset($_SESSION['user']) || empty($_SESSION['user'])) {
    header("location: ../login.php"); exit();
}

//if (isset($_POST['download_csv'])) {


    $jsonFile = '/mnt/nand/apps/ids/db.json';
    $jsonContent = file_get_contents($jsonFile);
    $data = json_decode($jsonContent, true);
    if (!$data) {
        echo "ID Storage database not configured";
    } else {
        // echo "User: " . $data['user'];
        //  echo "Password: " . $data['passw'];
        //  echo "dbtype: " . $data['dbtype'];

        if ($data['dbtype'] != 'mysql') {
            echo "ID Storage database type must by MySQL for reporting";
        } else {

            $range = $_GET['range'];
            if(!$range) {
                $range = "today";
            }

            $tzpath = realpath("/etc/localtime");
            if(substr($tzpath, 0, 20) == '/usr/share/zoneinfo/') {
                $tz = substr($tzpath, 20);
                date_default_timezone_set($tz);
            }
            // echo "Date/time " . date('Y-m-d H:i:s');

            $conn = mysqli_connect($data['server'], $data['user'], $data['passw'], $data['database']);
            if(!$conn) {
                echo 'Connection error: ' . mysqli_connect_error();
            } else {
                //echo "range " . $range;
                $dateTo = "";
                switch($range) {
                    case "today":
                        $dateFrom = date('Y-m-d');
                        $dateTo = date('Y-m-d');
                        break;

                    case "tweek":
                        $dayOfWeek = date('w');
                        $d = new DateTime();
                        if($dayOfWeek != 0) {
                            $d->modify('-' . strval($dayOfWeek) . ' days');
                        }
                        $dateFrom = date('Y-m-d', $d->GetTimestamp());
                        break;

                    case "tmonth":
                        $dateFrom = date('Y-m') . '-01';
                        break;

                    case "tyear":
                        $dateFrom = date('Y') . '-01-01';
                        break;

                    case "lweek":
                        $dayOfWeek = date('w');
                        $d = new DateTime();
                        $d->modify('-' . strval($dayOfWeek + 7) . ' days');

                        $dateFrom = date('Y-m-d', $d->GetTimestamp());
                        $d->modify('+ 6 days');
                        $dateTo = date('Y-m-d', $d->GetTimestamp());
                        //echo 'Day of week ' . $dayOfWeek . ' Last week ' . $dateFrom . ' - ' . $dateTo . '<br>';
                        break;

                    case "lmonth":
                        $d1 = strtotime("-1 months");
                        $dateFrom = date("Y-m", $d1) . "-01";
                        $dateTo = date("Y-m-t", $d1);
                        break;

                    case "lyear":
                        $d1 = strtotime("-1 years");
                        $dateFrom = date("Y", $d1) . "-01-01";
                        $dateTo = date("Y", $d1) . "-12-31";
                        break;

                    case "custom":
                        $dateFrom = $_GET['from'];
                        $dateTo = $_GET['to'];
                        break;
                }

                $filename = 'idstrans' . $dateFrom;
                if($dateTo != "") {
                    $filename = $filename . '-' . $dateTo;
                }
                $filename = $filename . '.csv';

                header('Content-Type: text/csv');
                header('Content-Disposition: attachment; filename="' . $filename . '"');
                header('Pragma: no-cache');
                header('Expires: 0');

                $output = fopen('php://output', 'w');

                $dt_object = DateTime::createFromFormat('Y-m-d', $dateFrom);
                $dateStr = $dt_object->format('F d, Y');

                $flds = [ 'tkt_num', 'datetm', 'fpdatetm', 'truck', 'prod', 'cust', 'job', 'gross', 'tare', 'net', 'units', 'two_pass', 'void', 'flags'  ];
                fputcsv($output, $flds);
                $fldsStr = "";
                foreach($flds as $fld) {
                    if($fldStr != "") {
                        $fldStr = $fldStr . ',';
                    }
                    $fldStr = $fldStr . $fld;
                }

                // echo '[' . $fldStr . ']';

                //echo "where ". $where;
                if($dateFrom == $dateTo) {
                    $where = "WHERE datetm >= '" . $dateFrom . " 00:00:00' AND datetm <= '". $dateTo . " 23:59:59'";
                    //echo "Date: " . $dateStr;
                } else {
                    //echo "Date range - from: " . $dateStr;
                    if($dateTo != "") {
                        $where = "WHERE datetm >= '" . $dateFrom . " 00:00:00' AND datetm <= '". $dateTo . " 23:59:59'";
                        $dt_object = DateTime::createFromFormat('Y-m-d', $dateTo);
                        $dateStr = $dt_object->format('F d, Y');
                        //echo " To: " . $dateStr;
                    } else {
                        $where = "WHERE datetm >= '" . $dateFrom . " 00:00:00'";
                    }
                }

                $units = "";


                //$where = "datetm >= '2025-11-01' AND datetm <= '2025-11-09 23:59:59'";
                $sql = 'SELECT ' . $fldStr . ' FROM trans ' . $where . ' ORDER BY datetm;';
                $result = $conn->query($sql);

                if($result->num_rows > 0) {

                    // echo '<table><tr><th>Tran Num</th><th>date/time</th><th>Vehicle<br/>Product<br/>Customer</th><th>Gross Wt</th><th>Tare Wt</th><th>Net Wt</th><th>Image</th><th>First pass</th></tr>';
                    while($row = $result->fetch_assoc()) {

                        fputcsv($output, $row);
                    }
                } else {
                   // $row = [];
                   // $row[] = "NO";
                   // $row[] = "RECORDS";
                   // fputcsv($output, $flds);

                }
            }
        }
    }

    fclose($output);
    exit();
//}
?>
