<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include 'services/session.php';

// Retrieve invoice_id from the URL
$invoice_id = isset($_GET['invoice_id']) ? $_GET['invoice_id'] : null;

// Now you can use $invoice_id in your code

?>

<!DOCTYPE html>
<html lang="en">

<head>

    <?php $title = "Income Statement Details";
    include 'partials/title-meta.php'; ?>
    
        <link href="assets/libs/spectrum-colorpicker2/spectrum.min.css" rel="stylesheet" type="text/css">
    <link href="assets/libs/flatpickr/flatpickr.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/clockpicker/bootstrap-clockpicker.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/bootstrap-datepicker/css/bootstrap-datepicker.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/bootstrap-datepicker/css/bootstrap-datepicker.min.css" rel="stylesheet" type="text/css" />

    <?php include 'partials/head-css.php'; ?>

</head>

<?php include 'partials/body.php'; ?>

<!-- Begin page -->
<div id="wrapper">

    <?php $pagetitle = "Income Statement Details";
    include 'partials/menu.php'; ?>
            
            <!-- ============================================================== -->
            <!-- Start Page Content here -->
            <!-- ============================================================== -->

            <div class="content-page">
                <div class="content">

                  <!-- Start Content-->
                  <div class="container-fluid">

                    <div class="row">
                        <div class="col-md-12">
                            <div class="card">
                                <div class="card-body">
                                 
                                    <div class="panel-body">
                                        <div class="clearfix">
                                            <div class="float-start">
                                                <h3>Faida Accounting System</h3>
                                            </div>
                                            <div class="float-end">
                                                <h4>Invoice # <br>
                                                    <strong><?php echo $invoice_id; ?></strong>
                                                </h4>
                                            </div>
                                        </div>
                                        <hr>
                                        <div class="clearfix">
                                            
                                                <div class="col-lg-4">
                                                    <div class="mb-3">
                                                        <label class="form-label">Generate Month Wise</label>
                                                        <input type="text" class="form-control" data-provide="datepicker" id="datepicker"
                                                            data-date-format="MM yyyy" data-date-min-view-mode="1" data-date-autoclose="true">
                                                    </div>
                                                </div>
                                                <div class="col-lg-4">
                                                    <div class="d-print-none mt-4">
                                                        <button class="btn btn-success waves-effect waves-light" id="generateIncomeStatementBtn">Generate Income Statement</button>
                                                    </div>
                                                </div>
                                        </div>
                                        <hr>
                                        <div class="row">
                                            <div class="col-md-12">
    
                                                <div class="float-start mt-3">
                                                    <address>
                                                        <strong>Twitter, Inc.</strong><br>
                                                        795 Folsom Ave, Suite 600<br>
                                                        San Francisco, CA 94107<br>
                                                        <abbr title="Phone">P:</abbr> (123) 456-7890
                                                    </address>
                                                </div>
                                                <div class="float-end mt-3">
                                                    <p><strong>Order Date: </strong> Jan 17, 2016</p>
                                                    <p class="m-t-10"><strong>Order Status: </strong> <span class="label label-pink">Pending</span></p>
                                                    <p class="m-t-10"><strong>Order ID: </strong> #123456</p>
                                                </div>
                                            </div><!-- end col -->
                                        </div>
                                        <!-- end row -->
    
                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="table-responsive">
                                                    <table class="table mt-4">
                                                        <thead>
                                                        <tr>
                                                            <th>Month</th>
                                                            <th>Total Invoices</th>
                                                            <th>Total Expenses</th>
                                                            <th>Net Income</th>
                                                        </tr></thead>
                                                        <tbody id="incomeStatementTableBody">
                                                            <!-- Table rows will be dynamically added here -->
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-xl-6 col-6">
                                                <div class="clearfix mt-4">
                                                    <h5 class="small text-dark fw-normal">PAYMENT TERMS AND POLICIES</h5>
    
                                                    <small>
                                                        All accounts are to be paid within 7 days from receipt of
                                                        invoice. To be paid by cheque or credit card or direct payment
                                                        online. If account is not paid within 7 days the credits details
                                                        supplied as confirmation of work undertaken will be charged the
                                                        agreed quoted fee noted above.
                                                    </small>
                                                </div>
                                            </div>
                                            <div class="col-xl-3 col-6 offset-xl-3">
                                                <p class="text-end"><b>Sub-total:</b> </p>
                                                <p class="text-end">Discout: </p>
                                                <p class="text-end">VAT: </p>
                                                <hr>
                                                <h3 class="text-end" id="netIncomeDisplay">USD 0.00</h3>
                                            </div>
                                        </div>
                                        <hr>
                                        <div class="d-print-none">
                                            <div class="float-end">
                                                <a href="javascript:window.print()" class="btn btn-dark waves-effect waves-light"><i class="fa fa-print"></i></a>
                                            </div>
                                            

                                            <div class="clearfix"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                          
                        </div>

                    </div>
                    <!-- end row -->        
                    
                </div> <!-- container-fluid -->

                </div> <!-- content -->

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

            </div>

            <!-- ============================================================== -->
            <!-- End Page content -->
            <!-- ============================================================== -->


        </div>
        <!-- END wrapper -->

        <?php include 'partials/right-sidebar.php'; ?>

        <?php include 'partials/footer-scripts.php'; ?>
        <script src="assets/libs/flatpickr/flatpickr.min.js"></script>
        <script src="assets/libs/spectrum-colorpicker2/spectrum.min.js"></script>
        <script src="assets/libs/clockpicker/bootstrap-clockpicker.min.js"></script>
        
        
        <!-- Init js <script src="assets/libs/bootstrap-datepicker/js/bootstrap-datepicker.min.js"></script>-->
        <script src="assets/js/pages/form-pickers.init.js"></script>

        <!-- App js -->
        <script src="assets/js/app.min.js"></script>
        <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
        
        <script>
  
            $(document).ready(function () {
            var selectedMonth; // declare selectedMonth at a higher scope
        
            $('#generateIncomeStatementBtn').on('click', function () {
                generateIncomeStatement();
            });
        
            $('#datepicker').datepicker({
                format: 'mm/yyyy',
                autoclose: true,
                minViewMode: 1
            });
        
            function generateIncomeStatement() {
                // Get the selected date from the datepicker
                var selectedDate = $('#datepicker').datepicker('getDate');
        
                // Check if the selected date is not null
                if (selectedDate !== null) {
                    // Update the selectedMonth variable
                    selectedMonth = selectedDate.getMonth() + 1; // Months are zero-based
        
                    // Make an AJAX request for the selected month and year
                    $.ajax({
                        type: 'POST',
                        url: 'inc_statement.php',
                        data: { month: selectedMonth, year: selectedDate.getFullYear() },
                        success: function (response) {
                            updateIncomeStatement(response);
                        },
                        error: function (error) {
                            console.error('Error fetching income statement data:', error);
                        }
                    });
                }
            }
            
            function updateIncomeStatement(data) {
                // Clear existing rows in the table
                $('#incomeStatementTableBody').empty();
            
                // Filter the data for the selected month
                var filteredData = data.monthlyData.filter(function (monthData) {
                    // Convert the month name to the numeric representation (1-12)
                    var monthNumber = new Date(Date.parse(monthData.month + " 1, 2023")).getMonth() + 1;
            
                    return monthNumber === selectedMonth;
                });
            
                // Check if data is empty or not
                if (filteredData.length === 0) {
                    console.log('No data found for the selected month and year.');
                    return;
                }
            
                // Loop through each month's data and add a row for each
                for (var i = 0; i < filteredData.length; i++) {
                    var monthData = filteredData[i];
            
                    var rowHtml = '<tr>' +
                        '<td>' + monthData.month + '</td>' +
                        '<td>' + '$' + (Number(monthData.totalInvoices) || 0).toFixed(2) + '</td>' +
                        '<td>' + '$' + (Number(monthData.totalExpenses) || 0).toFixed(2) + '</td>' +
                        '<td>' + '$' + (Number(monthData.netIncome) || 0).toFixed(2) + '</td>' +
                        '</tr>';
            
                    $('#incomeStatementTableBody').append(rowHtml);
                }
            
                // Display net income in the specified <h3> element
                var totalNetIncome = filteredData[0].netIncome;
                $('#netIncomeDisplay').text('$' + (Number(totalNetIncome) || 0).toFixed(2));
            }

        
           /* function updateIncomeStatement(data) {
                // Log the selected month
                console.log('Selected month:', selectedMonth);
            
                // Log the received data to check its structure
                console.log('Received data:', data);
            
                // Check if data.monthlyData is not undefined or null
                if (data.monthlyData) {
                    // Log the entire monthlyData array
                    console.log('Monthly data:', data.monthlyData);
            
                    // Filter the data for the selected month
                    var filteredData = data.monthlyData.filter(function (monthData) {
                    // Convert the month name to the numeric representation (1-12)
                    var monthNumber = new Date(Date.parse(monthData.month + " 1, 2023")).getMonth() + 1;
            
                    return monthNumber === selectedMonth;
                });
            
                    // Log the filtered data to check its contents
                    console.log('Filtered data:', filteredData);
            
                    // Check if filtered data is not empty
                    if (filteredData.length > 0) {
                        // Loop through each month's data and add a row for each
                        for (var i = 0; i < filteredData.length; i++) {
                            var monthData = filteredData[i];
            
                            var rowHtml = '<tr>' +
                                '<td>' + monthData.month + '</td>' +
                                '<td>' + '$' + (Number(monthData.totalInvoices) || 0).toFixed(2) + '</td>' +
                                '<td>' + '$' + (Number(monthData.totalExpenses) || 0).toFixed(2) + '</td>' +
                                '<td>' + '$' + (Number(monthData.netIncome) || 0).toFixed(2) + '</td>' +
                                '</tr>';
            
                            $('#incomeStatementTableBody').append(rowHtml);
                        }
                    } else {
                        console.log('No data found for the selected month and year.');
                    }
                } else {
                    console.log('No monthly data received.');
                }
            } */
            
            
            });
        
        </script>



    </body>
</html>