<?php
session_start();
require_once('../connect.php');
require_once('sql_required.php');

if (!isset($_SESSION['username'])) {
  header("Location: ../index.php");
  exit;
}

$datetoday = date('Y-m-d');
$active_tab = "dashboard";

if (isset($_POST['save_data'])) {
  $readingdate = $_POST['reading'];
  $duedate = $_POST['due'];
  $disconnectiondate = $_POST['disconnection'];

  $update_reading = "UPDATE tbl_reading_sched SET reading_date = '$readingdate', due_date = '$duedate', disconnection_date = '$disconnectiondate' WHERE status = 1";
  mysqli_query($conn, $update_reading);

  $success = '<span class="text-success"><b>Successfully Upgraded!</b></span>';
}

if (isset($_POST['save_data_1'])) {
  $select_readingdate = $_POST['select_readingdate'];

  $update_reading = "UPDATE tbl_reading_sched SET status = 0";
  mysqli_query($conn, $update_reading);

  $update_reading = "UPDATE tbl_reading_sched SET status = 1 WHERE reading_date = '$select_readingdate'";
  mysqli_query($conn, $update_reading);

  $success = '<span class="text-success"><b>Successfully updated!</b></span>';
}

$todaypayreceived = 0; // Initialize total

$result = mysqli_query($conn, "SELECT M.`id`, M.`reading_date`, M.`transaction_date`, M.`account_no`, M.`account_name`, M.`prev_reading`, M.`pres_reading`, M.`total_reading`, M.`billing_amount`, M.`due_date`, M.`disconnection_date`, M.`completed`
FROM `tbl_members_report` M
LEFT JOIN `tbl_payments` P ON M.`reading_date` = P.`reading_date` AND M.`account_no` = P.`unique_id`
WHERE P.`id` IS NULL
AND M.`reading_date` >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH)");

while ($row = mysqli_fetch_array($result)) {
  $todaypayreceived += floatval($row['billing_amount']);
}
?>

<!DOCTYPE html>
<html>

<head>
  <title>AWS Admin Dashboard</title>

  <!-- Include necessary CSS and JavaScript files -->
  <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
  <link rel="stylesheet" href="plugins/datatables-bs4/css/dataTables.bootstrap4.min.css">
  <link rel="stylesheet" href="plugins/datatables-responsive/css/responsive.bootstrap4.min.css">
  <link rel="stylesheet" href="dist/css/adminlte.min.css">
  <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css">
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <?php include_once('linkStyle.php'); ?>
  <style>
    .currencyinput {
      border: 1px inset #ccc;
    }

    .currencyinput input {
      border: 0;
    }
  </style>
</head>

<body class="hold-transition layout-footer-fixed layout-fixed sidebar-collapse">
  <div id="preloader" style="display:none;"></div>
  <div class="wrapper">
    <section class="content-header bg-primary">
      <div class="container-fluid">
        <div class="display-flex-item">
          <div>
            <center>
              <div class="fontSize-22 font-weight-bolder text-light">
                <p id="totalBill">Today Payment Collections ₱ <?php echo number_format($todaypayreceived, 2); ?></p>
              </div>
            </center>
          </div>
          <div style="line-height: 45px;text-align:center;">
          </div>
        </div>
      </div>
    </section>
    <?php include_once('navbar.php'); ?>
    <div class="content-wrapper">
      <p id="success"></p>
      <section class="content">
        <div class="container-fluid">
          <div class="col-lg-12 col-12">
            <div class="small-box bg-secondry shadow_block" style="height: auto; width: 100%;">
            </div>
          </div>
        </div>
      </section>
      <section class="content">
        <div class="container-fluid">
          <div class="col-lg-12 col-12">
            <div class="small-box bg-secondry shadow_block" style="height: auto; width: 100%;">
              <div class="inner">
                <h4 style="mx-auto">
                  Today <b>Payment Collections</b> &#8369;<?php echo number_format($todaypayreceived, 2); ?>
                </h4>
                <div>
                  <input type="text" id="minDate" placeholder="Start Date (MM/DD/YYYY)" class="datepicker">
                  <input type="text" id="maxDate" placeholder="End Date (MM/DD/YYYY)" class="datepicker">
                  <button id="applyDateFilter">Apply Date Range Filter</button>
                </div>

                <div>
                  <select id="filterMonth">
                    <option value="">Filter by Month</option>
                    <option value="01">January</option>
                    <option value="02">February</option>
                    <option value="03">March</option>
                    <option value="04">April</option>
                    <option value="05">May</option>
                    <option value="06">June</option>
                    <option value="07">July</option>
                    <option value="08">August</option>
                    <option value="09">September</option>
                    <option value="10">October</option>
                    <option value="11">November</option>
                    <option value="12">December</option>
                  </select>
                  <button id="applyMonthFilter">Apply Month Filter</button>
                </div>
                <table id="example1" class="table table-striped table-bordered table-sm" cellspacing="0" width="100%">
                  <thead>
                    <tr>
                      <th>Account #</th>
                      <th>Account Name</th>
                      <th>Reading Date</th>
                      <th>Previous Reading</th>
                      <th>Present Reading</th>
                      <th>Total Reading</th>
                      <th>Total Bill</th>
                      <th>Due Date</th>
                      <th width="20%">Action</th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php
                    $result = mysqli_query($conn, "SELECT M.`id`, M.`reading_date`, M.`transaction_date`, M.`account_no`, M.`account_name`, M.`prev_reading`, M.`pres_reading`, M.`total_reading`, M.`billing_amount`, M.`due_date`, M.`disconnection_date`, M.`completed`
                    FROM `tbl_members_report` M
                    LEFT JOIN `tbl_payments` P ON M.`reading_date` = P.`reading_date` AND M.`account_no` = P.`unique_id`
                    WHERE P.`id` IS NULL
                    AND M.`reading_date` >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH)");
                    $i = 1;
                    while ($row = mysqli_fetch_array($result)) {
                      $id = $row['id'];
                      $account_no = $row['account_no'];
                      $account_name = $row['account_name'];
                      $reading_date = $row['reading_date'];
                      $prev_reading = $row['prev_reading'];
                      $pres_reading = $row['pres_reading'];
                      $total_reading = $row['total_reading'];
                      $billing_amount = $row['billing_amount'];
                      $due_date = $row['due_date'];
                    ?>
                      <tr id="<?php echo $i; ?>">
                        <td><?php echo $account_no; ?></td>
                        <td><?php echo $account_name; ?></td>
                        <td><?php echo $reading_date; ?></td>
                        <td><?php echo $prev_reading; ?></td>
                        <td><?php echo $pres_reading; ?></td>
                        <td><?php echo $total_reading; ?></td>
                        <td><?php echo $billing_amount; ?></td>
                        <td><?php echo $due_date; ?></td>
                        <td>
                          <a href="printreceipt.php?id=<?php echo $id; ?>">Print Receipt</a>
                        </td>
                      </tr>
                    <?php
                      $i++;
                    }
                    ?>
                  </tbody>
                  <tfoot>
  <tr>
    <th colspan="6">Total:</th>
    <th id="totalBillFooter"></th>
    <th></th>
    <th></th>
  </tr>
</tfoot>
                </table>
              </div>
            </div>
          </div>
          <br>
          <?php include_once('footer.php'); ?>
          <aside class="control-sidebar control-sidebar-dark">
          </aside>
        </div>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
        <script src="plugins/jquery/jquery.min.js"></script>
        <script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
        <script src="plugins/datatables/jquery.dataTables.min.js"></script>
        <script src="plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
        <script src="plugins/datatables-responsive/js/dataTables.responsive.min.js"></script>
        <script src="plugins/datatables-responsive/js/responsive.bootstrap4.min.js"></script>
        <script src="dist/js/adminlte.min.js"></script>
        <script src="dist/js/demo.js"></script>
        <script src="https://cdn.datatables.net/buttons/2.3.2/js/dataTables.buttons.min.js"></script>
        <script src="https://cdn.datatables.net/buttons/2.3.2/js/buttons.bootstrap4.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
        <script src="https://cdn.datatables.net/buttons/2.3.2/js/buttons.html5.min.js"></script>
        <script src="https://cdn.datatables.net/buttons/2.3.2/js/buttons.print.min.js"></script>
        <script src="https://cdn.datatables.net/buttons/2.3.2/js/buttons.colVis.min.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
      
        <script type="text/javascript">
         $(document).ready(function() {
    $(".datepicker").datepicker({
        dateFormat: "mm/dd/yy",
        changeMonth: true,
        changeYear: true
    });

    var table = $('#example1').DataTable({
        "paging": true,
        "lengthChange": false,
        "searching": true,
        "ordering": true,
        "info": true,
        "autoWidth": false,
        "responsive": true,
        "stateSave": true,
        "dom": 'Bfrtip',
        "buttons": [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ],
        "order": [[2, 'asc']], // Sort by the reading date column (index 2)
        "columnDefs": [
            {
                "targets": [2],
                "type": "date",
                "render": function(data, type, row) {
                    if (type === 'sort') {
                        return data; // Sorting type
                    }
                    return new Date(data).toLocaleDateString(); // Display format
                }
            }
        ],
        "language": {
            "search": "Date range:",
            "searchPlaceholder": "MM/DD/YYYY - MM/DD/YYYY",
        }
    });

    var totalBill = 0;

    // Function to update the total
    function updateTotal() {
        totalBill = table.column(6).data().reduce(function(a, b) {
            return parseFloat(a) + parseFloat(b);
        }, 0);
        $('#totalBill').text('Today Payment Collections ₱' + totalBill.toFixed(2));
        $('#totalBillFooter').text(totalBill.toFixed(2));
    }

    // Initial total
    updateTotal();

    $('#applyDateFilter').click(function() {
        var minDateStr = $('#minDate').val();
        var maxDateStr = $('#maxDate').val();
        var minDate = $.datepicker.parseDate("mm/dd/yy", minDateStr);
        var maxDate = $.datepicker.parseDate("mm/dd/yy", maxDateStr);

        $.fn.dataTable.ext.search.pop(); // Remove any previous search functions
        $.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
            var readingDate = $.datepicker.parseDate("mm/dd/yy", data[2]);
            return readingDate >= minDate && readingDate <= maxDate;
        });

        table.draw();

        // Update the total when applying the date filter
        updateTotal();
    });

    $('#applyMonthFilter').click(function() {
        var selectedMonth = $('#filterMonth').val();
        if (selectedMonth !== "") {
            $.fn.dataTable.ext.search.pop(); // Remove any previous search functions
            $.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
                var readingDate = $.datepicker.parseDate("mm/dd/yy", data[2]);
                return readingDate.getMonth() + 1 === parseInt(selectedMonth);
            });

            table.draw();

            // Update the total when applying the month filter
            updateTotal();
        }
    });
});

        </script>
      </body>
</html>
