
<?php $__env->startSection('content'); ?>
<style>
  button.dt-button, div.dt-button, a.dt-button, input.dt-button {
    border-radius: 5px;
    color: white;
    background-color: rgb(197, 7, 178);
    box-shadow: rgba(50, 50, 93, 0.25) 0px 50px 100px -20px, rgba(0, 0, 0, 0.3) 0px 30px 60px -30px, rgba(10, 37, 64, 0.35) 0px -2px 6px 0px inset;
}

button.dt-button:hover:not(.disabled), div.dt-button:hover:not(.disabled), a.dt-button:hover:not(.disabled), input.dt-button:hover:not(.disabled) {
    border: 1px solid #666;
    background-color: rgb(29, 29, 29);
}


</style>
      <!-- partial -->
      <div class="main-panel">
        <div class="content-wrapper">
          <div class="page-header">
            <h3 class="page-title">
              Dashboard
            </h3>
          </div>
          <div class="row grid-margin">
            <div class="col-12">
              <div class="card card-statistics">
                <div class="card-body">
                  <div class="d-flex flex-column flex-md-row align-items-center justify-content-between">
                    <div class="statistics-item">
                        <p>
                            <i class="icon-sm fa fa-user mr-2"></i>
                            Total Quantity
                        </p>
                        <h4><?php echo e(number_format($purchaseTotalSums->overall_total_quantity, 2)); ?></h4>
                    </div>
                   
                    <div class="statistics-item">
                        <p>
                            <i class="icon-sm fas fa-hourglass-half mr-2"></i>
                            Total Cost
                        </p>
                        <h4><?php echo e(number_format($purchaseTotalSums->overall_total_cost, 2)); ?></h4>
                    </div>
                    <div class="statistics-item">
                      <p>
                          <i class="icon-sm fas fa-hourglass-half mr-2"></i>
                          Total Paid
                      </p>
                      <h4><?php echo e(number_format($purchaseTotalSums->overall_total_paid, 2)); ?></h4>
                  </div>
                    <div class="statistics-item">
                        <p>
                            <i class="icon-sm fas fa-hourglass-half mr-2"></i>
                            Balance
                        </p>
                        <h4><?php echo e(number_format($purchaseTotalSums->overall_total_cost - $purchaseTotalSums->overall_total_paid, 2)); ?></h4>
                        
                        <?php if(($purchaseTotalSums->overall_total_cost - $purchaseTotalSums->overall_total_paid) > 0): ?>
                            <label class="badge badge-outline-danger badge-pill">Outstanding Amount</label>
                        <?php else: ?>
                            <label class="badge badge-outline-success badge-pill">Balance Amount</label>
                        <?php endif; ?>
                    </div>
                   
                    
                      
                  </div>
                </div>
              </div>
            </div>
          </div>
         
          <div class="content-wrapper">
            
            <div class="card">
              <div class="card-body">
                <h4 class="card-title">Data table</h4>
                <div class="row">
                  <div class="col-12">
                    <div class="table-responsive" style="overflow-x: auto; -webkit-overflow-x: auto;">
                        <table id="example" class="table table-striped table-hover table-product  nowrap" style="width: 100%; ">
                        <thead>
                          <tr>
                              <th>Id #</th>
                              <th>Purchase Id</th>
                              <th>Date</th>
                              <th>Supplier</th>
                              <th>total Quantity</th>
                              <th>total Cost</th>
                              <th>total Paid</th>
                              <th>Status</th>
                              <th>view</th>
                          </tr>
                        </thead>
                        <tbody>
                         
                      
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col-12">
              <div class="card">
                <div class="card-body">
                  <div class="d-md-flex justify-content-between align-items-center">
                    <div class="d-flex align-items-center mb-3 mb-md-0">
                      <button class="btn btn-social-icon btn-facebook btn-rounded">
                        <i class="fab fa-facebook-f"></i>
                      </button>
                      <div class="ml-4">
                        <h5 class="mb-0">Facebook</h5>
                        <p class="mb-0">813 friends</p>
                      </div>
                    </div>
                    <div class="d-flex align-items-center mb-3 mb-md-0">
                      <button class="btn btn-social-icon btn-twitter btn-rounded">
                        <i class="fab fa-twitter"></i>
                      </button>
                      <div class="ml-4">
                        <h5 class="mb-0">Twitter</h5>
                        <p class="mb-0">9000 followers</p>
                      </div>
                    </div>
                    <div class="d-flex align-items-center mb-3 mb-md-0">
                      <button class="btn btn-social-icon btn-google btn-rounded">
                        <i class="fab fa-google-plus-g"></i>
                      </button>
                      <div class="ml-4">
                        <h5 class="mb-0">Google plus</h5>
                        <p class="mb-0">780 friends</p>
                      </div>
                    </div>
                    <div class="d-flex align-items-center">
                      <button class="btn btn-social-icon btn-linkedin btn-rounded">
                        <i class="fab fa-linkedin-in"></i>
                      </button>
                      <div class="ml-4">
                        <h5 class="mb-0">Linkedin</h5>
                        <p class="mb-0">1090 connections</p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

      
        <!-- content-wrapper ends -->
        <!-- partial:../../partials/_footer.html -->
        <footer class="footer">
          <div class="d-sm-flex justify-content-center justify-content-sm-between">
            <span class="text-muted text-center text-sm-left d-block d-sm-inline-block">Copyright © 2025  <a href="https://www.urbanui.com/" target="_blank">Urbanui</a>. All rights reserved.</span>
            <span class="float-none float-sm-right d-block mt-1 mt-sm-0 text-center">Hand-crafted & made with <i class="far fa-heart text-danger"></i></span>
          </div>
        </footer>
        <!-- partial -->
      </div>
   

        <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="mb-3">
										<label class="form-label">Payment Type <span class="text-danger">*</span></label>
										<select class="select form-control select-payment PaymentMethods" id="PaymentMethods">
											<option value="credit">Credit Card</option>
											<option value="cash" selected>Cash</option>
											<option value="cheque">Cheque</option>
											<option value="deposit">Deposit</option>
											<option value="points">Points</option>
										</select>
									</div>
                   <div class="mb-3">
										<label class="form-label">Date :<span class="text-danger">*</span></label>
										<div class="input-icon-start position-relative">
											
                      		
											<input type="date" class="form-control date" value="0" id="date">
										</div>
									</div>
                  <div class="mb-3">
										<label class="form-label">Received Amount :<span class="text-danger">*</span></label>
										<div class="input-icon-start position-relative">
											
                      		
											<input type="text" class="form-control ReceivedAmount" value="0" id="ReceivedAmount">
										</div>
									</div>
                <div class="mb-3">
                  <label class="form-label">Outstanding Amount :</label>
									
											<span class="input-icon-addon text-gray-9">
												<i class="ti ti-currency-dollar"></i>
											</span>
											<input type="text" class="form-control outstandingAmount" id="outstandingAmount" value="0.00">
                      <input type="text" class="form-control outstandingAmount1" value="0" id="outstandingAmount1" style="display: none">
									</div>
              
									<div class="mb-3">
										<label class="form-label">Payment Note</label>
										<textarea class="form-control PaymentNote" rows="3" placeholder="Type your message"></textarea>
									</div>
							
									<div class="mb-3">
										<label class="form-label">Sale Note</label>
										<textarea class="form-control SaleNote" rows="3" placeholder="Type your message"></textarea>
									</div>
							
									<div class="mb-3">
										<label class="form-label">Staff Note</label>
										<textarea class="form-control StaffNote" rows="3" placeholder="Type your message"></textarea>
									</div>
								

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" id="paymentSubmit">Save changes</button>
      </div>
    </div>
  </div>
</div>
     
      <script>
$( document ).ready(function() {
  var branch_id = <?php echo e(Session::get('branch_id')); ?> 

  

  // alert("hi")
  $('#example').DataTable({
            dom: "<'row'<'col-sm-12 col-md-4'l><'col-sm-12 col-md-4'B><'col-sm-12 col-md-4'f>>" +
                "<'row'<'col-sm-12'tr>>" +
                "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
            buttons: [
                'copy', 'csv', 'excel', 'pdf', 'print'
            ],
            processing: true,
            info: true,
            responsive: true,
            lengthMenu: [
                [10, 25, 50, 100, 200, -1],
                [10, 25, 50, 100, 200, "All"]
            ],
            order: [[0, 'desc']],
            ajax: "<?php echo e(route('list_purchase')); ?>",
            columns: [
                {
                    data: 'id',
                    name: 'id'
                },
                {
                    data: 'purchases_id',
                    name: 'purchases_id'
                },
                {
                    data: 'date',
                    name: 'date'
                },
                {
                    data: 'name',
                    name: 'name'
                },
                {
                    data: 'total_quantity',
                    name: 'total_quantity'
                },
                {
                    data: 'total_cost',
                    name: 'total_cost',
                    render: function(data, type, row) {
                    return parseFloat(data).toLocaleString('en-US', {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2
                    });
                }

                },
                {
                    data: 'total_paid',
                    name: 'total_paid',
                    render: function(data, type, row) {
                    return parseFloat(data).toLocaleString('en-US', {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2
                    });
                }

                },
                 
                {
                    data: 'status',
                    name: 'status'
                },
                   {
                    data: 'id',
                    name: 'view',
                    render: function(data, type, row, meta) {
                      return `
                        <div class="dropdown" style="display: inline-block;">
                        <button 
                          class="btn btn-sm btn-secondary dropdown-toggle" 
                          type="button" 
                          data-bs-toggle="dropdown" 
                          aria-expanded="false"
                          style="background-color: #6c757d; border-color: #6c757d; padding: 5px 10px; font-size: 14px; border-radius: 4px;"
                        >
                        Action
                        </button>
                        <ul class="dropdown-menu shadow-sm" style="min-width: 120px;">
                          <li><a class="dropdown-item text-primary add-payment" id="addpayment" data-toggle="modal" data-id ="${data}" data-outstanding_amount="${row.outstanding_amount}" data-target="#exampleModal">Add Payment</a></li>
                          <li><a class="dropdown-item text-danger view"  data-id="${data}">View</a></li>
                        </ul>
                      </div>
                      `;
                  }
                },
               
              
                // {
                //     data: 'id',
                //     name: 'view',
                //     render: function(data, type, row, meta) {
                //       if(row.delete_permission == 0){
                //         return `<button type="button" class="btn  btn-warning request" data-toggle="modal" data-target="#exampleModal-2"  data-id="${data}" style="height:32px; margin:0px;">Request Delete</button>`;
                //       }if(row.delete_permission == 2){
                //         return `<button type="button" class="btn  btn-danger delete"  data-id="${data}" style="height:32px; margin:0px;">Delete</button>`;
                //       }else{
                //         return `<button type="button" class="btn btn-danger " data-id="${data}" style="height:32px; margin:0px;" disabled>Requested</button>`;

                //       }
                        
                //     }
                // },
            ],


           
            createdRow: function(row, data, dataIndex) {
            // Example condition to change font color
            // Adjust condition as needed
                $(row).css('font-size', '15px');
           
        }
        });

        $(document).on('click', '.delete', function() {
        var id = $(this).data('id');
        alert(id)

            const swalWithBootstrapButtons = Swal.mixin({
                customClass: {
                    confirmButton: 'btn btn-success',
                    cancelButton: 'btn btn-danger'
                },
                buttonsStyling: false
            })

            swalWithBootstrapButtons.fire({
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, Do it!',
                cancelButtonText: 'No, cancel!',
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: "/delete-expenses",
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        type: "POST",
                        data: JSON.stringify({
                            'id': id
                        }),
                        contentType: "application/json",
                        success: function(response) {
                            window.location.reload();
                        },
                    });
                    swalWithBootstrapButtons.fire(
                        'Payment Deleted!',
                        'Your Payment has been Deleted.',
                        'success'
                    )
                } else if (
                    /* Read more about handling dismissals below */
                    result.dismiss === Swal.DismissReason.cancel
                ) {
                    swalWithBootstrapButtons.fire(
                        'Cancelled',
                        'Your imaginary file is safe  😇 ',
                        'error'
                    )
                }
            })

        });

        var ExpensesId;
        $(document).on('click', '.request', function() {
          ExpensesId = $(this).data('id');
         
        });
        $(document).on('click', '.RequestDelete', function() {
        var id = ExpensesId;
        var DeleteReason = $('#DeleteReason').val();

            const swalWithBootstrapButtons = Swal.mixin({
                customClass: {
                    confirmButton: 'btn btn-success',
                    cancelButton: 'btn btn-danger'
                },
                buttonsStyling: false
            })

            swalWithBootstrapButtons.fire({
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, Do it!',
                cancelButtonText: 'No, cancel!',
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: "/Request-delete-expenses",
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        type: "POST",
                        data: JSON.stringify({
                            'id': id,
                            'DeleteReason':DeleteReason
                        }),
                        contentType: "application/json",
                        success: function(response) {
                            window.location.reload();
                        },
                    });
                    swalWithBootstrapButtons.fire(
                        'Payment Deleted!',
                        'Your Payment has been Deleted.',
                        'success'
                    )
                } else if (
                    /* Read more about handling dismissals below */
                    result.dismiss === Swal.DismissReason.cancel
                ) {
                    swalWithBootstrapButtons.fire(
                        'Cancelled',
                        'Your imaginary file is safe  😇 ',
                        'error'
                    )
                }
            })

        });


        

        $(document).on('click', '.view', function() {
            var id = $(this).data('id');
            

            var url = '/purchase_data?id=' + id;
            window.location.href = url;
        });





var Purchaseid = '';
var outstanding_amount;

$(document).on("click", "#addpayment", function () {
  Purchaseid = $(this).data('id');
  outstanding_amount = parseFloat($(this).data('outstanding_amount')) ;
  
  $('.outstandingAmount').val(outstanding_amount.toFixed(2));
  $('.outstandingAmount1').val(outstanding_amount.toFixed(2));
});

$(document).on("input", "#ReceivedAmount", function () {
  var Received_amount = parseFloat($(this).val()) || 0;
  var new_outstanding = outstanding_amount - Received_amount;
  $('.outstandingAmount').val(new_outstanding.toFixed(2));
});

         $(document).on("click", "#paymentSubmit", function (e) {
        e.preventDefault();
        var receivedAmount = parseFloat($('.ReceivedAmount').val()) || 0;
        var outstandingAmount = parseFloat($('.outstandingAmount').val()) || 0;
        var StaffNote = $(".StaffNote").val();
	      var SaleNote = $(".SaleNote").val();
	      var PaymentNote = $(".PaymentNote").val();
        var PaymentMethods = $('.PaymentMethods').val();
        var date =$('.date').val();
       

        var isValid = true;
            var errorMessage = '';

            // Perform individual validation checks for each input field
        if (!date || date.length === 0) {
            errorMessage += 'Date is required.<br>';
            isValid = false;
        }
        if (!receivedAmount || receivedAmount.length === 0) {
            errorMessage += 'Received Amount is required.<br>';
            isValid = false;
        }

        if (!isValid) {
                Swal.fire({
                    icon: 'error',
                    title: 'Validation Error',
                    html: errorMessage,
                    showCloseButton: true,
                    showCancelButton: false,
                    focusConfirm: false,
                    confirmButtonText: 'OK',
                });
                return;
      }else{
        var form_data = new FormData();
            form_data.append('_token', '<?php echo e(csrf_token()); ?>');
            form_data.append('id', Purchaseid);
             form_data.append('receivedAmount', receivedAmount);
            form_data.append('outstandingAmount', outstandingAmount);
            form_data.append('date', date);
            form_data.append('StaffNote', StaffNote);
            form_data.append('SaleNote', SaleNote);
            form_data.append('PaymentNote', PaymentNote);
            form_data.append('PaymentMethods', PaymentMethods);


            $.ajax({
                url: '/store-purchase-payment', // Replace with your backend URL
                type: 'POST',
                data: form_data,
                contentType: false,
                processData: false,
                success: function (response) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: 'Your data has been submitted successfully!',
                        confirmButtonText: 'OK',
                    }).then((result) => {
                      if (result.isConfirmed) {
                         window.location.reload();
                      }
                    });
                },
                error: function (response) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'There was an error submitting your data.',
                        confirmButtonText: 'OK',
                    });
                }
            });
      }
              
    });
});
      
      </script>
<?php $__env->stopSection(); ?>
      <!-- main-panel ends -->
    
<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH C:\Users\USER\Desktop\pos\susmart\resources\views/Section/Purchase/purchaseList.blade.php ENDPATH**/ ?>