<?php include( 'inc/template.php' );?>
<div class="container-fluid flex-grow-1 container-p-y">
	<nav aria-label="breadcrumb">
	<ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="index.php">Home</a></li>
	<li class="breadcrumb-item"><a href="booking_add.php">Package Booking Add</a></li>
    <li class="breadcrumb-item">Package Booking List</li>
    </ol>
</nav>
<!-- Modal for Status Change -->


<div class="card">
<div class="card-datatable table-responsive pt-0">
<table class="datatables-ajax table table-bordered table-responsive">
    <thead>
        <tr>
            <th style="display: none"></th>
            <th>Invoice Date</th>
            <th>Invoice No.</th>
            <th>Name</th>
            <th>Mobile</th>
            <th>Package Name</th>
            <th>Total Amount</th>
            <th>Due Amount</th>
            <th>Payment Status</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <?php
        $nox = 0;
        $ure = mysqli_query($conn, "SELECT * FROM package_bookings ORDER BY ABS(id) DESC");
        while ($urow = mysqli_fetch_array($ure)) {
            $id = $urow[0];
            $no = 1 + $nox++;
            $uupQry = "UPDATE package_bookings SET orderlist='$no' WHERE id='$id'";
            mysqli_query($conn, $uupQry);
        }
        $totalAmount = 0;
$totalDue = 0;

        $sql = "SELECT pb.*, c.name AS customer_name, c.phone AS customer_phone, pp.type AS last_payment_type, pp.amount AS last_payment_amount, pp.payment_date AS last_payment_date, COALESCE(debit.total_debit, 0) AS total_debit, COALESCE(credit.total_credit, 0) AS total_credit, COALESCE(debit.total_debit, 0) - COALESCE(credit.total_credit, 0) AS due_amount FROM package_bookings pb JOIN customers c ON pb.customer_id = c.id LEFT JOIN ( SELECT p1.* FROM package_payments p1 INNER JOIN ( SELECT booking_id, MAX(id) AS max_id FROM package_payments GROUP BY booking_id ) p2 ON p1.booking_id = p2.booking_id AND p1.id = p2.max_id ) pp ON pb.id = pp.booking_id LEFT JOIN ( SELECT booking_id, SUM(amount) AS total_debit FROM package_payments WHERE type = 'debit' GROUP BY booking_id ) debit ON pb.id = debit.booking_id LEFT JOIN ( SELECT booking_id, SUM(amount) AS total_credit FROM package_payments WHERE type = 'credit' GROUP BY booking_id ) credit ON pb.id = credit.booking_id WHERE pb.gst_included = 'no' AND pb.financial_year = '$financial_year' ORDER BY pb.id DESC";

        $result = mysqli_query($conn, $sql);
        while ($row = mysqli_fetch_array($result)) {
            
            $btnClass = ($row['due_amount'] == 0) ? 'btn-success' : 'btn-danger changeStatusBtn';
            $statusLabel = ($row['due_amount'] == 0) ? 'Paid' : 'Pending';
             $totalAmount += $row['grand_total']; // Sum of total amount
    $totalDue += $row['due_amount']; // Sum of due amount
        ?>
        <tr class="showtr">
            <td style="display: none"><?php echo $row['orderlist']; ?></td>
            <td><?php echo htmlspecialchars(date('d-m-Y', strtotime($row['booking_date']))); ?></td>
            <td><?php echo htmlspecialchars($row['booking_no']); ?></td>
            <td><a href="booking_details.php?packagebookingid=<?php echo $row['id']; ?>" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="View Details"><?php echo htmlspecialchars(ucwords($row['customer_name'])); ?></a></td>
            <td><?php echo htmlspecialchars($row['customer_phone']); ?></td>
            <td><?php echo htmlspecialchars(ucwords($row['package_name'])); ?></td>
            <td><?php echo htmlspecialchars($row['grand_total']); ?></td>
            <td><?php echo htmlspecialchars($row['due_amount']); ?></td>
            <td>
                <button class="btn btn-sm <?php echo $btnClass; ?>"
                        data-id="<?php echo $row['id']; ?>"
                        data-customer_id="<?php echo $row['customer_id']; ?>"
                        data-total_amount="<?php echo $row['due_amount']; ?>"
                        data-gst_included="<?php echo $row['gst_included']; ?>"
                        data-current-status="<?php echo htmlspecialchars(strtolower($row['status'])); ?>">
                    <?php echo htmlspecialchars(ucwords(strtolower($statusLabel))); ?>
                </button><br>
                <small class="text-muted">
                    <?php
                    if (!empty($row['last_payment_date'])) {
                        echo "Last: " . date('d-m-Y', strtotime($row['last_payment_date'])) . "<br>";
                        echo ucwords($row['last_payment_type']) . ": ₹" . number_format($row['last_payment_amount'], 2);
                    }
                    ?>
                </small>
            </td>
            <td>
                <button type="button" class="btn btn-xs btn-info download" data-id="<?= $row['id']; ?>"><i class="far fa-file-pdf"></i></button>
                <button type="button" id="<?php echo $row['id']; ?>" class="btn btn-xs btn-danger delete"><i class="far fa-trash-alt"></i></button>
            </td>
        </tr>
        <?php } ?>
    </tbody>
    <tfoot>
        <tr>
            <th colspan="5" style="text-align:right">Total:</th>
            <th><?php echo '₹' . number_format($totalAmount, 2); ?></th>
            <th><?php echo '₹' . number_format($totalDue, 2); ?></th>
            <th colspan="3"></th>
        </tr>
    </tfoot>
</table>


<!-- Modal HTML -->
<div class="modal fade" id="statusChangeModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <form id="paymentForm">
        <div class="modal-header">
          <h5 class="modal-title">Payment Mode</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <div class="row">
            <div class="col mb-3">
              <label class="form-label">Payment Mode</label>
              <select name="payment_mode" id="payment_mode" class="form-select" required>
                <option value="cash">Cash</option>
                <option value="upi">UPI</option>
                <option value="cheque">Cheque</option>
              </select>
            </div>
          </div>

          <div class="row">
            <div class="col-6 mb-3">
              <label class="form-label">Total</label>
              <input type="number" id="totalAmount" name="total" class="form-control" readonly />
            </div>
            <div class="col-6 mb-3">
              <label class="form-label">Received</label>
              <input type="number" name="received" class="form-control" required />
            </div>
          </div>

          <div class="row" id="upi_details_group" style="display: none;">
            <div class="col mb-3">
              <label class="form-label">UPI Details</label>
              <textarea name="upi_details" class="form-control"></textarea>
            </div>
          </div>

          <div class="row" id="bank_cheque_group" style="display: none;">
            <div class="col-6 mb-3">
              <label class="form-label">Cheque No. / Ref No.</label>
              <input type="text" name="cheque_no" class="form-control">
            </div>
            <div class="col-6 mb-3">
              <label class="form-label">Bank Name</label>
              <input type="text" name="bank_name" class="form-control">
            </div>
          </div>

          <div class="row">
            <div class="col mb-3">
              <label class="form-label">Remarks</label>
              <textarea name="remarks" class="form-control"></textarea>
            </div>
          </div>
		 <input type="hidden" name="useridnew" id="useridnew" value="<?php echo $adminId; ?>" />
          <input type="hidden" name="id" id="bookingId" />
          <input type="hidden" name="customer_id" id="customerId" />
          <input type="hidden" name="gst_included" id="gstIncluded" />
        </div>
        <div class="modal-footer">
          <input type="hidden" name="action" value="save">
          <button type="submit" class="btn btn-primary">Save</button>
          <button type="submit" class="btn btn-primary" id="download-pdf">Save & PDF</button>
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        </div>
      </form>
    </div>
  </div>
</div>




</div>
</div>
</div>
<!-- Include jQuery -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
<script>
let isPdf = false;
$(document).ready(function () {
  $('#payment_mode').on('change', function() {
    let mode = $(this).val();

    // Hide all groups first
    $('#upi_details_group, #bank_cheque_group').hide();

    // Remove required attributes from all optional inputs
    $('#upi_details').prop('required', false);
    $('#cheque_no').prop('required', false);
    $('#bank_name').prop('required', false);

    if (mode === 'upi') {
      $('#upi_details_group').show();
      $('#upi_details').prop('required', true);
    } else if (mode === 'cheque') {
      $('#bank_cheque_group').show();
      $('#cheque_no').prop('required', true);
      $('#bank_name').prop('required', true);
    }
  });

  $(document).on('click', '.changeStatusBtn', function() {
    var bookingId = $(this).data('id');
    var customerId = $(this).data('customer_id');
    var totalAmount = $(this).data('total_amount');
    var gstIncluded = $(this).data('gst_included');
    var currentStatus = $(this).data('current-status');

    // Populate modal fields
    $('#bookingId').val(bookingId);
    $('#customerId').val(customerId);
    $('#totalAmount').val(totalAmount);
    $('#gstIncluded').val(gstIncluded);
    $('#payment_mode').val(currentStatus);
    
    $('#statusChangeModal').modal('show');
  });
	$('#save-only').on('click', function () {
    isPdf = false;
  });

  $('#download-pdf').on('click', function () {
    isPdf = true;
  });

  // Handle payment form submission (Save or Save & PDF)
$("#paymentForm").on("submit", function (e) {
    e.preventDefault();
	$('#statusChangeModal').modal('hide');
    $.ajax({
      url: "controller/PaymentController.php",
      type: "POST",
      data: $(this).serialize(),
      dataType: 'json',
      success: function (response) {
        if (response.status === "success") {
          Swal.fire({
            icon: "success",
            title: "Payment Added!",
            text: response.message,
            showConfirmButton: true,
            confirmButtonText: 'OK'
          }).then(function () {
            if (isPdf) {
              window.open('controller/DownlaodPaymentController.php?payment_id=' + response.payment_id, '_blank');

            }

            
            $("#paymentForm")[0].reset();

            // Optional delay
            setTimeout(function () {
              location.reload(); // or refresh a specific section
            }, 1500);
          });
        } else {
          Swal.fire("Error", response.message, "error");
        }
      },
      error: function () {
        Swal.fire("Error", "Could not reach the server.", "error");
      }
    });
  });

});

</script>

<script>

$(document).ready(function () {
    
    // Handle delete action
    $(document).on('click', '.delete', function () {
    var id = $(this).attr("id");
    var row = $(this).closest('tr');
    if (confirm('Are you sure you want to delete this record?')) {
        $.ajax({
            url: 'controller/BookingController.php',
            method: 'POST',
            data: { id: id, action: 'Delete' },
            dataType: 'json', // Expect JSON response
            success: function (response) {
                console.log('Server Response:', response); // Log the response
                if (response.status === 'Delete') {
                    toastr.success(response.message);
                    row.css('background-color', '#63ba8f').fadeOut(800, function() {
                        $(this).remove();
                    });
                } else {
                    toastr.error(response.message);
                }
            },
            error: function () {
                toastr.error('Error while deleting record.');
            }
        });
    }
});

// Download PDF
    $('.download').on('click', function() {
        const id = $(this).data('id');
        window.open('controller/DownloadPDFBookingController.php?id=' + id, '_blank');
    });


});

</script>
<?php include('inc/footer.php');?>