@extends('Layouts.Application')

@section('MainContent')

<div class="row">
    <div class="col-sm-12">
        <div class="panel panel-default">
            <div class="panel-heading"><strong>Student Online Payment</strong></div>
            <div class="panel-body">
                @if (session()->has('errorMessage'))
                    <div class="alert alert-danger alert-dismissible" role="alert">
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <strong>Error!</strong> {{ session()->pull('errorMessage') }}
                    </div>
                @endif

                @if (session()->has('successMessage'))
                    <div class="alert alert-success alert-dismissible" role="alert">
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <strong>Success!</strong> {{ session()->pull('successMessage') }}
                    </div>
                @endif

                <div class="table-responsive">
                    <table class="table table-condensed table-bordered text-uppercase">
                        <thead>
                            <input type="hidden" id="grand_total_amount" name="total_amount">
                            <input type="hidden" id="head_amount" name="head_amount">
                            <input type="hidden" id="payment_id" name="payment_id">

                            <tr>
                                <td colspan="2">
                                    NAME : <strong> {{ Auth::user()->full_name }} </strong>
                                </td>
                                <td>
                                    ID : <strong> {{ $studentID->system_generated_student_id }} </strong>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    CLASS : <strong>{{ isset($studentID->class_info->ClassName) ? $studentID->class_info->ClassName : '' }}</strong>
                                </td>
                                <td>
                                    SECTION : <strong>{{ isset($studentID->section->SectionName) ? $studentID->section->SectionName : '' }}</strong>
                                </td>
                                <td>
                                    GROUP : <strong>{{ isset($studentID->group->GroupName) ? $studentID->group->GroupName : '' }}</strong>
                                </td>
                            </tr>
                        </thead>
                    </table>

                    <table id="tblbody" class="table table-condensed table-bordered text-uppercase">
                        <thead>
                            <colgroup>
                                <col width="14%">
                                <col width="8%">
                                <col width="70%">
                                <col width="8%">
                            </colgroup>
                            <tr>
                                <th>Head Name<sup><i class="fa fa-asterisk"></i></sup></th>
                                <th>Head Value</th>
                                <th>Month<sup><i class="fa fa-asterisk"></i></sup></th>
                                <th>Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>
                                    <select class="form-control" name='head_name' id="head_name">
                                        <option value="">----- Select -----</option>
                                        @if(isset($paymentHead))
                                            @foreach($paymentHead as $ph)
                                                <option value="{{ $ph->thisTableID . '_' . $ph->student_payment_id }}" {{ $ph->student_payment_id == 1 ? "selected" : "" }}>{{ $ph->student_payment_name }}</option>
                                            @endforeach
                                        @endif
                                    </select>
                                    <span class="label label-danger">{{ $errors->payment->first('head_name') }}</span>
                                </td>
                                <td style="text-align: center; vertical-align: middle;">
                                    <span class="head_price">0</span>
                                </td>
                                <td>
                                    <div style="display: flex; flex-direction: row;">
                                        @foreach ($months as $key => $month)
                                            <?php
                                                $neededObject = array_filter(
                                                    $receivedPaymentHead,
                                                    function ($e) use (&$key) {
                                                        if ($e->month == $key && $e->year) {
                                                            return true;
                                                        } else {
                                                            return false;
                                                        }
                                                    }
                                                );
                                            ?>
                                            <div style="padding: 5px; border: 1px solid #ddd; text-align: center; margin: 2px;">
                                                <input type="checkbox" class="bKashMonths" value="{{ $key }}" {{ !empty($neededObject) ? "checked disabled" : '' }} id="month-{{ $key }}"> 
                                                <label for="month-{{ $key }}" style="user-select: none;">{{ $month }}</label>
                                            </div>
                                        @endforeach
                                    </div>
                                    <span class="label label-danger">{{ $errors->payment->first('months') }}</span>
                                </td>
                                <td style="text-align: center; vertical-align: middle;">
                                    <span class="total">0</span>
                                </td>
                            </tr>
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="3" class="text-right">
                                    Online service charge (1.5%)
                                </td>
                                <td style="text-align: center">
                                    <span id="serviceCharge">0</span>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="3" class="text-right">
                                    Grand Total
                                </td>
                                <td style="text-align: center">
                                    <span id="gtotal">0</span>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="5" style="text-align:center">
                                    <img src="{{ asset('rsrc/multimedia/pay_with_bkash.png') }}" width="150px" height="34" id="bKash_button" disabled="disabled" style="cursor: pointer;">
                                </td>
                            </tr>
                        </tfoot>
                    </table>
                </div>

                <div id="student_payment_status"></div>
            </div>
        </div>  
    </div>
</div>

@section('script')

<script src="https://scripts.pay.bka.sh/versions/1.2.0-beta/checkout/bKash-checkout.js"></script>

<script>
    $(document).ready(function() {
        var paymentID = '';

        bKash.init({
            paymentMode: 'checkout',
            paymentRequest: {
				amount: '10',
				intent: 'sale'
			},
            createRequest: function(request) {
                $.ajax({
                    url: baseURL + "/!/StudentModule/StudentOnlinePayment/bKash/InitiatePayment",
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        "amount": request.amount,
                        "_token": "<?php echo csrf_token(); ?>",
                        "student_payment_id": $("#head_name").val(),
                        "months": $.map($('input[type="checkbox"]:checked').not(":disabled"),  function(e) { return +e.value; })
                    }),
                    success: function(data) {
                        if (data.create_payment_response && data.create_payment_response.paymentID != null) {
                            paymentID = data.create_payment_response.paymentID;
                            bKash.create().onSuccess(data.create_payment_response);
                        } else if (data.status == 'failed') {
                            bKash.create().onError();
                            Swal.fire('Oops...', data.message, 'error');
                        } else {
                            bKash.create().onError();
                            Swal.fire('Oops...', data.create_payment_response.errorMessage, 'error');
                        }
                    },
                    error: function(jqXHR, textStatus) {
                        bKash.create().onError();
                        Swal.fire('Oops...', textStatus, 'error');
                    },
                    timeout: 30000
                });
            },
            executeRequestOnAuthorization: function() {
                $.ajax({
                    url: baseURL + "/!/StudentModule/StudentOnlinePayment/bKash/executePaymentRequest",
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        "paymentID": paymentID,
                        "_token": "<?php echo csrf_token(); ?>"
                    }),
                    success: function(apiResponseData) {
                        if (apiResponseData.payment_execute_response && apiResponseData.payment_execute_response.transactionStatus === "Completed") {
                            store_student_payment_details(apiResponseData.payment_execute_response);
                        } else {
                            bKash.execute().onError();
                            Swal.fire('Oops...', apiResponseData.payment_execute_response.errorMessage, 'error');
                        }
                    },
                    error: function(jqXHR, textStatus) {
                        if (textStatus == 'timeout') {
                            $.ajax({
                                url: baseURL + "/!/StudentModule/StudentOnlinePayment/bKash/queryPaymentDetails",
                                type: 'POST',
                                contentType: 'application/json',
                                data: JSON.stringify({
                                    "paymentID": paymentID,
                                    "_token": "<?php echo csrf_token(); ?>"
                                }),
                                success: function(apiResponseData) {
                                    if (apiResponseData.queryResult && apiResponseData.queryResult.transactionStatus === "Completed") {
                                        store_student_payment_details(apiResponseData.queryResult);
                                    } else if (apiResponseData.queryResult && apiResponseData.queryResult.transactionStatus === "Initiated") {
                                        bKash.execute().onError();
                                        Swal.fire('Oops...', "Transaction couldn't complete. Please try again!", 'error');
                                    } else {
                                        bKash.execute().onError();
                                        Swal.fire('Oops...', apiResponseData.queryResult.errorMessage, 'error');
                                    }
                                },
                                error: function(jqXHR, textStatus) {
                                    bKash.execute().onError();
                                    Swal.fire('Oops...', textStatus, 'error');
                                },
                                timeout: 30000
                            });
                        } else {
                            bKash.execute().onError();
                            Swal.fire('Oops...', textStatus, 'error');
                        }
                    },
                    timeout: 30000
                });
            },
            onClose: function () {
                Swal.fire('Oops...', "You have cancelled the transaction!", 'warning');
            }
        });

        $('#bKash_button').removeAttr('disabled');

        function store_student_payment_details(apiResponseData) {
            $.ajax({
                url: baseURL + "/!/StudentModule/StudentOnlinePayment/bKash/storePaymentDetails",
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    "student_payment_id": $("#head_name").val(),
                    "student_payment_name": $("#head_name option:selected").text(),
                    "head_amount": $("#head_amount").val(),
                    "months": $.map($('input[type="checkbox"]:checked').not(":disabled"),  function(e) { return +e.value; }),
                    "_token": "<?php echo csrf_token(); ?>",
                    "totalAmount": $(".total").text(),
                    "service_charge": $('#serviceCharge').text(),
                    "paymentExecuteResponse": apiResponseData
                }),
                success: function(data) {
                    if (data.status === "success") {
                        bKash.execute().onError();

                        $("#student_payment_status").html("<div class='alert alert-success alert-dismissible text-center' role='alert'>\
                            <button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button>\
                            <strong>Success!</strong> Student Payment Successful. bKash Transaction Id: <strong>" + apiResponseData.trxID + "</strong>\
                        </div>");

                        Swal.fire(
                            'Successful',
                            'Student Payment Successful. bKash Transaction Id: ' + apiResponseData.trxID,
                            'success'
                        );

                        $('input[type="checkbox"]:checked').attr('disabled', true);
                    } else {
                        bKash.execute().onError();
                        Swal.fire('Oops...', data.message, 'error');
                    }
                },
                error: function(jqXHR, textStatus) {
                    bKash.execute().onError();
                    Swal.fire('Oops...', textStatus, 'error');
                }
            });
        }

        $(document).on('change', '#head_name', function() {
            var headIdAndName = $(this).val();
            var headIdAndNameArr = headIdAndName.split("_");
            var headName = headIdAndNameArr[0];
            var paymentId = headIdAndNameArr[1];
            $("#payment_id").val(paymentId);

            if (headName != null || headName != '') {
                $.ajax({
                    url: baseURL + '/!/StudentModule/StudentOnlinePayment/GetHeadValue/' + headName,
                    type: 'GET',
                    success: function (response) {
                        $('.head_price').html(response);
                        $('#head_amount').val(response);
                    }
                });
            } else {
                $('.head_price').html('0');
                return false;
            }
        });

        $("#head_name").trigger('change');

        $(document).on('change', '.bKashMonths', function () {
            var price = parseInt($('.head_price').text());
            var selectedMonths = $('input[type="checkbox"]:checked').not(":disabled").length;
            var totalAmount = price * selectedMonths;
            var serviceCharge = Math.ceil((totalAmount / .985) - totalAmount);
            var grandTotal = totalAmount + serviceCharge;

            var selectedMonthsArray = $.map($('input[type="checkbox"]:checked').not(":disabled"),  function(e) { return +e.value; });

            bKash.reconfigure({
                paymentRequest: {
                    amount: grandTotal,
                    intent: 'sale'
                }
            });

            $('.total').html(totalAmount);
            $('#gtotal').html(grandTotal);
            $('#serviceCharge').html(serviceCharge);
            $('#grand_total_amount').val(grandTotal);
        });
    });
</script>
@endsection

@endsection