<?php include 'auth_check.php'; ?>
<?php include 'header.php'; ?>

<?php include 'sidemenu.php'; ?>

<style>
    .highcharts-credits{
        display: none;
    }
	.hId{
		display: none;
	}
	#myCustomer{
		padding-right: 30% !important;
	}
</style>
<div class="content-wrapper">
            <div class="content-header">
                <div class="container-fluid">
                </div>
            </div>
     <!--       <section class="content">-->
     <!--           <div class="container-fluid">-->
					<!--<div class="row">-->
					<!--	<div class="col-md-2">-->
					<!--		<div class="form-group row ">-->
					<!--			<div class="col-md-12">-->
					<!--				<select type="text" class="form-select" id="cboBranch">-->
					<!--				</select>       -->
					<!--			</div>-->
					<!--		</div>-->
					<!--	</div>-->
					<!--	<div class="col-md-2">-->
					<!--		<div class="input-group date" id="datePicker1" data-date="2020-02-04" data-date-format="yyyy-mm-dd">-->
					<!--			<div class="input-group-prepend">-->
					<!--				<span class="input-group-text" style="width: 40px;">-->
					<!--					<i class="far fa-calendar-alt"></i>-->
					<!--				</span>-->
					<!--			</div>-->
					<!--			<input type="text" class="form-control" id="txtDatePicker1" value="1982-06-15" />-->
					<!--		</div>-->
					<!--	</div>-->
					<!--	<div class="col-md-2">-->
					<!--		<div class="input-group date" id="datePicker2" data-date="2020-02-04" data-date-format="yyyy-mm-dd">-->
					<!--			<div class="input-group-prepend">-->
					<!--				<span class="input-group-text" style="width: 40px;">-->
					<!--					<i class="far fa-calendar-alt"></i>-->
					<!--				</span>-->
					<!--			</div>-->
					<!--			<input type="text" class="form-control" id="txtDatePicker2" value="1982-06-15" />-->
					<!--		</div>-->
					<!--	</div>-->
					<!--</div>-->
					<!--<div class="row mt-3">-->
					<!--	<div class="col-md-4">-->
					<!--		<div class="card card-outline">-->
					<!--			<div class="card-body p-0 chart-responsive">-->
									<!-- Use a canvas element for the chart -->
					<!--				<canvas id="categoryPieChart" style="height: 300px;"></canvas>-->
					<!--			</div>-->
					<!--		</div>-->
					<!--	</div>-->
					<!--	<div class="col-md-4">-->
					<!--		<div class="card card-outline">-->
					<!--			<div class="card-body p-0 chart-responsive">-->
									<!-- Use a canvas element for the chart -->
					<!--				<canvas id="receivable" style="height: 300px;"></canvas>-->
					<!--			</div>-->
					<!--		</div>-->
					<!--	</div>-->
					<!--	<div class="col-md-4">-->
					<!--		<div class="card card-outline">-->
					<!--			<div class="card-body p-0 chart-responsive">-->
									<!-- Use a canvas element for the chart -->
					<!--				<canvas id="payable" style="height: 300px;"></canvas>-->
					<!--			</div>-->
					<!--		</div>-->
					<!--	</div>-->
					<!--</div>-->
					<!--<div class="row mt-3">-->
					<!--	<div class="col-md-6">-->
					<!--		<div class="card card-outline">-->
					<!--			<div class="card-body p-0 chart-responsive">-->
									<!-- Use a canvas element for the chart -->
					<!--				<canvas id="SalesByDateChart" style="height: 300px;"></canvas>-->
					<!--			</div>-->
					<!--		</div>-->
					<!--	</div>-->
					<!--	<div class="col-md-6">-->
					<!--		<div class="card card-outline">-->
					<!--			<div class="card-body p-0 chart-responsive">-->
									<!-- Use a canvas element for the chart -->
					<!--				<canvas id="cashInOut" style="height: 300px;"></canvas>-->
					<!--			</div>-->
					<!--		</div>-->
					<!--	</div>-->
					<!--</div>-->
     <!--           </div>-->
     <!--       </section>-->
        </div>
 <?php include 'footer.php'; ?>

 <script>
	var d = new Date();
	var n = d.getTime();
	var customDate = d.toISOString().split('T')[0]; // Format as yyyy-mm-dd

	var firstOfMonth = new Date(d.getFullYear(), d.getMonth(), 1);
	var formattedFirstOfMonth = $.datepicker.formatDate('yy-mm-dd', firstOfMonth);

	$(function() {  
        
        $("body").addClass("sidebar-collapse");	
		// getAllBranch();
		$('#txtDatePicker1, #txtDatePicker2').datepicker({
			changeMonth: true,
			changeYear: true,
			dateFormat: 'yy-mm-dd',
			showButtonPanel: true,
			showAnim: 'clip',
		}).val(customDate);

	$('#txtDatePicker1').val(formattedFirstOfMonth);

    // Set the second date picker to the current date
    $('#txtDatePicker2').val(customDate);


    });

	function getAllBranch(){
		$("#cboBranch").find("option").remove();
		$.ajax({
			url: APP_URL + "api/branch/get_all_rows.php"
		}).done(function(data) {
			$.each(data.records, function(i, v) {
				$("#cboBranch").append("<option value = '" + v.id + "' code= '" + v.code + "' >" + v.branch + "</option>");
			});
			getChartCategoryPie();
			getChartReceivable();
			getChartPayable();
			getChartSalesByDate();
			getChartCashInOut();
		});
	}

	$("#cboBranch,#txtDatePicker1,#txtDatePicker2").change(function(){
        getChartCategoryPie();
		getChartReceivable();
		getChartPayable();
		getChartSalesByDate();
		getChartCashInOut();
    });

	function getChartCategoryPie() {
		$("#loading").show();
		
		$.ajax({
			type: "POST",
			url: APP_URL + "api/utils/get_chart_category_pie.php",
			data: JSON.stringify({
				branch_id: $("#cboBranch").val(),
				df: $("#txtDatePicker1").val(),
				dt: $("#txtDatePicker2").val()
			}),
			contentType: "application/json"
		}).done(data => {
			const ctx = document.getElementById("categoryPieChart").getContext("2d");
			if (window.categoryPieChart instanceof Chart) window.categoryPieChart.destroy();
			
			window.categoryPieChart = new Chart(ctx, {
				type: "doughnut",
				data: {
					labels: data.container_category,
					datasets: [{
						data: data.container_amount,
						backgroundColor: Array.from({ length: data.container_category.length }, () => `rgba(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, 0.7)`),
						borderWidth: 1,
					}],
				},
				options: {
					responsive: true,
					maintainAspectRatio: false,
					layout: {
						padding: {
							top: 5,
							bottom: 5,
							left: 10,
							right: 10
						}
					},
					plugins: {
						legend: {
							position: "right",
							align: "center",
							labels: {
								boxWidth: 12, // Reduce the box width to give more space for text
								font: {
									size: 10 // Adjust font size if needed
								},
								fullSize: true, // Ensure legend uses the available space
								textAlign: "start", // Align text properly
							}
						},
						tooltip: {
							callbacks: {
								label: tooltipItem => `${tooltipItem.label}: ${tooltipItem.raw.toLocaleString()}`
							}
						},
						title: {
							display: true,
							text: `Expenses (Total: ${data.total_amount})`,
						},
					},
				},
			});
		}).fail((xhr, status, error) => {
			console.error("Error fetching chart data:", status, error);
		}).always(() => $("#loading").hide());
	}

	function getChartReceivable() {
		$("#loading").show();

		$.ajax({
			type: "POST",
			url: APP_URL + "api/utils/get_receivable.php",
			data: JSON.stringify({
				branch_id: $("#cboBranch").val(),
				df: $("#txtDatePicker1").val(),
				dt: $("#txtDatePicker2").val()
			}),
			contentType: "application/json"
		}).done(data => {
			const ctx = document.getElementById("receivable").getContext("2d");

			// Destroy existing chart instance if it exists
			if (window.receivableChart instanceof Chart) window.receivableChart.destroy();

			// Compute Receivables as Sales - Payments
			const totalSales = data.container_sales[0] || 0;
			const totalPayments = data.container_payment[0] || 0;
			const totalReceivables = totalSales - totalPayments;

			window.receivableChart = new Chart(ctx, {
				type: "bar", // Stacked column chart
				data: {
					labels: ["Receivables Summary"], // Only one column
					datasets: [
						{
							label: "Payments",
							data: [totalPayments], // Payments go at the bottom
							backgroundColor: `rgba(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, 0.7)`, // Payments color
							borderWidth: 1
						},
						{
							label: "Receivables",
							data: [totalReceivables], // Receivables take the remaining space
							backgroundColor: `rgba(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, 0.7)`, // Receivables color
							borderWidth: 1
						}
					]
				},
				options: {
					responsive: true,
					maintainAspectRatio: false,
					layout: {
						padding: {
							top: 5,
							bottom: 5,
							left: 10,
							right: 10
						}
					},
					plugins: {
						legend: {
							position: "top",
							align: "center"
						},
						tooltip: {
							callbacks: {
								label: function(tooltipItem) {
									return `${tooltipItem.dataset.label}: ${tooltipItem.raw.toLocaleString()}`; // Format numbers with commas
								}
							}
						},
						title: {
							display: true,
							text: `Receivables & Payments Breakdown (Total Sales: ${totalSales.toLocaleString()})`,
						}
					},
					scales: {
						y: {
							stacked: true, // Enable stacking
							beginAtZero: true, // Start from zero
							max: totalSales, // Ensure total height = sales amount
							ticks: {
								callback: function(value) {
									return value.toLocaleString(); // Format Y-axis values
								}
							}
						},
						x: {
							stacked: true // Enable stacking on X-axis as well
						}
					},
					barPercentage: 0.5, // Adjust bar thickness (optional)
					categoryPercentage: 0.5 // Reduce spacing (optional)
				}
			});
		}).fail((xhr, status, error) => {
			console.error("Error fetching chart data:", status, error);
		}).always(() => $("#loading").hide());
	}

	function getRandomColor(alpha = 0.7) {
    return `rgba(${Math.floor(Math.random() * 255)}, 
                 ${Math.floor(Math.random() * 255)}, 
                 ${Math.floor(Math.random() * 255)}, ${alpha})`;
}

	function getChartPayable() {
		$("#loading").show();

		$.ajax({
			type: "POST",
			url: APP_URL + "api/utils/get_payable.php",
			data: JSON.stringify({
				branch_id: $("#cboBranch").val(),
				df: $("#txtDatePicker1").val(),
				dt: $("#txtDatePicker2").val()
			}),
			contentType: "application/json"
		}).done(data => {
			const ctx = document.getElementById("payable").getContext("2d");

			// Destroy existing chart instance if it exists
			if (window.payableChart instanceof Chart) window.payableChart.destroy();

			// Extract data correctly
			const totalPurchase = data.container_purchase[0] || 0;
			const totalPayments = data.container_payment[0] || 0;
			const totalPayable = data.container_payable[0] || 0;

			window.payableChart = new Chart(ctx, {
				type: "bar", // Stacked column chart
				data: {
					labels: ["Payables Summary"], // Only one column
					datasets: [
						{
							label: "Payments",
							data: [totalPayments], // Payments at the bottom
							backgroundColor: getRandomColor(),
							borderWidth: 1
						},
						{
							label: "Remaining Payable",
							data: [totalPayable], // Remaining payable on top
							backgroundColor: getRandomColor(),
							borderWidth: 1
						}
					]
				},
				options: {
					responsive: true,
					maintainAspectRatio: false,
					plugins: {
						legend: {
							position: "top",
							align: "center"
						},
						tooltip: {
							callbacks: {
								label: function(tooltipItem) {
									return `${tooltipItem.dataset.label}: ${tooltipItem.raw.toLocaleString()}`; // Format numbers with commas
								}
							}
						},
						title: {
							display: true,
							text: `Payables Breakdown (Total Purchase: ${totalPurchase.toLocaleString()})`
						}
					},
					scales: {
						y: {
							stacked: true, // Enable stacking
							beginAtZero: true,
							max: totalPurchase, // Ensure total height = purchase amount
							ticks: {
								callback: function(value) {
									return value.toLocaleString(); // Format Y-axis values
								}
							}
						},
						x: {
							stacked: true // Enable stacking on X-axis as well
						}
					},
					barPercentage: 0.5, // Adjust bar thickness (optional)
					categoryPercentage: 0.5 // Reduce spacing (optional)
				}
			});
		}).fail((xhr, status, error) => {
			console.error("Error fetching chart data:", status, error);
		}).always(() => $("#loading").hide());
	}




	function getChartSalesByDate() {
    $("#loading").show();

    $.ajax({
        type: "POST",
        url: APP_URL + "api/utils/get_sales_by_date.php",
        data: JSON.stringify({
            branch_id: $("#cboBranch").val(),
			df: $("#txtDatePicker1").val(),
			dt: $("#txtDatePicker2").val()
        }),
        contentType: "application/json"
    }).done(data => {
        // Ensure the required data exists before proceeding
        if (!data.container_date || !data.container_sales) {
            console.error("Missing data for chart rendering");
            return;
        }

        // Sort the dates (if they are strings, they will be sorted as strings)
        const sortedData = data.container_date.map((date, index) => ({
            date,
            sales: data.container_sales[index]
        })).sort((a, b) => new Date(a.date) - new Date(b.date)); // Sorting based on date

        const sortedDates = sortedData.map(item => item.date);
        const sortedSales = sortedData.map(item => item.sales);

        const ctx = document.getElementById("SalesByDateChart").getContext("2d");

        // Destroy previous chart instance if it exists
        if (window.salesByDateChart instanceof Chart) window.salesByDateChart.destroy();

        // Create new line chart
        window.salesByDateChart = new Chart(ctx, {
            type: "line", // Line chart type
            data: {
                labels: sortedDates, // Sorted dates
                datasets: [{
                    label: 'Sales Amount',
                    data: sortedSales, // Sorted sales amounts
                    // borderColor: 'rgba(54, 162, 235, 1)', // Line color for sales
                    // backgroundColor: 'rgba(54, 162, 235, 0.2)', // Fill color under the line
                    // borderWidth: 2,
                    pointBackgroundColor: `rgba(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, 0.7)`, // Color for points
                    pointRadius: 5
                }],
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                layout: {
                    padding: {
                        top: 10,
                        bottom: 10,
                        left: 15,
                        right: 15
                    }
                },
                plugins: {
                    legend: {
                        position: "top",
                        align: "center",
                        labels: {
                            boxWidth: 12,
                            font: {
                                size: 12
                            },
                            fullSize: true,
                            textAlign: "start",
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(tooltipItem) {
                                // Add localized number formatting for amounts
                                return `${tooltipItem.dataset.label}: ${tooltipItem.raw.toLocaleString()}`;
                            }
                        }
                    },
                    title: {
                        display: true,
                        text: `Sales (Total: ${data.totalSales})`,
                        font: {
                            size: 14,
                            weight: 'bold'
                        }
                    },
                },
                scales: {
                    y: {
                        beginAtZero: true, // Ensure Y-axis starts from zero
                        ticks: {
                            callback: function(value) {
                                return value.toLocaleString(); // Format Y-axis ticks with commas
                            }
                        }
                    }
                }
            },
        });
    }).fail((xhr, status, error) => {
        // Improved error logging
        console.error("Error fetching chart data:", status, error);
        alert("Failed to load chart data. Please try again later.");
    }).always(() => $("#loading").hide());
}

function getChartCashInOut() {
    $("#loading").show();

    $.ajax({
        type: "POST",
        url: APP_URL + "api/utils/get_cash_in_out.php",
        data: JSON.stringify({
            branch_id: $("#cboBranch").val(),
            df: $("#txtDatePicker1").val(),
            dt: $("#txtDatePicker2").val()
        }),
        contentType: "application/json"
    }).done(data => {
        // Ensure the required data exists before proceeding
        if (!data.container_date2 || !data.container_cashin || !data.container_cashout) {
            console.error("Missing data for chart rendering");
            return;
        }

        // Sort the dates (if they are strings, they will be sorted as strings)
        const sortedData = data.container_date2.map((date, index) => ({
            date,
            cashin: data.container_cashin[index],
            cashout: data.container_cashout[index]
        })).sort((a, b) => new Date(a.date) - new Date(b.date)); // Sorting based on date

        const sortedDates = sortedData.map(item => item.date);
        const sortedCashIn = sortedData.map(item => item.cashin);
        const sortedCashOut = sortedData.map(item => item.cashout);

        const ctx = document.getElementById("cashInOut").getContext("2d");

        // Destroy previous chart instance if it exists
        if (window.cashInOut instanceof Chart) window.cashInOut.destroy();

        // Create new bar chart
        window.cashInOut = new Chart(ctx, {
            type: "bar", // Bar chart type
            data: {
                labels: sortedDates, // Sorted dates
                datasets: [
                    {
                        label: 'Cash In',
                        data: sortedCashIn, // Sorted cash-in amounts
                        backgroundColor: `rgba(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, 0.7)`, // Cash-in bar color
                        // borderColor: 'rgba(54, 162, 235, 1)', // Cash-in border color
                        borderWidth: 1
                    },
                    {
                        label: 'Cash Out',
                        data: sortedCashOut, // Sorted cash-out amounts
                        backgroundColor: `rgba(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, 0.7)`, // Cash-out bar color
                        // borderColor: 'rgba(255, 99, 132, 1)', // Cash-out border color
                        borderWidth: 1
                    }
                ],
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                layout: {
                    padding: {
                        top: 10,
                        bottom: 10,
                        left: 15,
                        right: 15
                    }
                },
                plugins: {
                    legend: {
                        position: "top",
                        align: "center",
                        labels: {
                            boxWidth: 12,
                            font: {
                                size: 12
                            },
                            fullSize: true,
                            textAlign: "start",
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(tooltipItem) {
                                // Add localized number formatting for amounts
                                return `${tooltipItem.dataset.label}: ${tooltipItem.raw.toLocaleString()}`;
                            }
                        }
                    },
                    title: {
                        display: true,
                        text: `Cash In & Out (Total Cash In: ${data.totalCashIn}, Total Cash Out: ${data.totalCashOut})`,
                        font: {
                            size: 14,
                            weight: 'bold'
                        }
                    },
                },
                scales: {
                    y: {
                        beginAtZero: true, // Ensure Y-axis starts from zero
                        ticks: {
                            callback: function(value) {
                                return value.toLocaleString(); // Format Y-axis ticks with commas
                            }
                        }
                    }
                }
            },
        });
    }).fail((xhr, status, error) => {
        // Improved error logging
        console.error("Error fetching chart data:", status, error);
        alert("Failed to load chart data. Please try again later.");
    }).always(() => $("#loading").hide());
}








</script>