<?php
session_start();
if(!isset($_SESSION['user']) || empty($_SESSION['user'])) {
    header("location: ../login.php"); exit();
}
?>
<!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>
<title>Transaction Report</title>
<style type="text/css" media="screen">
table tr td {
    text-align: right;
    padding: 0 15px;
}
table td:nth-child(1) {
	width: 60px;
}
table td:nth-child(2) {
	text-align: left;
	width: 130px;
}
table td:nth-child(3) {
	width: 100px; 
	text-align: left; 
}
table td:nth-child(4) {
	width: 80px;
}
table td:nth-child(5) {
	width: 80px;
}
table td:nth-child(6) {
	width: 80px;
}
table td:nth-child(7) {
	width: 140px;
}
table td:nth-child(8) {
	width: 140px;
}

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

table {
    width: 100%;
    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;
    height: 80px;
}


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;
    }
}
.trtitle {
    height: 20px;
}
.thtitle {
    height: 20px;
}
.thrange {
    height: 20px;
    font-weight: normal;
}
.thday {
    height: 25px;
}
.tdsubtot {
    height: 20px;
    font-weight: bold;
}
.tdtitle {
    text-align: left;
    background-color: #f1f1f1;

}
.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'],
];

$imgdir = '../../../images/ids/';
$svrimgdir = '/usr/share/apache2/default-site/htdocs/images/ids/';

$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/ids.php" method="GET">';
        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>';

        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">';
        echo '<label for="to"> To:</label>';
        echo '<input type="date" name="to" id="to">';
        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(!$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;
            }

            //echo "<h2>Transaction Report</h2>";

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

            $dateRange = "";

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



            $units = "";

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

            $prvDt = "";
            $dayNetWt = 0;
            $dayCnt = 0;
            $rptCnt = 0;
            $rptNetWt = 0;
            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>';
		echo '<br><br><table>';
        echo '<tr><td colspan="7" class="tdtitle"><span class="title">ID Storage Transaction Report</span><br><span class="range">' . $dateRange . '</span></td>';
        //echo '<tr class="trtitle"><th class="thtitle" colspan="7">Transaction Report</th><th class="thtitle">';
        //echo '<tr><th class="thrange" colspan="7">' . $dateRange . '</th><th class="thrange">';
        echo '<td class="tdtitle" colspan="2"><form action="idscsv.php" method="get">';
        echo '<input type="hidden" name="range" value="' . $range . '">';
        echo '<input type="hidden" name="from" value="' . $dateFrom . '">';
        echo '<input type="hidden" name="to" value="' . $dateTo . '">';
        echo '<button type="submit">Download CSV (Excel) File</button>';
        echo '</form>';

        echo '</td></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);
                    $dateStr = $dt_object->format('F d, Y');

                    if($prvDt != $dateStr) {
                        if($prvDt != "") {
                            // Daily subtotals
                            echo '<tr"><td class="tdsubtot"> </td><td class="tdsubtot">' . $prvDt .'</td><td class="tdsubtot" colspan="3">' . $dayCnt .  ' transactions</td><td class="tdsubtot">' . $dayNetWt . ' ' . $units . '</td><td colspan="3"></td></tr>';
                            //echo '<tr><td colspan="6"> <br> </td></tr>';
                            echo '</tbody>';

                            $rptCnt += $dayCnt;
                            $rptNetWt += $dayNetWt;

                            $dayCnt = 0;
                            $dayNetWt = 0;
                        }
                        $prvDt = $dateStr;

                        echo '<tbody><thread><tr><th class="thday" colspan="9">' . $dateStr . '</th></tr>';
			echo '<tr><th>Tran Num</th><th>Time</th><th>Vehicle<br/>Product<br/>Customer<br/>Job</th><th>Gross Wt</th><th>Tare Wt</th><th>Net Wt</th><th>Image</th><th>First pass</th><th></th></tr></thread>';
                    }

                    $dayNetWt += $net;
                    $dayCnt += 1;


                    echo '<tr><td><a href="/reports/idstrannum.php?num=' . $tkt_num . '">' . $tkt_num . '</a></td><td>' . $dt_object->format('h:i:s A') . '</td><td>' . $veh . '<br/>' . $prod . '<br/>' . $cust . '<br/>' . $job . '</td><td>' . $gross . ' ' . $units . '</td><td>' . $tare . ' ' . $units . '</td><td>'. $net . ' ' . $units . '</td>';
                    //$imgfile = sprintf("v%06d_1.jpg", $tkt_num);
					$imgnumstr = sprintf("%06d", $tkt_num);
					$imgfile = $dt_object->format('Y-m-d') . '/v' . $imgnumstr . '_1.jpg';
                    $img = $imgdir . $imgfile;
					if(file_exists($svrimgdir . $imgfile)) {
                        echo '<td><a href="' . $img . '"><img src="' . $img .'" width="128" height="96" ></a></td>';
                    } else {
                        echo '<td></td>';
                    }
                    //$imgfile = sprintf("v%06da_1.jpg", $tkt_num);
                    //$img = '../images/' . $imgfile;
					$imgfile = $dt_object->format('Y-m-d') . '/v' . $imgnumstr . 'a_1.jpg';
					$img = $imgdir . $imgfile;
					if(file_exists($svrimgdir . $imgfile)) {
                        echo '<td><a href="' . $img . '"><img src="' . $img .'" width="128" height="96" ></a></td>';
                    } else {
                        echo '<td></td>';
                    }
                    echo '<td></td></tr>';
                }
                if($prvDt != "") {
                    // Daily subtotals
                    //echo '<tr><td> </td><td>' . $prvDt .'</td><td colspan="2">' . $dayCnt .  ' transactions</td><td>$ ' . $tot . '</td><td colspan="3"></td></tr>';
                    echo '<tr><td class="tdsubtot"> </td><td class="tdsubtot">' . $prvDt .'</td><td class="tdsubtot" colspan="3">' . $dayCnt .  ' transactions</td><td class="tdsubtot">' . $dayNetWt . ' ' . $units . '</td><td class="tdsubtot" colspan="3"></td></tr>';

                    $rptCnt += $dayCnt;
                    $rptNetWt += $dayNetWt;

                    echo '<tr><td class="tdsubtot"> </td><td class="tdsubtot">Report Total</td><td colspan="3">' . $rptCnt . ' transactions</td><td class="tdsubtot">' . $rptNetWt  . ' ' . $units . '</td><td class="tdsubtot" colspan="3"></td></tr>';
                    echo '</tbody>';
                }

                echo '</table>';
            }
        }
    }
}

?>
</body>
</html>
