<?php
session_start();
if(!isset($_SESSION['user']) || empty($_SESSION['user'])) {
    header("location: ../login.php"); exit();
}
$type = $_GET['rpttype'];
if(!$type) {
    $type = "bar";
}
?>
<!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>Product Graph</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%;
    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;
}
.tdgraph {
	max-height: 300px !important;
	height: 300px;
}
</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' => 'bar', 'name' => 'Bar'],
['id' => 'pie', 'name' => 'Pie'],
];

$range = $_GET['range'];


$labels = [];
$values = [];

$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 {
   if ($data['dbtype'] != 'mysql') {
      echo "ID Storage database type must by MySQL for reporting";
   } else {

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

        echo '<label>Graph 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>';


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

           echo "<h2>Product Graph</h2>";

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


          $sql = 'SELECT prod, COUNT(*) AS ProdCount, SUM(net) AS NetTotal FROM trans ' . $where . ' GROUP BY prod;';
         // echo "SQL " . $sql . "<br>";

            $result = $conn->query($sql);
            if(!$result) {
                echo "query error ";
            }
            if($result->num_rows > 0) {
                $totCount = 0;
                $totNet = 0;
               // echo '<table id="tblSum"><tr><th>Product</th><th>Loads</th><th>Net weight total</th></tr>';
                while($row = $result->fetch_assoc()) {
                    $prod = $row['prod'];
                    $count = $row['ProdCount'];
                    $netTotal = $row['NetTotal'];
                  // echo '<tr><td>' . $prod . '</td><td>' . $count . '</td><td>' . $netTotal . '</td></tr>';
                    $totCount += $count;

                    $totNet += $netTotal;

                    $labels[] = $prod;
                    $values[] = $netTotal;
                }
               // echo '<tr><th>Total</th><th>' . $totCount . '</th><th>' . $totNet . '</th></tr>';
               // echo '</table>';


               // print_r($values);
                $quoted_array = array_map(function($string) {
                    return "'" . $string . "'";
                }, $labels);

                $lbls = implode(', ', $quoted_array);
                $tags = implode(', ', $values);
               // echo 'lbls ' . $lbls . ' values ' . $tags . '<br>';

               // echo '<table id="tblSum">';
               // echo '<tr><td colspan="2" class="tdtitle"><span class="title">Product Graph</span><br><span class="range">' . $dateRange . '</span><br></td></tr>';
		// echo '<tr><td>';

                echo '<div>';
                echo '<canvas id="myChart" style="width:100%;max-width:700px"></canvas>';
                echo '</div>';

		//echo '</td><td></td></tr>';
		//echo '</table>';

                echo '<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>';
                echo '<script>';
                echo "const ctx = document.getElementById('myChart');";

                echo "new Chart(ctx, {";
                echo "    type: '" . $type . "',";
                echo '    data: {';
                echo "        labels: [ " . $lbls . " ],";
                echo '        datasets: [{';
                echo "            label:  'Product Net Weight',";
                echo '            data: [ ' . $tags . ' ],';
                echo '            backgroundColor: ["#0074D9", "#FF4136", "#2ECC40", "#FF851B", "#7FDBFF", "#B10DC9", "#FFDC00", "#001f3f", "#39CCCC", "#01FF70", "#85144b", "#F012BE", "#3D9970", "#111111", "#AAAAAA" ],';
                echo "          borderColor: 'rgba(255, 99, 132, 1)',";
                echo '          borderWidth: 1';
                echo '        }]';
                echo '    },';
                echo '    options: {';
                echo '        scales: {';
                echo '            y: {';
                echo '                beginAtZero: true';
                echo '            }';
                echo '        }';
                echo '    }';
                echo '});';
                echo '</script>';

            }
        }
    }
}

?>

</body>
</html>
