<?php
session_start();
$key = md5(date("Y-m-d").":".$_SERVER['REMOTE_ADDR']);
if ((isset($_SESSION['aW1iZXN0cmEuY29tLm15']) ? $_SESSION['aW1iZXN0cmEuY29tLm15'] : '') != $key) {
    header("location:".$_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME']);
    exit;
}

include "_header2.php";
include "_navtop.php";
include "_navside.php";
include "_functions.php";
require "conn.php";
?>

<style>
.badge-custom { padding: 6px 10px; font-size: 0.85em; }
</style>

<div id="page-wrapper">
    <div id="page-inner">
        <div class="row"><div class="col-md-12"><h2>Sales List</h2></div></div>
        <hr />

        <!-- Filter Form + Print/CSV Button -->
        <form id="filterForm" class="form-inline mb-3">
            <label for="month">Month:</label>
            <input type="month" id="month" name="month" class="form-control mx-2">

            <label for="report_type">Report Type:</label>
            <select id="report_type" name="report_type" class="form-control mx-2">
                <option value="day">Daily</option>
                <option value="month">Monthly</option>
                <option value="year">Yearly</option>
            </select>

            <button type="submit" class="btn btn-primary">Apply Filter</button>
            <button id="printBtn" class="btn btn-warning ml-2"><i class="fa fa-print"></i> Print</button>
            <button id="csvBtn" class="btn btn-info ml-2"><i class="fa-solid fa-file-csv"></i> Export</button>
        </form>
        <br>
        <!-- Chart -->
        <canvas class="pt-5" id="salesChart" height="100"></canvas>
        <br>

        <!-- Sales Table -->
        <div class="row">
            <div class="col-md-12">
                <div class="panel panel-default">
                    <div class="panel-heading">Paid Sales Records</div>
                    <div class="panel-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-bordered table-hover">
                                <thead>
                                    <tr class="small">
                                        <th>#</th>
                                        <th>Date</th>
                                        <th>Invoice No</th>
                                        <th>Customer</th>
                                        <th>Product</th>
                                        <th>Price (Per Set)</th>
                                        <th>Qty Set</th>
                                        <th>Subtotal</th>
                                        <th>Discount</th>
                                        <th>Shipping</th>
                                        <th>Tax</th>
                                        <th>Total Cost</th>
                                        <th>Grand Total</th>
                                        <th>Profit</th>
                                        <th>Payment</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody id="salesTableBody"></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<!-- LEPAS TU: DataTables -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script>
let salesChart;

function loadSalesData() {
    const month = $('#month').val();
    const report_type = $('#report_type').val();

    $.ajax({
        url: 'sales_ajax.php',
        method: 'GET',
        data: { month, report_type },
        dataType: 'json',
        success: function(res) {
            // Populate table
            $('#salesTableBody').html(res.tableHtml);
// Log the entire response to browser console
    console.log("sales_ajax response:", res);

            // Prepare legend with totals
            const totalSalesLabel   = 'Total Sales (RM: ' + Number(res.totalSales).toLocaleString(undefined,{minimumFractionDigits:2, maximumFractionDigits:2}) + ')';
            const totalCostLabel    = 'Total Cost (RM: ' + Number(res.totalCost).toLocaleString(undefined,{minimumFractionDigits:2, maximumFractionDigits:2}) + ')';
            const totalProfitLabel  = 'Total Profit (RM: ' + Number(res.totalProfit).toLocaleString(undefined,{minimumFractionDigits:2, maximumFractionDigits:2}) + ')';
            const totalTaxLabel     = 'Total Tax (RM: ' + Number(res.totalTax).toLocaleString(undefined,{minimumFractionDigits:2, maximumFractionDigits:2}) + ')';

            // Render Chart
            const ctx = document.getElementById('salesChart').getContext('2d');
            if (salesChart) salesChart.destroy();
            salesChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: res.labels,
                    datasets: [
                        {
                            label: totalSalesLabel,
                            data: res.sales,
                            backgroundColor: 'rgba(54, 162, 235, 0.7)',
                            borderColor: 'rgba(54, 162, 235, 1)',
                            borderWidth: 1
                        },
                        {
                            label: totalCostLabel,
                            data: res.cost,
                            backgroundColor: 'rgba(155, 89, 182, 0.7)',
                            borderColor: 'rgba(142, 68, 173, 1)',
                            borderWidth: 1
                        },
                        {
                            label: totalProfitLabel,
                            data: res.profit,
                            backgroundColor: 'rgba(75, 192, 192, 0.7)',
                            borderColor: 'rgba(46, 204, 113, 1)',
                            borderWidth: 1
                        },
                        {
                            label: totalTaxLabel,
                            data: res.tax,
                            backgroundColor: 'rgba(243, 156, 18, 0.7)',
                            borderColor: 'rgba(241, 196, 15, 1)',
                            borderWidth: 1
                        }
                    ]
                },
                options: {
                    responsive: true,
                    plugins: { 
                        legend: { display: true },
                        tooltip: { 
                            mode: 'index', 
                            intersect: false,
                            callbacks:{
                                label: function(context){
                                    return context.dataset.label + ': RM ' + Number(context.raw).toLocaleString(undefined,{minimumFractionDigits:2, maximumFractionDigits:2});
                                }
                            }
                        }
                    },
                    scales: {
                        x: { title: { display: true, text: report_type } },
                        y: { title: { display: true, text: 'Amount (RM)' }, beginAtZero: true }
                    }
                }
            });

            // Bind print button
            let printUrl = 'sales_print.php?report_type=' + report_type;
            if(month) printUrl += '&month=' + month;
            $('#printBtn').off('click').on('click', function(e){
                e.preventDefault();
                window.open(printUrl,'_blank');
            });

            // Bind CSV
            $('#csvBtn').off('click').on('click', function(e){
                e.preventDefault();
                window.open('sales_csv.php?report_type=' + report_type + (month ? '&month='+month : ''),'_blank');
            });

        }
    });
}

$('#filterForm').on('submit', function(e){
    e.preventDefault();
    loadSalesData();
});

$(document).ready(function() {
    loadSalesData();
});
</script>

<?php include "_footer2.php"; ?>

