<?php 

/*var_dump($pending_payment_data);
var_dump($pending_payment_data['finance_discount']);*/
// echo $current_date;
// die('s-');
 ?>

@extends('template.app')

@section('meta')
@endsection

@section('title')
    Payment Details
@endsection

@section('styles')
@endsection

@section('content')
<!-- <div class="page-breadcrumb">
    <div class="row">
        <div class="col-7 align-self-center">
            <h4 class="page-title text-truncate text-dark font-weight-medium mb-1">Invoice Create</h4>
            <div class="d-flex align-items-center">
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb m-0 p-0">
                        <li class="breadcrumb-item"><a href="{{ route('dashboard') }}" class="text-muted">Dashboard</a></li>
                        <li class="breadcrumb-item"><a href="{{ route('car_varient') }}" class="text-muted">Invoice Create</a></li>
                    </ol>
                </nav>
            </div>
        </div>
    </div>
</div> -->
<div class="container-fluid">
    <div class="row">
        @if(isset($pending_payment_data['payment_status']) && $pending_payment_data['payment_status'] == 1)

        <div class="col-12">
            <div class="alert alert-success" role="alert">
              No Pending Payment
            </div>
            
            <div class="card">
                <div class="card-body">
                    <form name="form" id="payment_form" enctype="multipart/form-data">
                        @csrf
                        @method('POST')
                        <div class="row">
                            <div class="col-md-12 text-center">
                                <hr>
                                <h2>Payment Detail</h2>
                                <hr>
                            </div>
                            <div class="col-sm-12">
                                <div class="table-responsive">
                                    <table class="table">
                                    <thead>
                                      <tr style="background-color:grey;">
                                        <th><b>Detail</b></th>
                                        <th><b>AMOUNT(Rs)</b></th>                                       
                                      </tr>
                                    </thead>
                                    <tbody> 
                                        <input type="hidden" name="payment_done_status" value="all_payment_done">
                                        <input type="hidden" name="id" value="{!! $id !!}">
                                        <input type="hidden" name="obf_id" value="{!! $obf_id !!}">
                                        <input type="hidden" name="remark" value="All Payment Done">
                                        
                                        <tr>
                                            <th>On Road Price (A)</th>                                        
                                            <td>{{ isset($pending_payment_data['on_road_price']) ? $pending_payment_data['on_road_price'] : '' }}</td>
                                        </tr>
                                        <tr>
                                            <th>Total On Road Discount (B)</th>                                        
                                            <td>{{ isset($pending_payment_data['finance_discount']) ? $pending_payment_data['finance_discount'] : '' }}</td>
                                        </tr>
                                        <tr style="background-color:grey;">
                                            <th>Net Receivable Amount (A - B = C)</th>   
                                            @php
                                                $net_receivable_amt = $pending_payment_data['on_road_price'] - $pending_payment_data['finance_discount'];
                                            @endphp
                                            <td>{{ $net_receivable_amt  }}</td>
                                        </tr>
                                        <tr>
                                            <th></th>                                        
                                            <td></td>
                                        </tr>
                                        <tr>
                                            <th>Trade Car Value</th>                                        
                                            <td>{{ isset($pending_payment_data['trade_car_value']) ? $pending_payment_data['trade_car_value'] : '' }}</td>
                                        </tr>
                                        <tr>
                                            <th>Total Receipt Amount</th>                                        
                                            <td>{{ isset($pending_payment_data['cash_receipt_amount']) ? $pending_payment_data['cash_receipt_amount'] : '' }}</td>
                                        </tr>
                                        <tr style="background-color:grey;">
                                            <th>Total Received Amount (D)</th>    
                                            @php
                                                $ttl_rcd_amt = ($pending_payment_data['trade_car_value'] ?? 0) + ($pending_payment_data['cash_receipt_amount'] ?? 0);
                                            @endphp
                                            <td>{{ $ttl_rcd_amt }}</td>
                                        </tr>
                                        <tr>
                                            <th>Due Amt (+) / Refundable Amt (-)</th>                                        
                                            <td>{{ isset($pending_payment_data['pending_payment']) ? $pending_payment_data['pending_payment'] : '' }}</td>
                                        </tr>
                                    </tbody>
                                  </table>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <a href="{{ route('order') }}" class="btn waves-effect waves-light btn-rounded btn-outline-secondary">Back</a>
                            <button type="submit" class="btn waves-effect waves-light btn-rounded btn-outline-secondary" id="payment_submit">Submit</button>
                        </div>
                    </form>
                </div>
            </div>
        </div> 
        @else
        <div class="col-12">
            <div class="alert alert-danger" role="alert">
              Please complete your payment
            </div>

            <div class="card">
                <div class="card-body">
                    <form action="{{ route('order.insert') }}" name="form" id="form" method="post" enctype="multipart/form-data">
                        @csrf
                        @method('POST')
                        <div class="row">
                            
                            <div class="col-md-12 text-center">
                                <div class="card table-full" style="min-width:100% !important;">
                                <div class="card-body">
                                    <table class="table table-bordered data-table" id="data-table" style="text-align: center;">
                                        <thead>
                                            <tr>
                                                <th>Location</th>
                                                <th>Customer Name</th>
                                                <th>KEC Name</th>
                                                <th>Team Name</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr>
                                                <td>{{ $obfRecords->branch_name ?? '-' }}</td>
                                                <td>{{ $obfRecords->customer_name ?? '-' }}</td>
                                                <td>{{ $obfRecords->kec_name ?? '-' }}</td>
                                                <td>{{ $obfRecords->team_name ?? '-' }}</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                                <hr>
                                <h2>Payment Pending Detail</h2>
                                <hr>
                            </div>
                            <div class="col-sm-12">
                                <div class="table-responsive">
                                    <table class="table">
                                    <thead>
                                      <tr>
                                        <th><b>Detail</b></th>
                                        <th><b>AMOUNT(Rs)</b></th>                                       
                                      </tr>
                                    </thead>
                                    <tbody> 
                                        <input type="hidden" name="payment_done_status" value="all_payment_done">
                                        <input type="hidden" name="id" value="{!! $id !!}">
                                        <input type="hidden" name="obf_id" value="{!! $obf_id !!}">
                                        <input type="hidden" name="remark" value="{{ ($pending_payment_data['pending_payment'] ?? '') . '/- Amount Pending But Approve From Authority' }}">

                                        
                                        <tr>
                                            <th>On Road Price (A)</th>                                        
                                            <td>{{ (is_array($pending_payment_data) && isset($pending_payment_data['on_road_price'])) ? $pending_payment_data['on_road_price'] : '' }}</td>
                                        </tr>
                                        <tr>
                                            <th>Total On Road Discount (B)</th>                                        
                                            <td>{{ (is_array($pending_payment_data) && isset($pending_payment_data['finance_discount'])) ? $pending_payment_data['finance_discount'] : '' }}</td>
                                        </tr>
                                        <tr style="background-color:grey;">
                                            <th>Net Receivable Amount (A - B = C)</th>   
                                            @php
                                                $net_receivable_amt = ($pending_payment_data['on_road_price'] ?? 0) - ($pending_payment_data['finance_discount'] ?? 0);
                                            @endphp

                                            <td>{{ $net_receivable_amt  }}</td>
                                        </tr>
                                        <tr>
                                            <th></th>                                        
                                            <td></td>
                                        </tr>
                                        <tr>
                                            <th>Trade Car Value</th>                                        
                                            <td>{{ isset($pending_payment_data['trade_car_value']) ? $pending_payment_data['trade_car_value'] : '' }}</td>
                                        </tr>
                                        <tr>
                                            <th>Total Receipt Amount</th>                                        
                                            <td>{{ isset($pending_payment_data['cash_receipt_amount']) ? $pending_payment_data['cash_receipt_amount'] : '' }}</td>
                                        </tr>
                                        <tr style="background-color:grey;">
                                            <th>Total Received Amount (D)</th>    
                                            @php
                                                $ttl_rcd_amt = ($pending_payment_data['trade_car_value'] ?? 0) + ($pending_payment_data['cash_receipt_amount'] ?? 0);
                                            @endphp
                                            <td>{{ $ttl_rcd_amt }}</td>
                                        </tr>
                                        <tr>
                                            <th>Due Amt (+) / Refundable Amt (-)</th>                                        
                                            <td>{{ isset($pending_payment_data['pending_payment']) ? $pending_payment_data['pending_payment'] : ''  }}</td>
                                        </tr>
                                    </tbody>
                                  </table>
                                </div>
                            </div>
                        </div>

                        @php
                            $from_amt = auth()->user()->roles[0]['from_amt'];
                            $to_amt = auth()->user()->roles[0]['to_amt']; 
                        @endphp
                        <div class="form-group">
                            <a href="{{ route('order') }}" class="btn waves-effect waves-light btn-rounded btn-outline-secondary">Back</a>
                            @if(($pending_payment_data['pending_payment'] ?? 0) <= $to_amt)
                                <button type="submit" class="btn waves-effect waves-light btn-rounded btn-outline-secondary" id="payment_submit">Approve</button>
                            @endif
                        </div>
                    </form>
                </div>
            </div>
        </div>
        @endif
    </div>
</div>
@endsection

@section('scripts')
<script>
    $("#percentage").keyup(function(e){
        $('.percentage').html('');
        if ($(this).val() > 99){
            $('.percentage').html('');
            $('.percentage').html('Enter Value Between 0 to 100!');
            $(this).val();
            $(this).val(100);
        }else if($(this).val() <= 99){
            $('.percentage').html('');
        }
    });

</script>

<script>
    // $(document).ready(function() {
    //     var form = $('#submit');
    //     $('.kt-form__help').html('');
    //     form.submit(function(e) {
    //         e.preventDefault();
    //         $('.help-block').html('');
    //         $('.m-form__help').html('');
    //         $.ajax({
    //             url: form.attr('action'),
    //             type: form.attr('method'),
    //             data: new FormData($(this)[0]),
    //             dataType: 'json',
    //             async: false,
    //             processData: false,
    //             contentType: false,
    //             success: function(json) {
    //                 return true;
    //             },
    //             error: function(json) {
    //                 if (json.status === 422) {
    //                     e.preventDefault();
    //                     var errors_ = json.responseJSON;
    //                     $('.kt-form__help').html('');
    //                     $.each(errors_.errors, function(key, value) {
    //                         $('.' + key).html(value);
    //                     });
    //                 }
    //             }
    //         });
    //     });
    // });
    
    $('#form').on('submit', function (e) {
        e.preventDefault();
        var dummyElement = $('<div>')
            .attr('data-id', "{{ base64_encode($pending_payment_data['id'] ?? 0) }}")
            .attr('data-status', 'all_payment_done');
    
        change_status(dummyElement[0], function(response) {
            // After status changed, submit the form
            $('#form')[0].submit();
        });
    });
    
    function change_status(object){
        var id = $(object).data("id");
        var obf_id = $(object).data("obf_id") || 0;
        var status = $(object).data("status");

        if(status == 'delete'){
            status = 'deleted';
        }
        if (confirm('Are you sure you want to change Status ?')) {
            $.ajax({
                "url": "{!! route('order.change_status') !!}",
                "dataType": "json",
                "type": "POST",
                "data":{
                    id: id,
                    obf_id: obf_id,
                    status: status,
                    _token: "{{ csrf_token() }}"
                },
                success: function (response){
                    if (response.code == 200){
                        if(response.obf_id != undefined){
                            window.location.href="{{url('order/payment_pending_detail')}}?obf_id="+response.obf_id;
                        }else{
                            datatable.ajax.reload();
                            toastr.success('Status chagned successfully', 'Success');    
                        }                        
                    }else{
                        toastr.error('Failed to change status', 'Error');
                    }
                }
            });
        }
    }
    
    $(document).ready(function () {
        $("#payment_submit").on("click", function (e) {
            e.preventDefault(); // Prevent default form submission
    
            var id = $("input[name='id']").val();
            var obf_id = $("input[name='obf_id']").val();
            var status = $("input[name='payment_done_status']").val();
            var remark = $("input[name='remark']").val();
    
            $.ajax({
                "url": "{!! route('order.update_payment_status') !!}",
                "dataType": "json",
                "type": "POST",
                "data":{
                    id: id,
                    obf_id: obf_id,
                    status: status,
                    remark: remark,
                    _token: "{{ csrf_token() }}"
                },
                success: function (response){
                    if (response.code == 200){
                        window.location.href = "{{ url('order') }}";
                        toastr.success('Status chagned successfully', 'Success');    
                    }else{
                        toastr.error('Failed to change status', 'Error');
                    }
                }
            });
        });
    });
        // var id = $("#id").val();
        // var obf_id = $("#obf_id").val();
        // var status = $("#payment_done_status").val();
        
        // alert(id);
        // alert(obf_id);
        // alert(status);

        // if(status == 'delete'){
        //     status = 'deleted';
        // }
        
        
    // }
    
    // $(document).ready(function() {
    //     $('#form').on('submit', function(e) {
    //         e.preventDefault(); // prevent default form submission
    //         $('.help-block').html('');
    //         $('.m-form__help').html('');
    
    //         $.ajax({
    //             url: $(this).attr('action'),
    //             type: $(this).attr('method'),
    //             data: new FormData(this),
    //             dataType: 'json',
    //             processData: false,
    //             contentType: false,
    //             success: function(json) {
    //                 console.log("Success", json);
    //                 alert("Form submitted successfully!");
    //             },
    //             error: function(json) {
    //                 if (json.status === 422) {
    //                     var errors_ = json.responseJSON;
    //                     $.each(errors_.errors, function(key, value) {
    //                         $('.' + key).html(value);
    //                     });
    //                 }
    //             }
    //         });
    //     });
    // });


    $('#bill_to_1').on('click', function(){
        $('#bill_to').val($('#customer_name').val());
        $('#bill_to_2').prop('checked',false);
    });

    $('#bill_to_2').on('click', function(){
        $('#bill_to').val($('#company_name').val());
        $('#bill_to_1').prop('checked',false);
    });

    $('#address_ch_1').on('click', function(){
        $('#address').val($('#address_1').val());
        $('#address_ch_2').prop('checked',false);
    });

    $('#address_ch_2').on('click', function(){
        $('#address').val($('#address_2').val());
        $('#address_ch_1').prop('checked',false);
    });

    $('#address_ch_1_s').on('click', function(){
        $('#ship_to').val($('#address_1').val());
        $('#address_ch_2_s').prop('checked',false);
    });

    $('#address_ch_2_s').on('click', function(){
        $('#ship_to').val($('#address_2').val());
        $('#address_ch_1_s').prop('checked',false);
    });
</script>
@endsection