<?php include('inc/template.php');?>
<div class="container-fluid flex-grow-1 container-p-y">
	<?php include('booking_header.php');?>
        <div class="row mb-4">
                <!--  Modal -->
        <div class="modal fade" id="basicModal" tabindex="-1" aria-labelledby="basicModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <form id="paymentForm">
        <div class="modal-header">
          <h5 class="modal-title">Payment</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" value="<?= htmlspecialchars($due_amount); ?>" 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" value="<?= htmlspecialchars($row['id']); ?>" />
          <input type="hidden" name="customer_id" id="customerId" value="<?= htmlspecialchars($row['customer_id']); ?>" />
          <input type="hidden" name="gst_included" id="gstIncluded" value="<?= htmlspecialchars($row['gst_included']); ?>" />
        </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>

        <!-- Users Table -->
        <div class="col-xl-12 col-lg-6 col-md-6">
            <div class="card">
				
                <div class="card-datatable table-responsive pt-0"><button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#basicModal">
        <span class="ti-xs ti ti-plus me-1"></span> Add New Payment
    </button>
                    <table class="datatables-ajax table table-bordered table-responsive">
    <thead>
        <tr>
            <th style="display: none"></th>
            <th>Receipt No</th>
            <th>Date</th>
            <th>Payment Mode</th>
            <th>Remarks</th>
            <th class="text-success">Credit (₹)</th>
            <th class="text-danger">Debit (₹)</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <?php
        $nox = 0;
        $ure = mysqli_query($conn, "SELECT * FROM package_payments ORDER BY ABS(id) DESC");
        while ($urow = mysqli_fetch_array($ure)) {
            $id = $urow[0];
            $no = 1 + $nox++;
            $uupQry = "UPDATE package_payments SET orderlist='$no' WHERE id='$id'";
            mysqli_query($conn, $uupQry);
        }
        $total_credit = 0;
        $total_debit = 0;

        $query = "SELECT pp.*, c.name AS customer_name, c.phone AS customer_phone, b.package_name 
                  FROM package_payments pp 
                  LEFT JOIN customers c ON pp.customer_id = c.id 
                  LEFT JOIN package_bookings b ON pp.booking_id = b.id 
                  WHERE booking_id = '$packagebooking_id'
                  ORDER BY pp.payment_date DESC, pp.id DESC";

        $result = mysqli_query($conn, $query);
        while ($row = mysqli_fetch_assoc($result)) {
            $credit = $row['type'] === 'credit' ? $row['amount'] : '';
            $debit = $row['type'] === 'debit' ? $row['amount'] : '';

            if ($credit) $total_credit += $row['amount'];
            if ($debit) $total_debit += $row['amount'];

            // Check if it is a debit or credit entry
            if ($debit) {
                // Debit entry (no actions, payment mode blank)
        ?>
        <tr>
            <td style="display: none"><?=  $row['orderlist']; ?></td>
            <td><?= htmlspecialchars($row['receipt_no']); ?></td>
            <td><?= htmlspecialchars($row['payment_date']); ?></td>
            <td></td> <!-- Blank payment mode for debit -->
            <td><?= nl2br(htmlspecialchars($row['remarks'])); ?></td>
            <td class="text-success text-end"><?= $credit ? number_format($credit, 2) : ''; ?></td>
            <td class="text-danger text-end"><?= $debit ? number_format($debit, 2) : ''; ?></td>
            <td></td> <!-- No action buttons for debit -->
        </tr>
        <?php 
            } else {
                // Credit entry (show action buttons)
        ?>
        <tr>
            <td style="display: none"><?=  $row['orderlist']; ?></td>
            <td><?= htmlspecialchars($row['receipt_no']); ?></td>
            <td><?= htmlspecialchars($row['payment_date']); ?></td>
            <td>
                <button type="button" data-bs-toggle="modal" data-bs-target="#paymentModeModal"
                        class="btn btn-sm <?= in_array(strtolower($row['payment_mode']), ['cheque', 'upi']) ? 'btn-primary' : 'btn-secondary'; ?> payment-mode-btn" 
                        data-id="<?= $row['id']; ?>" 
                        data-mode="<?= $row['payment_mode']; ?>">
                    <?= ucfirst($row['payment_mode']); ?>
                </button>
            </td>
            <td><?= nl2br(htmlspecialchars($row['remarks'])); ?></td>
            <td class="text-success text-end"><?= $credit ? number_format($credit, 2) : ''; ?></td>
            <td class="text-danger text-end"><?= $debit ? number_format($debit, 2) : ''; ?></td>
            <td>
                <button type="button" class="btn btn-xs btn-success download" data-id="<?= $row['id']; ?>"><i class="far fa-file-pdf"></i></button>
                <button type="button" class="btn btn-xs btn-primary update" data-id="<?= $row['id']; ?>"><i class="far fa-edit"></i></button>
                <button type="button" class="btn btn-xs btn-danger delete" data-id="<?= $row['id']; ?>"><i class="far fa-trash-alt"></i></button>
            </td>
        </tr>
        <?php 
            } // End if-else for debit vs credit
        } // End while loop
        ?>
    </tbody>
    <tfoot>
        <tr>
            <th colspan="4" class="text-end">Total</th>
            <th class="text-success text-end"><?= number_format($total_credit, 2); ?></th>
            <th class="text-danger text-end"><?= number_format($total_debit, 2); ?></th>
        </tr>
        <tr>
            <th colspan="4" class="text-end">Balance (Credit - Debit)</th>
            <th colspan="2" class="text-center fw-bold">
                ₹<?= number_format($total_credit - $total_debit, 2); ?>
            </th>
        </tr>
    </tfoot>
</table>


<div class="modal fade" id="paymentModeModal" tabindex="-1" aria-labelledby="paymentModeModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="paymentModeModalLabel">Payment Mode Details</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body" id="paymentModeContent">
        Loading...
      </div>
    </div>
  </div>
</div>


                </div>
            </div>
        </div>
    </div>
</div>
<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>
$(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);
    }
  })
    // Show modal for Create
    $('#modal_button').click(function () {
    $('#paymentForm')[0].reset();
    $('#action').val('Create');
    $('#id').val('');
    $('.modal-title').text("Create New Payment");
    $('#basicModal').modal('show');
});


  
$(document).on('click', '.update', function () {
    const id = $(this).data("id"); // Use data-id attribute

    $.ajax({
        url: "controller/PaymentController.php",
        method: "POST",
        data: { id: id, action: 'Select' },
        dataType: "json",
        success: function (data) {
			console.log("Received data:", data); // Debug print
            if (data) {
                // Populate the form fields
                $('#payment_mode').val(data.payment_mode).trigger('change');
                $('#totalAmount').val(data.total);
                $('input[name="received"]').val(data.amount);
                $('textarea[name="upi_details"]').val(data.upi_details);
                $('input[name="cheque_no"]').val(data.cheque_no);
                $('input[name="bank_name"]').val(data.bank_name);
                $('textarea[name="remarks"]').val(data.remarks);
                $('#bookingId').val(data.booking_id);
                $('#customerId').val(data.customer_id);
                $('#gstIncluded').val(data.gst_included);
				$('#totalAmount').val(data.pending_amount);
                $('#id').val(id);
                $('#action').val('Update');

                $('.modal-title').text("Update Payment");
                $('#basicModal').modal('show');
            } else {
                Swal.fire('Not Found', 'No data found for this payment ID.', 'warning');
            }
        },
        error: function (xhr, status, error) {
            console.error(xhr.responseText); // Helpful for debugging
            Swal.fire('Error', 'Could not fetch payment details.', 'error');
        }
    });
});



// Delete action
$(document).on('click', '.delete', function () {
    const id = $(this).data("id"); // Use data-id instead of id
    const row = $(this).closest('tr');

    if (confirm('Are you sure you want to delete this payment record?')) { // Update text to reflect correct action
        $.ajax({
            url: 'controller/PaymentController.php',
            method: 'POST',
            data: { id: id, action: 'Delete' },
            dataType: "json",
            success: function (response) {
                if (response.status === 'success') {
                    toastr.success(response.message);
                    row.css('background-color', '#f8d7da').fadeOut(800, function () {
                        $(this).remove();
                    });
                } else {
                    toastr.error(response.message);
                }
            },
            error: function () {
                toastr.error('Error deleting payment record.');
            }
        });
    }
});

let generatePDF = false;

$('#download-pdf').on('click', function (e) {
    e.preventDefault();
    generatePDF = true;
    $('#paymentForm').submit(); // trigger form submission
});

    // Submit form for Create or Update
    $('#paymentForm').on('submit', function (e) {
    e.preventDefault();
 $('#basicModal').modal('hide');
		    $('#paymentForm').append('<input type="hidden" name="action" value="Create">');

    Swal.fire({
        title: 'Are you sure?',
        text: "You are about to save this payment.",
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Save it!',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: "controller/PaymentController.php",
                method: "POST",
                data: $('#paymentForm').serialize(),
                dataType: "json",
                success: function (response) {
                    if (response.status === 'success') {
						if (generatePDF) {
                            // open PDF in new tab
							 window.open('controller/DownlaodPaymentController.php?payment_id=' + response.payment_id, '_blank');
                            
                        }

                        Swal.fire('Saved!', response.message, 'success');
                       
                        setTimeout(() => location.reload(), 1500);
                    } else {
                        Swal.fire('Error', response.message, 'error');
                    }
                },
                error: function () {
                    Swal.fire('Error', 'Something went wrong while saving.', 'error');
                }
            });
        }
    });
});



	// View Payment Mode Details
    
    $('.payment-mode-btn').on('click', function () {
    const id = $(this).data('id');
    const mode = $(this).data('mode').toLowerCase();

    if (mode === 'cheque' || mode === 'upi') {
        $('#paymentModeContent').html('Loading...');
        $.ajax({
            url: 'payment_mode_details.php',
            method: 'POST',
            data: { id: id },
            success: function (response) {
                $('#paymentModeContent').html(response);
                // ✅ DO NOT create a new modal each time
                $('#paymentModeModal').modal('show'); // Use jQuery bootstrap shortcut
            }
        });
    }
});



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


});
</script>


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