<?php
session_start();
if(!isset($_SESSION['user']) || empty($_SESSION['user'])) {
    header("location: ../login.php"); exit();
}
$type = $_GET['rpttype'];
if(!$type) {
    $type = "sum";
}
?>
<!DOCTYPE html>
<html lang="en">
<script>
function toggleInputs() {
    const selectElement = document.getElementById("rangeSelect");
    const selectedValue = selectElement.value;

    const customInputs = document.getElementById("customInputs");

    // Hide all input containers initially
    customInputs.style.display = "none";

    // Show the relevant input container based on selection
    if (selectedValue === "custom") {
        customInputs.style.display = "block";
    }
}
</script>
<head>
<?php
if($type == "sum") {
	$rptTitle = "Job  Summary";
} else {
	$rptTitle = "Job  Detail";
}
echo '<title>' . $rptTitle. '</title>';
?>
<style type="text/css" media="screen">
#tblSum {
 tr td,th {
    text-align: right;
    padding: 0 15px;
}
 td:nth-child(1) { text-align: left; }
 th:nth-child(1) { text-align: left; }
}
#tblDet {
tr td,th {
    text-align: left;
    padding: 0 15px;
}
td:nth-child(1) { text-align: right; }
td:nth-child(7) { text-align: right; }
th:nth-child(4) { text-align: right; }
}

body {
    font-family: Arial, sans-serif;
    background-color: #f4f6f8;
    padding: 20px;
}

table {
    // width: 100%;
	width: 900px;
    border-collapse: collapse;
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden; /* Ensures rounded corners work */
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

thead {
    background-color: #4CAF50;
    color: white;
}

th, td {
    padding: 12px 15px;
    text-align: left;
}

tbody tr:nth-child(even) {
    background-color: #f9f9f9;
}

tbody tr:hover {
    background-color: #f1f1f1;
    transition: background-color 0.3s ease;
}

th {
    font-weight: bold;
}

/* Responsive table for small screens */
@media (max-width: 600px) {
    table, thead, tbody, th, td, tr {
        display: block;
        width: 100%;
    }
    thead tr {
        display: none; /* Hide table headers */
    }
    td {
        padding: 10px;
        text-align: right;
        position: relative;
    }
    td::before {
        content: attr(data-label);
        position: absolute;
        left: 10px;
        text-align: left;
        font-weight: bold;
        color: #555;
    }
}
.tdtitle {
    text-align: left !important;
    background-color: #f1f1f1;
    height: 60px;

}
.title {
    font-weight: bold;
}
.range {
    font-weight: normal;
}

</style>
</head>
<body>

<?php

$ranges = [
['id' => 'today', 'name' => 'Today'],
['id' => 'tweek', 'name' => 'This week'],
['id' => 'tmonth', 'name' => 'This month'],
['id' => 'tyear', 'name' => 'This year'],
['id' => 'lweek', 'name' => 'Last week'],
['id' => 'lmonth', 'name' => 'Last month'],
['id' => 'lyear', 'name' => 'Last year'],
['id' => 'custom', 'name' => 'Custom'],
];

$types = [
['id' => 'sum', 'name' => 'Summary'],
['id' => 'det', 'name' => 'Detail'],
];


$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";
        }

        echo '<form action="/reports/idsjob.php" method="GET">';

        echo '<label>Report Type: </label><select name="rpttype" id="typeSelect">';
        foreach ($types as $t):
            echo '<option value="' . $t['id'] . '"';
        if($t['id'] == $type) {
            echo " selected";
        }
        echo '>' . $t['name'];
        echo '</option>';
        endforeach;
        echo '</select>';

        echo '<label> Date Range: </label><select name="range" id="rangeSelect" onchange="toggleInputs()">';
        foreach ($ranges as $r):
            echo '<option value="' . $r['id'] . '"';
            if($r['id'] == $range) {
                echo " selected";
            }
            echo '>' . $r['name'];
            echo '</option>';
        endforeach;
        echo '</select>';

        $dateFrom = $_GET['from'];
        $dateTo = $_GET['to'];

        if($range != "custom") {
            echo '<div id="customInputs" style="display: none;">';
        } else {
            echo '<div id="customInputs">';
        }
        echo '<label for="from">From: </label>';
        echo '<input type="date" name="from" id="from" value="' . $dateFrom . '">';
        echo '<label for="to"> To: </label>';
        echo '<input type="date" name="to" id="to" value="' . $dateTo . '">';
        echo '</div>';
        echo ' ';
        echo '<input type="submit" value="Submit">';
        echo '</form>';

       $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(mysqli_connect_error()) {
            echo 'Connection error: ' . mysqli_connect_error();
        } else {
            //echo "range " . $range;
            $units = "";

            $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;
            }
            //echo "where ". $where;


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

            $dateRange = "";

            if($dateFrom == $dateTo) {
                $where = "WHERE datetm >= '" . $dateFrom . " 00:00:00' AND datetm <= '". $dateTo . " 23:59:59'";
                $dateRange = "Date: " . $dateStr;
            } else {
                $dateRange = "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');
                   $dateRange = $dateRange . " To: " . $dateStr;
                } else {
                    $where = "WHERE datetm >= '" . $dateFrom . " 00:00:00'";
                }
            }

         echo "<br>";

             if($type == "sum") {
 
          $sql = 'SELECT job, units, COUNT(*) AS CustCount, SUM(net) AS NetTotal FROM trans ' . $where . ' GROUP BY job;';
            $result = $conn->query($sql);
            if(!$result) {
                echo "query error ";
            }
            if($result->num_rows > 0) {
                $totCount = 0;
                $totNet = 0;
                echo '<table id="tblSum">';
                echo '<tr><td colspan="4" class="tdtitle"><span class="title">' . $rptTitle . '</span><br><span class="range">' . $dateRange . '</span><br></td></tr>';
		echo '<tr><th>Job</th><th>Loads</th><th>Net weight total</th><th></th></tr>';
                while($row = $result->fetch_assoc()) {
                    $job = $row['job'];
                    $units = $row['units'];

                    $count = $row['CustCount'];
                    $netTotal = $row['NetTotal'];
                    echo '<tr><td>' . $job . '</td><td>' . $count . '</td><td>' . $netTotal . ' ' . $units .'</td><td></td></tr>';
                    $totCount += $count;
                    $totNet += $netTotal;
                }
                echo '<tr><th>Total</th><th>' . $totCount . '</th><th>' . $totNet .' ' . $units . '</th><th></th></tr>';
                echo '</table>';
            }
        }
         else {

                // $sql = 'SELECT tkt_nu,prod, net FROM trans ' . $where . ' GROUP BY prod;';
                $sql = 'SELECT * FROM trans ' . $where . ' ORDER BY job,datetm;';
                //echo "sql ". $sql;
                $result = $conn->query($sql);
                if(!$result) {
                    echo "query error ";
                }
                if($result->num_rows > 0) {
                    $jobCnt = 0;
                    $rptCnt = 0;
                    $jobNetWt = 0;
                    $rptNetWt = 0;
                    $rowCnt = 0;
                    $prvJob = "";
                    echo '<table id="tblDet">';
                    echo '<tr><td colspan="8" class="tdtitle"><span class="title">' . $rptTitle . '</span><br><span class="range">' . $dateRange . '</span></td></tr>';
			echo '<tr><th>Tran Num</th><th>date/time</th><th>Vehicle</th><th>Product</th><th>Customer</th><th>Job</th><th>Net Wt</th><th></th></tr>';
                    while($row = $result->fetch_assoc()) {
                        $tkt_num = $row['tkt_num'];
                        $datetime = $row['datetm'];
                        $veh = $row['truck'];
                        $prod = $row['prod'];
                        $cust = $row['cust'];
                        $job = $row['job'];
                        //$gross = $row['gross'];
                        //$tare = $row['tare'];
                        $net = $row['net'];
                        $units = $row['units'];

	                $dt_object = DateTime::createFromFormat('Y-m-d H:i:s', $datetime);

                        if($rowCnt == 0) {
                            $prvJob = $job;
                        }

                        if($job != $prvJob) {
                            echo '<tr><th>Subtotal</th><th colspan="4"> Loads ' . $jobCnt . '</th><th>' . $prvJob. '</th><th>' . $jobNetWt .' ' . $units . '</th><th></th></tr>';

                            //echo '<tr><th>' . $prvJob. '</th><th colspan="4">Total ' . $jobCnt . ' loads</th><th>' . $jobNetWt . '</th><th></th></tr>';
                            $custCnt = 0;
                            $custNetWt = 0;

                            $prvJob = $job;
                            echo '<tr><td colspan="8"> &nbsp;  </td></tr>';
                        }

                        echo '<tr><td><a href="/reports/idstrannum.php?num=' . $tkt_num . '">' . $tkt_num . '</a></td><td>' . $dt_object->format('m/d/Y h:i:s A') . '</td><td>'  . $veh . '</td><td>' . $prod . '</td><td>' . $cust . '</td><td>' . $job .  '</td><td>'. $net  .' ' . $units . '</td><td></td>';
                        echo '</tr>';

                        $jobCnt++;
                        $rptCnt++;

                        $jobNetWt += $net;
                        $rptNetWt += $net;

                        $rowCnt++;
                    }
                    echo '<tr><th>Subtotal</th><th colspan="4"> Loads ' . $jobCnt . '</th><th>' . $prvJob. '</th><th>' . $jobNetWt .' ' . $units . '</th><th></th></tr>';
                    echo '<tr><td colspan="8">&nbsp; </td></tr>';
                    echo '<tr><th>Total</th><th colspan="4">Loads ' . $rptCnt . '</th><th></th><th>' . $rptNetWt .' ' . $units . '</th><th></th></tr>';
                    echo '</table>';

                }

            }
        }
    }
}

?>
</body>
</html>
