@extends('layout')
@section('content')
<style>
    .invoice-table {
        width: 100%;
        border-collapse: collapse;
    }
    .invoice-table th, .invoice-table td {
        border: 1px solid #ddd;
        padding: 8px;
        text-align: left;
    }
    .invoice-table th {
        background-color: #f2f2f2;
    }
    .form-control {
        width: 100%;
        padding: 8px;
        border: 1px solid #ddd;
        border-radius: 4px;
    }
    .checkbox-label {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
    }
    .summary-box {
        border: 1px solid #ddd;
        padding: 15px;
        margin-top: 20px;
        background-color: #f9f9f9;
    }
    .char-count {
        font-size: 12px;
        color: #6c757d;
    }
    .btn {
        padding: 8px 16px;
        margin-right: 10px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }
    .btn-primary {
        background-color: #007bff;
        color: white;
    }
    .btn-secondary {
        background-color: #6c757d;
        color: white;
    }
    .btn-danger {
        background-color: #dc3545;
        color: white;
    }
    .btn-success {
        background-color: #28a745;
        color: white;
    }
    .action-buttons {
        margin-bottom: 15px;
    }
</style>
<main class="main-content">
    <div class="container px-2">
        <h2>Edit Payment Receive</h2>
        <div class="page-header">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb ">
                    <li class="breadcrumb-item"><a href="{{ asset('dashboard') }}">{{ __('message.dashboard') }}</a></li>
                    <li class="breadcrumb-item"><a href="{{ asset('account/payment') }}">Payment</a></li>
                    <li class="breadcrumb-item active" aria-current="page">{{ __('message.add') }}</li>
                </ol>
            </nav>
        </div>
        @php 
            $is_id = isset($_GET['customer_id']) ? $_GET['customer_id'] : $payment->client_id;
        @endphp
        <div class="card">
            <x-flashMessage />
            @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
            <div class="row align-items-center mb-3 px-3 pt-3">
                <div class="col-md-6">
                    <div class="form-group row align-items-center">
                        <label class="col-md-4 col-form-label font-weight-bold">Client Name</label>
                        <div class="col-md-8">
                            
                            <form class="client_change_form" action="{{asset('account/add-payment-receive')}}" method="get">
                                <select class="form-control client_change_option" name="customer_id" required>
                                    <option selected disabled>Select</option>
                                    @foreach($clients as $cus)
                                        <option value="{{$cus->id}}" {{$is_id == $cus->id ? 'selected' : ''}}>{{$cus->name}}</option>
                                    @endforeach
                                </select>
                                
                            </form>
                        </div>
                    </div>
                </div>
            </div>
            <form action="{{asset('account/add-payment-receive')}}" method="post">

                @csrf

                <input type="hidden" name="payment_received_id" value="{{$payment->id}}">
                <input type="hidden" name="client_id" value="{{$is_id}}">

                <div class="card-header py-4">                   
                    
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <div class="form-group row align-items-center">
                                <label class="col-md-5 col-form-label font-weight-bold">Payment Number</label>
                                <div class="col-md-7">
                                    <input type="number" class="form-control" name="payment_number" value="{{$payment->payment_number}}" required>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group row align-items-center">
                                <label class="col-md-3 col-form-label font-weight-bold" >Date</label>
                                <div class="col-md-9">
                                    <input type="date" class="form-control" name="date" value="{{$payment->date}}" required>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group row align-items-center">
                                <label class="col-md-4 col-form-label font-weight-bold">Method</label>
                                <div class="col-md-8">
                                    <select class="form-control select2" name="payment_method" required>
                                        <option value="cash" {{$payment->payment_method == "cash" ? 'selected' : ''}}>Cash</option>
                                        <option value="bank_transfer" {{$payment->payment_method == "bank_transfer" ? 'selected' : ''}}>Bank Transfer</option>
                                        <option value="payment_gateway" {{$payment->payment_method == "payment_gateway" ? 'selected' : ''}}>Payment Gateway</option>
                                        <option value="upi" {{$payment->payment_method == "upi" ? 'selected' : ''}}>UPI</option>
                                        <option value="qr_code" {{$payment->payment_method == "qr_code" ? 'selected' : ''}}>QR Code</option>
                                        
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group row align-items-center">
                                <label class="col-md-5 col-form-label font-weight-bold">Amount</label>
                                <div class="col-md-7">
                                    <input type="number" class="form-control payment_amount" value="{{$payment->amount}}" name="amount" required>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group row align-items-center">
                                <label class="col-md-4 col-form-label font-weight-bold">Reference</label>
                                <div class="col-md-8">
                                    <input type="text" name="reference" class="form-control" value="{{$payment->reference}}" >
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group row align-items-center">
                                <label class="col-md-5 col-form-label font-weight-bold">Bank Charge</label>
                                <div class="col-md-7">
                                    <input type="number" class="form-control" name="bank_charge" value="{{$payment->bank_charge}}">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="d-flex justify-content-between bg-dark text-white px-3 py-2">
                        <div class="pt-2">
                            <h5>Unpaid Document</h5>
                        </div>
                        <div class="w-25">
                            
                            <select class="select2 change_time_wise" customer_id="{{isset($_GET['customer_id']) ? $_GET['customer_id'] : '' }}">
                                <option value="all" {{isset($_GET["time_duration"]) ? ($_GET["time_duration"] =="all" ? "selected" : "") : ''}}>All</option>
                                <option value="this_month" {{isset($_GET["time_duration"]) ? ($_GET["time_duration"] =="this_month" ? "selected" : "") : ''}}>This Month</option>
                                <option value="last_six_month" {{isset($_GET["time_duration"]) ? ($_GET["time_duration"] =="last_six_month" ? "selected" : "") : ''}}>Last 6 Month</option>
                                <option value="this_year" {{isset($_GET["time_duration"]) ? ($_GET["time_duration"] =="this_year" ? "selected" : "") : ''}}>This Year</option>
                            </select>
                        </div>
                    </div>
                    @if(isset($invoices))
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover">
                            <thead class="thead-light">
                                <tr>
                                    <th style="width: 10%">SN.</th>
                                    <th style="width: 10%">Date</th>
                                    <th style="width: 10%">Due Date</th>
                                    <th style="width: 20%">Client</th>
                                    <th style="width: 15%">Number</th>
                                    <th style="width: 10%">Amount</th>
                                    <th style="width: 15%">Amount Due</th>
                                    <th style="width: 15%">Payment Value</th>
                                </tr>
                            </thead>
                            <tbody>
                                @php
                                    $total = 0;
                                    $due_amomunt = 0;
                                    $paid_amount = 0;
                                @endphp
                                @foreach($invoices as $key=>$in)
                                
                                    <tr>
                                        <td>{{++$key}}</td>
                                        <td>{{$in->invoice_date}}</td>
                                        <td>{{$in->due_date}}</td>
                                        <td>{{$in->client_name}}</td>
                                        <td>{{$in->invoice_number}}</td>
                                        <td>{{$in->grand_total}}</td>
                                        <td>{{$in->amount_due}}</td>
                                        <td>
                                            <input type="hidden" value="{{$in->id}}" name="invoice_id[]">
                                            @php
                                                $paymentValue = 0;
                                                if(isset($payment_details)) {
                                                    foreach($payment_details as $detail) {
                                                        if($detail->invoice_id == $in->id) {
                                                            $paymentValue = $detail->payment_value;
                                                            break;
                                                        }
                                                    }
                                                }
                                            @endphp
                                            <input type="text" value="{{ $paymentValue }}" class="form-control payment-value-field" name="payment_value[]">
                                        </td>
                                    </tr>
                                    @php
                                        $total += $in->grand_total;
                                        $due_amomunt += $in->amount_due;
                                        $paid_amount += $paymentValue;
                                    @endphp
                                @endforeach
                            </tbody>
                        </table>
                        <div class="d-flex justify-content-end">
                            <div>
                                <h5>Total Amount: <span class="total-amount-display">{{$total}}</span></h5>
                                <h5>Due Amount: <span class="due-amount-display">{{$due_amomunt}}</span></h5>
                                <h5>Paid Amount: <span class="paid-amount-display">{{$paid_amount}}</span></h5>
                            </div>
                        </div>
                    </div>
                    <div class="mt-3 d-flex justify-content-center">
                        {{ $invoices->links('pagination::bootstrap-4') }} 
                    </div>
                    @endif
                    <div class="mt-4">
                        <h6>Memo/notes</h6>
                        <textarea class="form-control" name="note" rows="3" placeholder="Enter any additional notes here...">{{$payment->note}}</textarea>
                    </div>

                    <div class="d-flex justify-content-end mt-4">
                        
                        <div>
                            
                            <button type="submit" class="btn btn-primary">Save & View Receipt</button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>


    <!-- The Modal -->
    <div class="modal" id="invoiceModal">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">

            <!-- Modal Header -->
            <div class="modal-header bg-success rounded-0">
                <h4 class="modal-title">Add Expense</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>

            <!-- Modal body -->
            <div class="modal-body">
                
                <form action="{{ asset('account/add-account-expense') }}" method="post">
                    @csrf
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label>Expense Name</label>
                                <input type="text" name="name" class="form-control">
                            </div>
                        </div>
                    </div>
                    
                    <div class="d-flex justify-content-end">
                        <button type="submit" class="btn btn-success">Submit</button>
                    </div>
                </form>
            </div>

            

            </div>
        </div>
    </div>
</main>
@endsection

@push('footer-script')

<script>
    $(document).ready(function() {


        //change invoice number
        $(".client_change_option").on("change",function(){

            $(".client_change_form").submit();
            
        });

        $(".change_time_wise").on("change",function(){
            var time_duration = $(this).val();
            var customer_id = $(this).attr("customer_id");
            window.location.href= "{{asset('account/add-payment')}}?time_duration="+time_duration+"&customer_id="+customer_id;


        });

        $(".payment-value-field").on("input",function(){
            var isCheck = $(this).val();
        
            if(isNaN(isCheck))
            {
                alert("Enter number only !");
                $(this).val(0);
            }
        });
       
        $(".payment_amount").on("input", function() {
        var paymentAmount = parseFloat($(this).val()) || 0;
        var remainingAmount = paymentAmount;
        
        // Reset all payment value fields first
        $("input.payment-value-field").val('');
        
        // Process each invoice row
        $("table tbody tr").each(function() {
            if (remainingAmount <= 0) return;
            
            var dueAmount = parseFloat($(this).find("td:eq(6)").text()) || 0;
            var paymentValueField = $(this).find("input.payment-value-field");
            
            // Calculate payment for this invoice
            var paymentForThisInvoice = Math.min(dueAmount, remainingAmount);
            
            // Update the payment value field
            paymentValueField.val(parseFloat(paymentForThisInvoice).toFixed(2));
            
            // Deduct from remaining amount
            remainingAmount -= paymentForThisInvoice;
        });
        
        // Update totals display
        updateTotals();
    });
    
    // Handle individual payment value changes
    $(document).on("input", "input.payment-value-field", function() {
        updateTotals();
    });
    
    // Function to update totals
    function updateTotals() {
        var totalPaid = 0;
        
        // Calculate total paid amount
        $("input.payment-value-field").each(function() {
            totalPaid += Number($(this).val()) || 0;
        });
        
        // Update paid amount display
        $(".paid-amount-display").text(totalPaid.toFixed(2));
        
        // Update the main payment amount field to match
        $(".payment_amount").val(Number(totalPaid));
    }
        
        
    });
</script>
@endpush