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

<div class="page-header d-print-none">
    <div class="container-xl">
        <div class="row g-2 align-items-center">
            <div class="col d-flex justify-content-between">
                <h2 class="page-title">Monthly Report</h2>
            </div>
        </div>
    </div>
</div>

<div class="page-body">
    <div class="container-xl">
        <div class="row row-cards">
            <div class="col-12">
				<div class="row">
					<div class="col-3 mb-3 row">
						<label class="col-4 col-form-label text-end">Date From</label>
						<div class="col">
							<input type="text" class="flatpickr flatpickr-input active form-control" id="dateFrom" required>
						</div>
					</div>
					<div class="col-3 mb-3 row">
						<label class="col-4 col-form-label text-end">Date To</label>
						<div class="col">
							<input type="text" class="flatpickr flatpickr-input active form-control" id="dateTo" required>
						</div>
					</div>
				</div>

				<div class="d-flex justify-content-end">
                    <div class="export-buttons-container" style="margin-bottom: 10px;">
                        <button id="exportCSV" class="btn btn-outline-primary">Export to CSV</button>
                        <button id="exportExcel" class="btn btn-outline-primary">Export to Excel</button>
                        <button id="exportPDF" class="btn btn-outline-primary">Export to PDF</button>
                        <button id="printTable" class="btn btn-outline-primary">Print Table</button>
                    </div>
                </div>
				<div class="card">
					<div class="mb-3 mt-3 table-responsive" >
						<table class="table table-vcenter card-table" id="myTable">
							<thead style="position: sticky; top: 0; z-index: 10;">
								<tr>
									<th style="width: 30%">Description</th>
									<th style="width: 20%" class="text-end">Cash In</th>
									<th style="width: 30%">Description</th>
									<th style="width: 20%" class="text-end">Cash Out</th>
								</tr>
							</thead>
							<tbody>
							</tbody>
						</table>
					</div>
				</div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="myModalIncome" tabindex="-1" aria-labelledby="myModalIncomeLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="mdtitle"></h5>
                <h5 class="modal-title" id="mdtitle1"></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="card card-md">
                    <div class="card-body p-0">
                        <!-- Table with max height and scrollable -->
                        <div class="table-responsive" style="max-height: 500px; overflow-y: auto;">
                            <table class="table table-striped table-hover" id="myTable1">
                                <thead class="sticky-top bg-light">
                                    <tr>
                                        <th style="width: 3%;">#</th>
                                        <th style="width: 10%;">Date</th>
                                        <th style="width: 30%;">Description</th>
                                        <th style="width: 30%;">Particular</th>
                                        <th style="width: 10%;">Amount</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Rows will be populated here -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

 
<?php include '../footer.php'; ?>

<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.4.0/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.25/jspdf.plugin.autotable.min.js"></script>

<script>
	var today = new Date().toISOString().split('T')[0];
	const today1 = new Date();
	const firstDayOfMonth = new Date(today1.getFullYear(), today1.getMonth(), 1);

$(function() {
	flatpickr("#dateFrom", {
		dateFormat: "Y-m-d",
		defaultDate: firstDayOfMonth, // Set to first day of the current month
		maxDate: today,               // Restrict selection to today or earlier
	});
	flatpickr("#dateTo", {
        dateFormat: "Y-m-d", 
        defaultDate: today,  
        maxDate: today,      
    });
	getAll();
});

$("#dateFrom, #dateTo").change(function() {
    getAll();
});

	var BAL = 0 ;
	var COL = "" ;
    function getAll(){

		var df =$("#dateFrom").val();
		var dt =$("#dateTo").val();

		$("#myTable").find("tbody").find("tr").remove();
		$.ajax({
			type: "POST",
			url: APP_URL + "api/sales/search_monthly_report.php",
			data: JSON.stringify({ df: df,dt: dt}),
		}).done(function(data) {	
			$.each(data.records_in, function(i, v) {
				var s="In";
				$("#myTable").find("tbody")
				.append($('<tr>')
					.append("<td onclick='getDetail(\"" + s + "\",\"" + v.description + "\",\"" + Number(v.cash_in).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + "\");' style='color:blue;cursor:pointer;'>" + v.description + "</td>")
					.append("<td style='text-align:right;' >" + Number(v.cash_in).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + "</td>")
					.append("<td></td>")
                    .append("<td></td>")
					)
			});	
              $.each(data.records_out, function(i, v) {
				var s="Out";

				$("#myTable").find("tbody")
				.append($('<tr>')
                    .append("<td></td>")
                    .append("<td></td>")
					.append("<td onclick='getDetail(\"" + s + "\",\"" + v.description + "\",\"" + Number(v.cash_out).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + "\");' style='color:blue;cursor:pointer;'>" + v.description + "</td>")
					.append("<td style='text-align:right;'>" + Number(v.cash_out).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + "</td>")
					)
			});	
			$("#myTable").find("tbody")
					.append($('<tr>')
                    .append("<td></td>")
                    .append("<td></td>")
					.append("<td></td>")
					.append("<td></td>")
					)


			$("#myTable").find("tbody")
			.append($('<tr style="font-weight:bold;">')
            .append("<td colspan='1' style='text-align:left;'>Total</td>")
            .append("<td style='text-align:right;'>" + ((data.cash_in_total)?Number(data.cash_in_total).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }):0) + "</td>")
			.append("<td style='text-align:left;'>Total</td>")
			.append("<td style='text-align:right;'>" + ((data.cash_out_total)?Number(data.cash_out_total).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }):0) + "</td>")
  			); 

			  var $bc="";
			if(parseInt(data.cash_balance)<0){
				 $bc="color:red;";
				 COL ="color:red;";
			}else{
				$bc="";
				COL ="";
			}
			BAL = data.cash_balance;

            $("#myTable").find("tbody")
			.append($('<tr style="font-weight:bold;">')
            .append("<td colspan='3' style='text-align:right;'>Balance Amount</td>")
			.append("<td style='text-align:right;"+$bc+"'>" + ((data.cash_balance)?Number(data.cash_balance).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }):0) + "</td>")
  			); 


       });

	}	

	function getDetail(r,st,amt){

		$("#myModalIncome").modal('show');
		$("#mdtitle").text(st);

		$("#myTable1").find("tbody tr").remove();
		var df =$("#dateFrom").val();
		var dt =$("#dateTo").val();
		$.ajax({
			url: APP_URL + "api/sales/get_monthly_detail.php",
			type: "POST",
			data: JSON.stringify({ r:r, df: df, dt: dt, st:st, ym:"" })
		}).done(function(data){
			console.log(data.records)
				$.each(data.records, function(i, v) {
					$("#myTable1").find("tbody")
						.append($('<tr>')
							.append("<td style='width: 10px'>" + (i+1) + "</td>")
							.append("<td>" + v.date + "</td>")
							.append("<td>" + v.description + "</td>")
							.append("<td>" + v.particular + "</td>")
							.append("<td  style='text-align:right;'>" + Number(v.amount).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + "</td>")
						)
				});
				$("#mdtitle1").text(Number(data.total_amountF).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }));
		});		
	}

    // Export to CSV
    $("#exportCSV").click(function () {
        var table = document.getElementById("myTable");
        var rows = table.querySelectorAll("tr");
        var csvContent = "";

        rows.forEach(function (row) {
            var cols = row.querySelectorAll("td, th");
            var rowData = [];
            cols.forEach(function (col) {
                rowData.push('"' + col.innerText.replace(/"/g, '""') + '"');
            });
            csvContent += rowData.join(",") + "\n";
        });

        var blob = new Blob([csvContent], { type: "text/csv" });
        var link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = "monthly_report.csv";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    });

    // Export to Excel
    $("#exportExcel").click(function () {
        var table = document.getElementById("myTable");
        var workbook = XLSX.utils.table_to_book(table, { sheet: "Monthly Report" });
        XLSX.writeFile(workbook, "monthly_report.xlsx");
    });

    // Export to PDF
    $("#exportPDF").click(function () {
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF();

        doc.text("Monthly Report", 14, 10);

        doc.autoTable({
            html: "#myTable",
            startY: 20,
            styles: { fontSize: 10 },
        });

        doc.save("monthly_report.pdf");
    });

    // Print Table
    $("#printTable").click(function () {
        var printContents = document.getElementById("myTable").outerHTML;
        var printWindow = window.open("", "_blank");
        printWindow.document.open();
        printWindow.document.write(`
            <html>
                <head>
                    <title>Print Table</title>
                    <style>
                        table { border-collapse: collapse; width: 100%; }
                        table, th, td { border: 1px solid black; }
                        th, td { padding: 8px; text-align: left; }
                    </style>
                </head>
                <body>
                    ${printContents}
                </body>
            </html>
        `);
        printWindow.document.close();
        printWindow.print();
    });
</script>
