<style>
    .main {
        display: flex;
        align-items: center;
        margin: auto;
    }

    .unpaid_fee_table th {
        width: 150px !important;
    }

    .eft-action i {
        margin: 0 5px;
    }

    .eft-table td,
    th {
        padding: 5px !important;
        font-size: 13px !important;
        text-align: center !important;
    }

    .fee-modal-header {
        border: none !important;
        padding: 30px 20px 10px 20px !important;
    }

    .fee-modal-body {
        padding: 10px 10px 10px 20px !important;
    }

    .fee-modal-footer {
        border: none !important;
        padding: 10px 30px 30px 30px !important;
    }

    .fee-modal-title {
        font-size: 20px;
        font-weight: 600;
    }

    .fee-add-btn {
        background-color: #032DA1;
        color: white;
        font-size: 12px;
        text-align: center;
        font-weight: 400;
        width: 130px;
    }

    .fee-cancel-btn {
        background-color: #AEAEAE;
        color: white;
        font-size: 12px;
        text-align: center;
        font-weight: 400;
        width: 130px;
    }

    .fee-modal-select-label {
        font-size: 14px;
        font-weight: 500;
        margin-bottom: 2px;
    }

    .w-60 {
        width: 70%;
    }

    .user-info-row-one {
        margin-bottom: 30px !important;
    }

    .title p {
        font-weight: 500;
        font-size: 20px;
        padding-bottom: 3px;
        border-bottom: 1px solid #c6c6c6;
        display: inline-block;
    }

    .total_th {
        font-size: 17px !important;
        vertical-align: middle !important;
    }

    table td {
        text-align: center !important;
        vertical-align: middle !important;
    }

    table.dataTable tbody td {
        font-size: 12px;
    }
</style>
<div class="wraper responsive-width">
    <main class="long-tbl-main" id="main">
        <div class="from-group">
            <a href="<?= base_url(); ?>admin/student"><button type="button" class="btn btn-success btn-sm btn-dark">Back</button></a>
        </div>
        <!-- admin template section -->
        <div class="admin_tempblock">
            <div class="admin_tempsec">
                <div class="admin_sec">

                    <div class="subsec_sec">
                        <div class="subject_r">
                            <div class="subject_lsec">
                                <?php if (!empty($student_info_array)) { ?>
                                    <!-- <div class="subject_lhead"> -->

                                    <?php
                                    if (empty($student_info_array['photo'])) {

                                        $profileimg = base_url() . "common_assets/user.png";
                                    } else if (file_exists('assets_student/application/' . $student_info_array['photo'])) {

                                        $profileimg = base_url() . "assets_student/application/" . $student_info_array['photo'];
                                    } else {
                                        if ($student_info_array['gender'] == 'Male')
                                            $profileimg = base_url() . "common_assets/male_image.jpg";
                                        else
                                            $profileimg = base_url() . "common_assets/female_image.jpg";
                                    }
                                    // print_r($student_info_array); 
                                    ?>
                                    <div class="card">

                                        <div class="card-body py-3">
                                            <div class="row align-items-center px-3">

                                                <img src="<?= $profileimg; ?>" class="img-thumbnail img-fluid border-primary  rounded-circle applicant-img" style="width: 80px; height: auto !important;">

                                                <div class="px-3">
                                                    <label style="font-size: 18px; font-weight: 600;" class="my-0 h6"> <?= $student_info_array['name']  ?></label>
                                                    <h6 style="font-size: 12px">
                                                        <?= $student_info_array['studentId']  ?>
                                                    </h6>
                                                    <h6 style="font-size: 14px; font-weight: 600; ">
                                                        <?= $student_info_array['classroom_name']  ?>
                                                    </h6>
                                                    <h6 style="font-size: 13px; font-style: italic; font-weight: 500; ">
                                                        <?= $student_info_array['b_name']  ?>
                                                    </h6>


                                                </div>
                                                <div style="font-size: 14px; font-weight: 600; " class="col text-right">
                                                    <div>
                                                        <i class="fa fa-phone mx-1" aria-hidden="true" style="-webkit-transform: rotate(90deg); -moz-transform: rotate(90deg); "></i>
                                                        <?= $student_info_array['emergency_contact_number']  ?>
                                                    </div>
                                                    <div>
                                                        <?php
                                                        // print_r($student_info_array);
                                                        $url_params = array(
                                                            'batch_id' => $student_info_array['batch_id'],
                                                            'course_id' => $student_info_array['course_id'],
                                                            'section_id' => $student_info_array['section_id'],
                                                            'student_id' => $student_info_array['student_id']
                                                        );

                                                        // print_r($url_params);
                                                        ?>
                                                        <a href="<?= base_url() . 'admin/student-fees/' . urlencode(serialize($url_params)) ?>" class="btn btn-sm btn-outline-primary mt-1 mx-1" style="font-size: 0.75rem;">Fee Management</a>
                                                        <a href="#" class="btn btn-sm btn-outline-primary mt-1" style="font-size: 0.75rem;">Download Academic Report</a>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <!-- <small><?= $student_info_array['classroom_name'] ?></small> -->
                                    <hr>
                                <?php } ?>
                                <div class="application-toggle-btn view-student-tab">
                                    <ul class="nav nav-pills">
                                        <li>
                                            <a href="<?= base_url() ?>admin/view-student/<?= $student_id ?>">Student
                                                Info</a>
                                        </li>
                                        <li>
                                            <a href="#">View
                                                Attendance</a>
                                        </li>
                                        <li>
                                            <a class="active" href="<?= base_url() ?>admin/view-student-payments/<?= $student_id ?>">Fee
                                                &amp; Payments</a>
                                        </li>
                                    </ul>
                                </div>

                                <?php if ($this->session->flashdata('success')) { ?>

                                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                                        <p><?php echo $this->session->flashdata('success') ?></p>
                                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>

                                <?php } ?>

                                <?php if ($this->session->flashdata('failed')) { ?>

                                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                        <p><?php echo $this->session->flashdata('failed') ?></p>
                                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>

                                <?php } ?>
                                <!-- <p class="loading" style="display:none">Please wait....</p> -->
                                <form method="post" action="<?= base_url(); ?>admin/view-student-payments/<?= $student_id ?>">
                                    <div class="row my-auto">
                                        <div class="col-md-9 my-auto">
                                            <?php
                                            if (isset($batches) || !empty($batches)) {
                                                foreach ($batches as $row) {
                                                    if ($row['id'] == $selectedBatch) {
                                            ?>
                                                        <h6> Transactions of <?= $row['b_name'] ?></h6>

                                            <?php

                                                    }
                                                }
                                            }
                                            ?>
                                            <!-- Transactions of -->
                                        </div>
                                        <div class="col-md-3 my-auto">
                                            <label class="has-float-label mb-0">
                                                <select id="f_batch" name="f_batch" class="custom-select form-control" onchange="this.form.submit()">
                                                    <option value="">Select Batch</option>
                                                    <?php if (isset($batches) || !empty($batches)) {
                                                        foreach ($batches as $row) {
                                                            if ($selectedBatch != '')
                                                                $b_selected = ($row['id'] == $selectedBatch) ? 'selected' : '';
                                                            else
                                                                $b_selected = ($row['id'] == $school_info['batch_id']) ? 'selected' : '';
                                                    ?>

                                                            <option value="<?php echo $row['id'] ?>" <?= $b_selected; ?>>
                                                                <?php echo $row['b_name']; ?></option>

                                                    <?php    }
                                                    } ?>
                                                </select>
                                                <span>Batch<span style="font-weight:bold;color:red;"> * </span></span>
                                            </label>
                                        </div>
                                    </div>

                                    <!-- <input type="submit" name="bUpdate" value="update"> -->
                                </form>
                                <?php

                                ?>

                                <?php

                                if (!$transactions) {
                                    echo '<p></p>';
                                } else { ?>

                                    <hr class="my-2">
                                    <div class="recent-transaction mb-5">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <h5 class="mb-3"> Recent Transactions</h5>
                                            </div>
                                            <div class="col-md-6"> <button style="    font-size: 14px;padding: 6px 25px ; margin: 0px 0px 0px 5px" class="subject_addbtn download_multiple_invoice float-right" id="download_multiple_invoice" data-toggle="tooltip" title="Selected Invoice Print">Print <i class="fa fa-print" aria-hidden="true"></i></button></div>
                                        </div>


                                        <div class="recent-table">
                                            <table id="tbl1" class="tbl2 display table-responsive">
                                                <thead>
                                                    <tr>
                                                        <th><input type="checkbox" id="chkParent" /></th>
                                                        <th>#</th>
                                                        <th>Payment For</th>
                                                        <th>Date</th>
                                                        <th>Invoice No</th>
                                                        <th>Payment Status</th>
                                                        <th>Amount</th>
                                                        <th>Discount</th>
                                                        <th>Fine Amount</th>
                                                        <th>Paid Amount</th>
                                                        <th>Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php
                                                    foreach ($transactions as $key => $value) {

                                                        $totalPaymentArray = explode(",", $value['payment_amt']);
                                                        $totalDeductionArray = explode(",", $value['deduction_amount']);
                                                        $totalFineAmountArray = explode(",", $value['fine_amount']);

                                                        $paid = (float)array_sum($totalPaymentArray) + (float)array_sum($totalFineAmountArray) - (float)array_sum($totalDeductionArray);

                                                    ?>
                                                        <tr>
                                                            <td><input type="checkbox" name="student_inovice_list[]" data-transid="<?= $value['online_transaction_id'] ?>" /></td>
                                                            <td><?= $key + 1 ?></td>
                                                            <td class="text-left">
                                                                <?php
                                                                $fee_values_arr = explode(',', $value['fee_values']);
                                                                $payment_for_arr = explode(',', $value['payment_for']);

                                                                // var_dump($fee_values_arr);


                                                                foreach ($fee_values_arr as $fKey => $fValue) {
                                                                    echo '<p class="m-0" style="font-size: 12px; font-weight: normal">' . $fValue ?><small>(<?= $payment_for_arr[$fKey] . ')</small></p>';
                                                                                                                                                        }
                                                                                                                                                            ?>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                $date = explode(' ', $value['payment_date']);
                                                                echo $date[0];
                                                                ?>
                                                            </td>
                                                            <td><?php
                                                                if ($school_info['invoice_prefix_status'] == 1 && !empty($value['invoice_no']))
                                                                    echo $school_info['invoice_prefix'] . $value['invoice_no'];
                                                                else
                                                                    echo $value['invoice_no'];

                                                                ?></td>
                                                            <!-- <td><?= $value['fee_values'] ?><small>(<?= $value['payment_for']  ?>)</small> -->
                                                            </td>
                                                            <td><?= $value['status']  ?></td>
                                                            <td>
                                                                <?= number_format((float)array_sum($totalPaymentArray), 2, '.', ''); ?>
                                                            </td>
                                                            <td>
                                                                <?= number_format((float)array_sum($totalDeductionArray), 2, '.', ''); ?>
                                                            </td>
                                                            <td>
                                                                <?= number_format((float)array_sum($totalFineAmountArray), 2, '.', ''); ?>
                                                            </td>
                                                            <td><?= number_format((float)$paid, 2, '.', ''); ?></td>
                                                            <td>

                                                                <div class="sub_tabbtnsec">
                                                                    <?php
                                                                    if (!empty($student_info_array)) { ?>

                                                                        <div class="sub_viewbtn" title="View"><a href="<?= base_url(); ?>admin/invoice/<?= urlsafe_b64encode($student_info_array['studentId']) ?>/<?= urlsafe_b64encode($value['txn_id']) ?>/<?= urlsafe_b64encode(0) ?>/<?= urlsafe_b64encode($value['online_transaction_id']) ?> "><i class="fa fa-eye" aria-hidden="true"></i></a>
                                                                        </div>
                                                                        <div class="sub_viewbtn" data-toggle="tooltip" title="<?= $value['payment_for'] ?>" title="View"><a href="#"><i class="fa fa-info-circle" aria-hidden="true"></i></a>
                                                                        </div>
                                                                    <?php } ?>

                                                                </div>
                                                            </td>
                                                        </tr>
                                                    <?php } ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>

                                <?php } ?>


                                <!-- Unpaid Fees in table format -->
                                <hr class="my-2">
                                <div class="pending-transaction mb-5">

                                    <h5 class="mb-3">Pending Transactions</h5>

                                    <div class="recent-table" style="width:1100px">
                                        <table id=" " class="tbl table unpaid_fee_table display ">
                                            <thead>
                                                <tr>
                                                    <th width="5%">
                                                        <input type="checkbox" id="main_check">
                                                    </th>
                                                    <th>Due-Date</th>
                                                    <th>Fee Name</th>
                                                    <th>Fee Amt</th>
                                                    <th>Pending Amt</th>
                                                    <th>Fine Amt</th>
                                                    <th>Payable Amt</th>
                                                    <th>Fine</th>
                                                    <th>Discount</th>
                                                    <th></th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>

                                                <?php
                                                $payment_status = array();
                                                $totalScholarshipAmt = 0;
                                                $scholarship_type = array();
                                                $course_fee_ids = array();
                                                $course_fee_amount = array();
                                                $totalDueAmount = 0;
                                                $totalDuePendginAmount = 0;
                                                foreach ($table_due_fees as $tdf_key => $tdf) {
                                                    array_push($payment_status, $tdf['fee_completed']);
                                                }
                                                if ($school_info['batch_id'] == $selectedBatch) {
                                                    if (in_array('no', $payment_status)) {
                                                        $batch_id = $table_due_fees[0]['batch_id'];
                                                        $batch_name = '';
                                                        foreach ($batches as $row) {
                                                            if ($row['id'] == $batch_id) {
                                                                $batch_name = $row['b_name'];
                                                            }
                                                        }



                                                ?>
                                                        <?php
                                                        foreach ($table_due_fees as $key => $value) {
                                                            // echo '<pre>';
                                                            // var_dump();
                                                            $paid_status = $value['fee_completed'] == 'no' ? TRUE : FALSE;
                                                            // echo '<pre>';
                                                            // print_r($value['hasScholarship']);



                                                            $totalFeeAmount = 0.0;
                                                            $totalPendingAmount = 0.0;
                                                            if (isset($value['is_half_fee']) && $value['is_half_fee'] == 'yes') {
                                                                $totalFeeAmount = number_format((float) $value['fee_amount'], 2, '.', '') / 2;
                                                                // array_push()
                                                                if ($totalFeeAmount < $value['pending_amount']) {
                                                                    $totalPendingAmount = $totalFeeAmount;
                                                                } else {
                                                                    $totalPendingAmount = number_format((float) $value['pending_amount'], 2, '.', '');
                                                                }
                                                            } else {
                                                                $totalFeeAmount = number_format((float) $value['fee_amount'], 2, '.', '');
                                                                $totalPendingAmount = number_format((float) $value['pending_amount'], 2, '.', '');
                                                            }

                                                            if ($value['hasScholarship'] == 'yes') {
                                                                if (isset($value['is_half_fee']) && $value['is_half_fee'] == 'yes') {
                                                                    $discount = ((float) $value['scholarship_discount'] / 100) * $totalFeeAmount;
                                                                    $totalFeeAmount = $totalFeeAmount - $discount;
                                                                } else {
                                                                    $totalFeeAmount = number_format($totalFeeAmount - (float) $value['scholarship_amount'], 2, '.', '');
                                                                }

                                                                // echo 'Scholarship Logic';
                                                                // echo 'Fee Amount = ' . $totalFeeAmount . ' Pending Amount = ' . $totalPendingAmount;
                                                                if ($totalFeeAmount < $totalPendingAmount) {
                                                                    $totalPendingAmount = $totalFeeAmount;
                                                                } else {
                                                                    $totalPendingAmount = number_format((float) $value['pending_amount'], 2, '.', '');
                                                                }
                                                            }

                                                            // echo $paid_status . '<br>';
                                                            if ($paid_status) {
                                                                $totalDueAmount = $totalDueAmount + $totalFeeAmount;

                                                                $totalDuePendginAmount = $totalDuePendginAmount + $totalPendingAmount;

                                                                $totalScholarshipAmt = $totalScholarshipAmt + $value['scholarship_amount'];

                                                                array_push($scholarship_type, $value['scholarship_type']);

                                                                array_push($course_fee_ids, $value['course_fee_id']);
                                                                array_push($course_fee_amount, $totalFeeAmount);

                                                                array_push($payment_status, 'no');
                                                            } else {
                                                                array_push($payment_status, 'yes');
                                                            }
                                                        }

                                                        ?>
                                                        <tr>
                                                            <td>
                                                                <?php if (in_array('no', $payment_status)) { ?>
                                                                    <input type="checkbox" onchange="toggleCheckbox(this,'<?= implode(',', $course_fee_ids) ?>',<?= $totalDueAmount ?>,<?= 0 ?>, <?= $totalScholarshipAmt ?>, '<?= implode(',', $scholarship_type) ?>')" class="checkbox">
                                                                    <span style="display:none" class="sop_id"><?= implode(',', $course_fee_ids) ?></span>
                                                                    <!-- <span style="display:none" class="fee_total_amount"><?= isset($value['is_half_fee']) && $value['is_half_fee'] == 'yes' ? $value['fee_amount'] / 2 : $value['fee_amount'] ?></span> -->
                                                                    <span style="display:none" class="fee_total_amount"><?= $totalDueAmount ?></span>
                                                                    <span class="row_index" style="display:none"><?= 99 ?></span>

                                                                <?php } else { ?>
                                                                    <i class="fa fa-check" style="color:green" aria-hidden="true"></i>
                                                                <?php } ?>

                                                            </td>
                                                            <!-- <td class="text-left">
                                                                <?php
                                                                //  $date = explode(' ', $value['batch_name']);
                                                                echo str_replace('Batch ', '', $value['batch_name']);
                                                                ?>
                                                            </td> -->
                                                            <td class="text-left">
                                                                <!-- <?php
                                                                        $date = explode(' ', $value['due_date']);
                                                                        echo $date[0];
                                                                        ?> -->
                                                                -
                                                            </td>
                                                            <td class="row_fee_name text-left">
                                                                <!-- <?= $value['fee_name'] ?> --> Old Due Fees
                                                                <small>(<?= $batch_name ?>)</small>
                                                            </td>
                                                            <td>
                                                                <?= $totalDueAmount ?>
                                                                <!-- <?= isset($value['is_half_fee']) && $value['is_half_fee'] == 'yes' ? number_format((float) $value['fee_amount'], 2, '.', '') / 2 : number_format((float) $value['fee_amount'], 2, '.', ''); ?> -->
                                                            </td>

                                                            <td class="row_fee_amount">
                                                                <?= $totalDuePendginAmount ?>
                                                            </td>
                                                            <td><?= number_format((float) $value['fine_amount'], 2, '.', ''); ?>
                                                            </td>
                                                            <td>
                                                                <?php if (in_array('no', $payment_status)) { ?>
                                                                    <input type="text" onkeypress="return numbersOnlyValidation(event)" min="0" onchange="addPayableFineAmountToDataObject(this,'payable_amount')" class=" form-control payable_amount" placeholder="Enter the amount" class="form-control" readonly />
                                                                <?php } else {
                                                                    echo '<span>-</span>';
                                                                } ?>

                                                            </td>
                                                            <td>
                                                                <?php if (in_array('no', $payment_status)) { ?>
                                                                    <input type="text" onkeypress="return numbersOnlyValidation(event)" min="0" onchange="addPayableFineAmountToDataObject(this,'fine_amount')" class=" form-control fine_amount" placeholder="Enter the amount" readonly />
                                                                <?php } else {
                                                                    echo '<span>-</span>';
                                                                } ?>
                                                            </td>
                                                            <td>

                                                                <?php

                                                                if ($value['hasScholarship'] == 'yes') {
                                                                ?>
                                                                    <span class="text-muted"><?= $value['scholarship_discount'] != 0 ? 'Scholarship' : '' ?></span><br>
                                                                    <label class="text-dark" style="font-style: italic; font-size: 9px;">
                                                                        <!-- <?php
                                                                                foreach ($scholarship_types as $s_type) {
                                                                                    // var_dump($s_type);
                                                                                    if ($s_type['id'] == $value['scholarship_type']) {
                                                                                        echo $s_type['scholarshiptype_name'];
                                                                                    }
                                                                                }
                                                                                ?> -->
                                                                        -
                                                                    </label>
                                                                    <?php
                                                                } else {

                                                                    if (in_array('no', $payment_status)) { ?>
                                                                        <select style="height:auto" onchange="add_table_discount_column(this)" class="custom-select form-control <?= $value['scholarship_discount'] == 0 ? 'deduction_type' : '' ?>" readonly>
                                                                            <option value="" selected>None</option>
                                                                            <option value="discount">Discount</option>
                                                                            <option value="scholarship" <?= $value['scholarship_discount'] != 0 ? 'selected' : '' ?>>Scholarship</option>
                                                                        </select>
                                                                    <?php
                                                                    } else {
                                                                    ?>
                                                                        <span class="text-muted"><?= $value['scholarship_discount'] != 0 ? 'Scholarship' : '' ?></span><br>
                                                                        <label class="text-dark" style="font-style: italic; font-size: 9px;">
                                                                            <?php foreach ($scholarship_types as $s_type) {
                                                                                // var_dump($s_type);
                                                                                if ($s_type['id'] == $value['scholarship_type']) {
                                                                                    echo $s_type['scholarshiptype_name'];
                                                                                }
                                                                            }
                                                                            ?>
                                                                        </label>
                                                                <?php
                                                                    }
                                                                } ?>

                                                            </td>
                                                            <?php
                                                            if ($value['hasScholarship'] == 'yes') {

                                                            ?>
                                                                <td style="width: 195px;">
                                                                    <!-- <input type="text" value="<?= $value['scholarship_amount'] ?>" min="0" class="form-control" placeholder="Enter the amount" class="form-control" readonly /> -->

                                                                    <input type="text" value="<?= $value['scholarship_amount'] ?>" onkeypress="return numbersOnlyValidation(event)" min="0" onkeyup="deductAmountFromTotalFee(this)" class="dynamic_discount form-control" placeholder="Enter the amount" class="form-control" readonly />
                                                                </td>
                                                            <?php
                                                            } else {
                                                            ?>
                                                                <td style="width: 195px;" class="dynamic-td">

                                                                </td>
                                                            <?php
                                                            }
                                                            ?>

                                                            <td>
                                                                <?php if ($value['sop_id']) {
                                                                    $fee_names = $value['fee_type'] . ' - ' . $value['fee_name'];
                                                                    echo '<i class="fa fa-eye" onClick="fetchEachFeeTrasnsactions(\'' . $fee_names . '\',' . $value['sop_id'] . ',' . $value['fee_amount'] . ')" style="color:#032da1;cursor:pointer"
                                                            aria-hidden="true"></i>';
                                                                } else {
                                                                    echo '<i class="fa fa-eye" aria-hidden="true"></i>';
                                                                } ?>

                                                            </td>
                                                        </tr>
                                                <?php
                                                    }
                                                }
                                                ?>

                                                <?php
                                                // dd($table_unpaid_fees);
                                                foreach ($table_unpaid_fees as $key => $value) {
                                                    // echo '<pre>';
                                                    // var_dump($value['is_half_fee']);
                                                    $paid_status = $value['fee_completed'] == 'no' ? TRUE : FALSE;
                                                    // echo '<pre>';
                                                    // print_r($value['hasScholarship']);


                                                    $totalFeeAmount = 0.0;
                                                    $totalPendingAmount = 0.0;
                                                    if (isset($value['is_half_fee']) && $value['is_half_fee'] == 'yes') {
                                                        $totalFeeAmount = number_format((float)$value['fee_amount'], 2, '.', '') / 2;

                                                        if ($totalFeeAmount < $value['pending_amount']) {
                                                            $totalPendingAmount = $totalFeeAmount;
                                                        } else {
                                                            $totalPendingAmount = number_format((float)$value['pending_amount'], 2, '.', '');
                                                        }
                                                    } else {
                                                        $totalFeeAmount = number_format((float)$value['fee_amount'], 2, '.', '');
                                                        $totalPendingAmount = number_format((float)$value['pending_amount'], 2, '.', '');
                                                    }

                                                    if ($value['hasScholarship'] == 'yes') {
                                                        if (isset($value['is_half_fee']) && $value['is_half_fee'] == 'yes') {
                                                            $discount = ((float)$value['scholarship_discount'] / 100) * $totalFeeAmount;
                                                            $totalFeeAmount = $totalFeeAmount - $discount;
                                                        } else {
                                                            $totalFeeAmount = number_format($totalFeeAmount  - (float)$value['scholarship_amount'], 2, '.', '');
                                                        }

                                                        // echo 'Scholarship Logic';
                                                        // echo 'Fee Amount = ' . $totalFeeAmount . ' Pending Amount = ' . $totalPendingAmount;
                                                        if ($totalFeeAmount < $totalPendingAmount) {
                                                            $totalPendingAmount = $totalFeeAmount;
                                                        } else {
                                                            $totalPendingAmount = number_format((float)$value['pending_amount'], 2, '.', '');
                                                        }
                                                    }

                                                ?>
                                                    <tr>
                                                        <td>
                                                            <?php if ($value['fee_completed'] == 'no') { ?>
                                                                <!-- <?= $value['scholarship_amount'] ?> -->

                                                                <input type="checkbox" onchange="toggleCheckbox(this,<?= $value['course_fee_id'] ?>,<?= $totalFeeAmount ?>,<?= $key + 1 ?>, <?= $value['scholarship_amount'] ?>, <?= $value['scholarship_type'] ?>)" class="checkbox">
                                                                <span style="display:none" class="sop_id"><?= $value['course_fee_id'] ?></span>
                                                                <!-- <span style="display:none" class="fee_total_amount"><?= isset($value['is_half_fee']) && $value['is_half_fee'] == 'yes' ? $value['fee_amount'] / 2 :  $value['fee_amount'] ?></span> -->
                                                                <span style="display:none" class="fee_total_amount"><?= $totalFeeAmount ?></span>
                                                                <span class="row_index" style="display:none"><?= $key + 1 ?></span>

                                                            <?php } else { ?>
                                                                <i class="fa fa-check" style="color:green" aria-hidden="true"></i>
                                                            <?php } ?>

                                                        </td>
                                                        <td class="text-left">
                                                            <?php
                                                            $date = explode(' ', $value['due_date']);
                                                            echo $date[0];
                                                            ?>
                                                        </td>
                                                        <td class="row_fee_name text-left">
                                                            <?= $value['fee_name']  ?>
                                                            <small>(<?= $value['fee_type']  ?>)</small>
                                                        </td>
                                                        <td>
                                                            <?= $totalFeeAmount ?>
                                                            <!-- <?= isset($value['is_half_fee']) && $value['is_half_fee'] == 'yes' ? number_format((float)$value['fee_amount'], 2, '.', '') / 2 :  number_format((float)$value['fee_amount'], 2, '.', '');  ?> -->
                                                        </td>

                                                        <td class="row_fee_amount">
                                                            <?= $totalPendingAmount ?>
                                                        </td>
                                                        <td><?= number_format((float)$value['fine_amount'], 2, '.', '');  ?>
                                                        </td>
                                                        <td>
                                                            <?php if ($paid_status) { ?>
                                                                <input type="text" onkeypress="return numbersOnlyValidation(event)" min="0" onchange="addPayableFineAmountToDataObject(this,'payable_amount')" class=" form-control payable_amount" placeholder="Enter the amount" class="form-control" />
                                                            <?php } else {
                                                                echo '<span>-</span>';
                                                            } ?>

                                                        </td>
                                                        <td>
                                                            <?php if ($paid_status) { ?>
                                                                <input type="text" onkeypress="return numbersOnlyValidation(event)" min="0" onchange="addPayableFineAmountToDataObject(this,'fine_amount')" class=" form-control fine_amount" placeholder="Enter the amount" />
                                                            <?php } else {
                                                                echo '<span>-</span>';
                                                            } ?>
                                                        </td>
                                                        <td>

                                                            <?php

                                                            if ($value['hasScholarship'] == 'yes') {
                                                            ?>
                                                                <span class="text-muted"><?= $value['scholarship_discount'] != 0 ? 'Scholarship' : '' ?></span><br>
                                                                <label class="text-dark" style="font-style: italic; font-size: 9px;">
                                                                    <?php
                                                                    foreach ($scholarship_types as $s_type) {
                                                                        // var_dump($s_type);
                                                                        if ($s_type['id'] == $value['scholarship_type']) {
                                                                            echo $s_type['scholarshiptype_name'];
                                                                        }
                                                                    }
                                                                    ?>
                                                                </label>
                                                                <?php
                                                            } else {

                                                                if ($paid_status) { ?>
                                                                    <select style="height:auto" onchange="add_table_discount_column(this)" class="custom-select form-control <?= $value['scholarship_discount'] == 0 ? 'deduction_type' : '' ?>" <?= $value['scholarship_discount'] != 0 ? 'readonly' : '' ?>>
                                                                        <option value="" selected>None</option>
                                                                        <option value="discount">Discount</option>
                                                                        <option value="scholarship" <?= $value['scholarship_discount'] != 0 ? 'selected' : '' ?>>Scholarship</option>
                                                                    </select>
                                                                <?php
                                                                } else {
                                                                ?>
                                                                    <span class="text-muted"><?= $value['scholarship_discount'] != 0 ? 'Scholarship' : '' ?></span><br>
                                                                    <label class="text-dark" style="font-style: italic; font-size: 9px;"><?php foreach ($scholarship_types as $s_type) {
                                                                                                                                                // var_dump($s_type);
                                                                                                                                                if ($s_type['id'] == $value['scholarship_type']) {
                                                                                                                                                    echo $s_type['scholarshiptype_name'];
                                                                                                                                                }
                                                                                                                                            }
                                                                                                                                            ?>
                                                                    </label>
                                                            <?php
                                                                }
                                                            } ?>

                                                        </td>
                                                        <?php
                                                        if ($value['hasScholarship'] == 'yes') {

                                                        ?>
                                                            <td style="width: 195px;">
                                                                <!-- <input type="text" value="<?= $value['scholarship_amount'] ?>" min="0" class="form-control" placeholder="Enter the amount" class="form-control" readonly /> -->

                                                                <input type="text" value="<?= $value['scholarship_amount'] ?>" onkeypress="return numbersOnlyValidation(event)" min="0" onkeyup="deductAmountFromTotalFee(this)" class="dynamic_discount form-control" placeholder="Enter the amount" class="form-control" readonly />
                                                            </td>
                                                        <?php
                                                        } else {
                                                        ?>
                                                            <td style="width: 195px;" class="dynamic-td">

                                                            </td>
                                                        <?php
                                                        }
                                                        ?>

                                                        <td>
                                                            <?php if ($value['sop_id']) {
                                                                $fee_names = $value['fee_type'] . ' - ' . $value['fee_name'];
                                                                echo '<i class="fa fa-eye" onClick="fetchEachFeeTrasnsactions(\'' . $fee_names . '\',' . $value['sop_id'] . ',' . $value['fee_amount'] . ')" style="color:#032da1;cursor:pointer"
                                                        aria-hidden="true"></i>';
                                                            } else {
                                                                echo '<i class="fa fa-eye" aria-hidden="true"></i>';
                                                            } ?>

                                                        </td>
                                                    </tr>
                                                <?php } ?>
                                            </tbody>
                                            <tfoot>
                                                <tr>
                                                    <th></th>
                                                    <th></th>
                                                    <th></th>
                                                    <th></th>
                                                    <th></th>
                                                    <th></th>
                                                    <th></th>
                                                    <th></th>
                                                    <th class="total_th">
                                                        <?php if (count($table_unpaid_fees)) { ?>
                                                            Total Fees : <span id="total_amount_span" class="ml-2"></span>
                                                            <a href="javascript:void(0)" class="ml-2 btn table-fee-btn pay-btn btn-sm" onClick="launchModal()">Pay Now</a>
                                                            <!-- <a href="javascript:void(0)" class="ml-2 btn table-fee-btn pay-btn btn-sm" onClick="submitTableFees(this)">Pay Now</a> -->
                                                            <i style="display:none" class="ml-2 fa fa-spinner fa-spin secy-loads icon-spinne-ref"></i>
                                                            <span class="table_flag_err" style="color:red"></span>
                                                        <?php } ?>


                                                    </th>
                                                    <th id="pay_table_fee_th">

                                                    </th>
                                                    <th></th>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>
                                    <hr>
                                </div>
                                <!-- // NOT PAID INSTALLMENTS -->
                                <?php
                                // echo $school_info['batch_id'] ." => ". $selectedBatch;
                                if ($school_info['batch_id'] == $selectedBatch) {

                                    // dd($table_due_fees);
                                    $payment_status = array();
                                    foreach ($table_due_fees as $tdf_key => $tdf) {
                                        array_push($payment_status, $tdf['fee_completed']);
                                    }

                                    if (in_array('no', $payment_status)) {


                                ?>

                                <?php
                                    }
                                }

                                ?>



                            </div>
                        </div>
                    </div>

                    <!-- admin template section end -->
    </main>
    <!--End right-top side-->

</div>

<!-- Table Payments -->

<div class="modal fade fee-modal" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header fee-modal-header">
                <h5 class="modal-title fee-modal-title" id="exampleModalCenterTitle">
                    Fee Payment
                </h5>
            </div>

            <div class="modal-body fee-modal-body">
                <div class="form-group pb-0">
                    <label for="disabledSelect" class="fee-modal-select-label">Payment Type</label>
                    <select class="custom-select" id="selectBox" onchange="changeFunc();">
                        <option selected value="">Select type of payment</option>
                        <option value="cash">Cash</option>
                        <option value="bank-transfer">Bank Transfer</option>
                    </select>
                </div>
                <div class="form-group" id="textboxes" style="display: none">
                    <label for="textboxes" class="fee-modal-select-label">Transaction ID</label>
                    <input name="dd_number" id="bank_transaction" onkeypress="return AlphaNumericValid(event)" placeholder="Type here" class="form-control" type="text">
                </div>
                <span id="bank_err" style="display:none;color:red;font-size: 14px;"></span>
            </div>

            <!-- Image loader -->
            <div id='loader' style="display:none;">
                <div class=" text-center justify-content-center" role="document">
                    <span class="fa fa-spinner fa-spin fa-3x"></span>
                </div>
            </div>
            <!-- Image loader -->

            <div class="modal-footer fee-modal-footer">
                <button type="button" class="btn fee-add-btn pay_btn" id="paybtn" onClick="submitTableFees(this)">
                    Pay
                </button>
                <i style="display:none" class="ml-2 submit-spinner fa fa-spinner fa-spin secy-loads"></i>
                <button type="button" data-dismiss="modal" class="btn fee-cancel-btn">Cancel</button>
            </div>
        </div>
    </div>
</div>

<!-- Modal -->
<div class="modal fade" id="EachFeeTransaction" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered" style="max-width : 90%" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="EFT-title">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="">
                    <table class="table eft-table table-bordered">
                        <thead>
                            <tr>
                                <th>s_no</th>
                                <th>Paid Amt</th>
                                <th>Pending Amt</th>
                                <th>Deduction Type</th>
                                <th>Deductiom Amt</th>
                                <th>Fine Amt</th>
                                <th>Payment Via</th>
                                <th>Update by</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody class="EFT-tbody">

                        </tbody>
                    </table>
                </div>

                <div class="err-eft-msgs">
                    <div class="eft-success eft-alerts alert alert-success" style="display:none" role="alert">
                        Transaction has been reverted successfully
                    </div>
                    <div class="eft-danger eft-alerts alert alert-danger" style="display:none" role="alert">
                        Transaction could not be reverted, Please try again!
                    </div>
                </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">Save changes</button>
            </div> -->
        </div>
    </div>
</div>



<script type="text/javascript">
    let table_flag = true;
    let total = 0;
    let data_to_store = [];

    const revertEft = function(ele, sopId, install_sno) {
        let isAllowed = confirm("Are you sure to revert this payment?");
        // let isAllowed = 1;
        $('.eft-alerts').hide();
        if (isAllowed) {
            $.ajax({
                url: '<?php echo base_url() ?>' + 'admin/ajax_erase_fee_installment',
                data: {
                    sopId,
                    install_sno
                },
                type: 'POST',
                async: false,
                success: function(data) {
                    $(ele).tooltip('hide')

                    if (data == 'success') {
                        $(ele).parent().parent().remove();
                        $('.eft-success').show();
                    } else if (data == 'sfot-record-missing') {
                        $('.eft-danger').show();
                        $('.eft-danger').text(
                            'Payment was deleted from students_online_payments, the its relative record is not found in student_online_fee_transaction.'
                        );
                    } else if (data == 'revert-backup-failed') {
                        $('.eft-danger').show();
                        $('.eft-danger').text(
                            'Payment was deleted from SOP, but taking the backup from student_online_fee_transaction is failed, and so deleting the record from student_online_fee_transaction is not done.'
                        );
                    } else if (data == 'trans-failed') {
                        $('.eft-danger').show();
                        $('.eft-danger').text(
                            'Payment was deleted from SOP, the revert is saved in student_fee_reverts table but record from student_online_fee_transaction, is not deleted.'
                        );
                    } else {
                        $('.eft-danger').show();
                    }
                }
            });
        }
        // console.log(isAllowed);
        // console.log(sopId, install_sno);
    }

    $('#EachFeeTransaction').on('hidden.bs.modal', function() {
        location.reload();
    })

    const fetchEachFeeTrasnsactions = function(feeName, sopId, feeAmount) {
        $('#EFT-title').html(feeName + '<div style="font-size : 17px;font-weight:600">Fee Amount : ' + feeAmount +
            '</div>');
        $('.EFT-tbody').empty();
        $.ajax({
            url: '<?php echo base_url() ?>' + 'admin/ajax_fetch_each_transac_details',
            data: {
                sopId
            },
            type: 'POST',
            async: false,
            success: function(data) {
                if (data != '') {
                    data = JSON.parse(data);
                    $('.EFT-tbody').append(data);
                    $('#EachFeeTransaction').modal({
                        keyboard: false,
                        backdrop: 'static'
                    });
                    $('[data-toggle="tooltip"]').tooltip();
                }

            }
        });



    }

    const addPayableFineAmountToDataObject = function(item, type) {

        if (item.value == '') {
            $('.fine_amount').val(null);
            $('.deduction_type').val(null);
            $('.dynamic-td').empty();
            $('#total_amount_span').text(0);
            let thisrowCheck = $(item).parent().siblings().children('.checkbox');
            let duerowCheck = $(item).parent().siblings().children('.dueCheckbox');
            let index = $(item).parent().siblings().children('.row_index').text();

            if (data_to_store.length > 0) {
                data_to_store = data_to_store.filter((item, i) => {
                    if (item.index !== index)
                        return item;
                })
            }

            $('.checkbox').each((i, ele) => {
                let deduction_type = $(ele).parent().siblings().children('.deduction_type').val();
                let deduction_amount = 0;

                if (deduction_type)
                    deduction_amount = parseInt($(ele).parent().siblings().children('.dynamic_discount').val());

                let ele_amount = parseInt($(ele).parent().siblings().children('.payable_amount').val());
                let fine_amount = parseInt($(ele).parent().siblings().children('.fine_amount').val());
                let sum_total_fees = 0;;
                if (ele.checked) {
                    deduction_amount = deduction_amount ? deduction_amount : 0;
                    fine_amount = fine_amount ? fine_amount : 0;
                    ele_amount = ele_amount ? ele_amount : 0;
                    sum_total_fees += (ele_amount - deduction_amount) + fine_amount;
                    total = sum_total_fees;
                }
            });

            $('.dueCheckbox').each((i, ele) => {
                let deduction_type = $(ele).parent().siblings().children('.deduction_type').val();
                let deduction_amount = 0;

                if (deduction_type)
                    deduction_amount = parseInt($(ele).parent().siblings().children('.dynamic_discount').val());

                let ele_amount = parseInt($(ele).parent().siblings().children('.payable_amount').val());
                let fine_amount = parseInt($(ele).parent().siblings().children('.fine_amount').val());
                let sum_total_fees = 0;;
                if (ele.checked) {
                    deduction_amount = deduction_amount ? deduction_amount : 0;
                    fine_amount = fine_amount ? fine_amount : 0;
                    ele_amount = ele_amount ? ele_amount : 0;
                    sum_total_fees += (ele_amount - deduction_amount) + fine_amount;
                    total = sum_total_fees;
                }
            });

            if ($(thisrowCheck).is(":checked") && type != 'fine_amount') {
                $(thisrowCheck).prop('checked', false);
                return;
            }

            if ($(duerowCheck).is(":checked") && type != 'fine_amount') {
                $(duerowCheck).prop('checked', false);
                return;
            }


        }

        let itemValue = item.value ? parseInt(item.value) : 0;
        let index = $(item).parent().siblings().children('.row_index').text();

        if ($(item).siblings('.item_err').length > 0) {
            $(item).siblings('.item_err').remove();
        }

        let itemRow = $(item).parent();
        let rowAmount = $(itemRow).siblings('.row_fee_amount').text();

        let sum_total_fees = 0;

        if ((parseInt(itemValue) > parseInt(rowAmount)) && type != 'fine_amount') {
            $(item).after(
                '<span class="item_err" style="color:red">Please enter amount which is less than pending amount (' +
                rowAmount + ')</span>');
            table_flag = false;
            return;
        } else {
            table_flag = true;
            $(item).siblings('.item_err').remove();
        }

        if (data_to_store.length > 0) {
            $.each(data_to_store, function(key, ele) {
                ele.total = total;
                if (index == ele.index) {
                    // ele.payable_amount = parseInt(itemValue);
                    ele[type] = parseInt(itemValue);
                }
            });
        }

        $('.checkbox').each((i, ele) => {
            let deduction_type = $(ele).parent().siblings().children('.deduction_type').val();
            let deduction_amount = 0;

            if (deduction_type)
                deduction_amount = parseInt($(ele).parent().siblings().children('.dynamic_discount').val());

            let ele_amount = parseInt($(ele).parent().siblings().children('.payable_amount').val());
            let fine_amount = parseInt($(ele).parent().siblings().children('.fine_amount').val());

            if (ele.checked) {
                deduction_amount = deduction_amount ? deduction_amount : 0;
                fine_amount = fine_amount ? fine_amount : 0;
                sum_total_fees += (ele_amount - deduction_amount) + fine_amount;
                total = sum_total_fees;
                $('#total_amount_span').text(sum_total_fees);
            }
        });

        $('.dueCheckbox').each((i, ele) => {
            let deduction_type = $(ele).parent().siblings().children('.deduction_type').val();
            let deduction_amount = 0;

            if (deduction_type)
                deduction_amount = parseInt($(ele).parent().siblings().children('.dynamic_discount').val());

            let ele_amount = parseInt($(ele).parent().siblings().children('.payable_amount').val());
            let fine_amount = parseInt($(ele).parent().siblings().children('.fine_amount').val());

            if (ele.checked) {
                deduction_amount = deduction_amount ? deduction_amount : 0;
                fine_amount = fine_amount ? fine_amount : 0;
                sum_total_fees += (ele_amount - deduction_amount) + fine_amount;
                total = sum_total_fees;
                $('#total_amount_span_due').text(sum_total_fees);
            }
        });

    }

    const add_table_discount_column = (ele) => {

        let elementTd = $(ele).parent();

        if ($('.each_dd_err').length > 0) {
            $('.each_dd_err').remove();
        }

        if ($(elementTd).siblings('.dynamic-td').children('.dynamic_discount').length > 0) {
            $(elementTd).siblings('.dynamic-td').children('.dynamic_discount').remove();
        }

        let index = $(ele).parent().siblings().children('.row_index').text();

        if (ele.value == 'discount' || ele.value == 'scholarship') {
            let dynamicTd = $(elementTd).siblings('.dynamic-td');
            $(dynamicTd).append(
                '<input type="text" onkeypress="return numbersOnlyValidation(event)" min="0" onkeyup="deductAmountFromTotalFee(this)" class="dynamic_discount form-control" placeholder="Enter the amount" class="form-control" />'
            );

            if (data_to_store.length > 0) {
                $.each(data_to_store, function(key, item) {
                    if (index == item.index) {
                        item.deduction_type = ele.value;
                    }
                });
            }
        } else {
            if (data_to_store.length > 0) {
                $.each(data_to_store, function(key, item) {
                    if (index == item.index) {
                        item.deduction_type = ele.value;
                    }
                });
            }
        }
    }

    function numbersOnlyValidation(e) {
        var keyCode = e.keyCode || e.which;

        //Regex for Valid Characters i.e. Alphabets and Numbers.
        var regex = /^[0-9]+$/;

        //Validate TextBox value against the Regex.
        var isValid = regex.test(String.fromCharCode(keyCode));

        return isValid;
    }

    const deductAmountFromTotalFee = (item) => {

        let itemValue = item.value ? parseInt(item.value) : 0;
        if ($(item).siblings('.item_err').length > 0) {
            $(item).siblings('.item_err').remove();
        }

        let complete_sum = total;
        let sum = 0;
        let itemRow = $(item).parent();
        let rowAmount = $(itemRow).siblings().children('.payable_amount').val();
        let index = $(item).parent().siblings().children('.row_index').text();



        if (parseInt(itemValue) > parseInt(rowAmount)) {
            $(item).after(
                '<span class="item_err" style="color:red">Please enter ammount which is less than the current fee (' +
                rowAmount + ')</span>');
            table_flag = false;
            return false;
        } else {
            table_flag = true;
            $(item).siblings('.item_err').remove();
        }

        let sum_total_fees = 0;
        let sum_total_due_fees = 0;
        $('.checkbox').each((i, ele) => {
            let deduction_type = $(ele).parent().siblings().children('.deduction_type').val();
            let deduction_amount = 0;
            let fine_amount = parseInt($(ele).parent().siblings().children('.fine_amount').val());
            if (deduction_type)
                deduction_amount = parseInt($(ele).parent().siblings().children('.dynamic_discount').val());

            let ele_amount = parseInt($(ele).parent().siblings().children('.payable_amount').val());
            // console.log(ele_amount + ' => ele amount');
            fine_amount = fine_amount ? fine_amount : 0;
            deduction_amount = deduction_amount ? deduction_amount : 0;

            sum_total_fees += (ele_amount - deduction_amount) + fine_amount;
            // console.log(sum_total_fees + ' => sum_total_fees');
            if (sum_total_fees < 0) {
                $(item).after(
                    '<span class="item_err" style="color:red">Please enter a valid amount such that the difference is not a negative number</span>'
                );
                $('#total_amount_span').text('0.00');
                table_flag = false;
                return false;
            } else {
                table_flag = true;
            }

            if (ele.checked) {
                total = sum_total_fees;
                $('#total_amount_span').text(sum_total_fees.toFixed(2));
            }
        });

        $('.dueCheckbox').each((i, ele) => {
            let deduction_type = $(ele).parent().siblings().children('.deduction_type').val();
            let deduction_amount = 0;
            let fine_amount = parseInt($(ele).parent().siblings().children('.fine_amount').val());
            if (deduction_type)
                deduction_amount = parseInt($(ele).parent().siblings().children('.dynamic_discount').val());

            let ele_amount = parseInt($(ele).parent().siblings().children('.payable_amount').val()) || 0;
            // console.log(ele_amount + ' => ele amount');
            fine_amount = fine_amount ? parseInt(fine_amount) : 0;
            deduction_amount = deduction_amount ? parseInt(deduction_amount) : 0;

            sum_total_due_fees = sum_total_due_fees + (ele_amount - deduction_amount + fine_amount);
            console.log('<======== ' + sum_total_due_fees + '============= ' + ele_amount + ' ================ ' + deduction_amount + ' ====================== ' + fine_amount);
            // console.log(sum_total_fees + ' => sum_total_fees');
            if (sum_total_due_fees < 0) {
                $(item).after(
                    '<span class="item_err" style="color:red">Please enter a valid amount such that the difference is not a negative number</span>'
                );
                $('#total_amount_span_due').text('0.00');
                table_flag = false;
                return false;
            } else {
                table_flag = true;
            }

            if (ele.checked) {
                total = sum_total_due_fees;
                // console.log(total + ' ==================================> Total');
                $('#total_amount_span_due').text(sum_total_due_fees.toFixed(2));
            }
        })

        if (data_to_store.length > 0) {
            $.each(data_to_store, function(key, ele) {
                ele.total = total;
                if (index == ele.index) {
                    ele.deduction_amount = parseInt(itemValue);
                }
            });
        }

        // console.log(data_to_store);
    }

    const toggleCheckbox = (ele, courseFeeId, fee_total_amount, index) => {
        console.log(courseFeeId);
        console.log(fee_total_amount);

        if ($('.paybale_err').length > 0) {
            $('.paybale_err').remove();
        }

        $('.table_flag_err').empty();

        let deduction_type = $(ele).parent().siblings().children('.deduction_type').val();
        let deduction_amount = 0;

        let payable_amount = parseInt($(ele).parent().siblings().children('.payable_amount').val());
        payable_amount = payable_amount ? payable_amount : 0;

        // if (!payable_amount) {
        //     $(ele).parent().siblings().children('.payable_amount').after(
        //         '<span class="paybale_err" style="color:red">Please enter an amount before selecting</span>');
        //     $(ele).prop('checked', false);
        //     return;
        // }

        if (!table_flag) {
            $('.table_flag_err').text('Please provide valid data in table and try again');
            $(ele).prop('checked', false);
            return false;
        }

        let fine_amount = parseInt($(ele).parent().siblings().children('.fine_amount').val());
        fine_amount = fine_amount ? fine_amount : 0;


        if (deduction_type)
            deduction_amount = parseInt($(ele).parent().siblings().children('.dynamic_discount').val());

        let ele_amount;

        if (!payable_amount) {
            let pending_fee = $(ele).parent().siblings('.row_fee_amount').text();
            ele_amount = payable_amount = parseInt(pending_fee.trim());

            $(ele).parent().siblings().children('.payable_amount').val(payable_amount);
        }

        ele_amount = payable_amount;



        if (ele.checked) {

            deduction_amount = deduction_amount ? deduction_amount : 0;
            let ele_sum = (ele_amount - deduction_amount) + fine_amount;
            total += ele_sum;

            if (courseFeeId.toString().includes(",")) {
                var courseIdArray = courseFeeId.split(',');
                var feeAmounts = <?= json_encode($course_fee_amount) ?>;
                console.log(courseIdArray);
                console.log(feeAmounts);
                var payableAmt = payable_amount;

                for (var i = 0; i < feeAmounts.length; i++) {

                    var courseFeeId = courseIdArray[i];
                    var fee_total_amount = feeAmounts[i];
                    var feePayableAmt = 0;

                    if (payableAmt >= fee_total_amount) {
                        feePayableAmt = feeAmounts[i];

                    } else {
                        feePayableAmt = payableAmt - fee_total_amount;
                    }
                    payableAmt = payableAmt - feePayableAmt;

                    data_to_store.push({
                        index,
                        courseFeeId,
                        fee_total_amount,
                        deduction_type,
                        deduction_amount,
                        feePayableAmt,
                        fine_amount,
                        payableAmt
                    })
                }

            } else {
                data_to_store.push({
                    index,
                    courseFeeId,
                    fee_total_amount,
                    deduction_type,
                    deduction_amount,
                    payable_amount,
                    fine_amount
                })
            }



            $('#total_amount_span').text(total.toFixed(2));

        } else {

            if (data_to_store.length > 0) {
                data_to_store = data_to_store.filter((item, i) => {
                    if (item.index !== index)
                        return item;
                })
            }
            let ele_diff = (ele_amount - deduction_amount) + fine_amount;
            total -= ele_diff;
            $('#total_amount_span').text(total.toFixed(2));
            $(ele).parent().siblings().children('.deduction_type').val(null);
            $(ele).parent().siblings().children('.fine_amount').val(null);
            $(ele).parent().siblings().children('.payable_amount').val(null);
            $(ele).parent().siblings('.dynamic-td').empty();

        }
    }


    $("#main_check").change(function() {

        $('.table_flag_err').empty();

        if ($('.paybale_err').length > 0) {
            $('.paybale_err').remove();
        }

        if ($(this).is(":checked")) {
            $('.checkbox').prop('checked', true);
        } else {
            $('.checkbox').prop('checked', false);
        }


        data_to_store = [];
        let sum_total_fees = 0;
        let payable_flag = false;
        $('.checkbox').each((i, ele) => {
            let deduction_type = $(ele).parent().siblings().children('.deduction_type').val();
            let deduction_amount = 0;

            let payable_amount = parseInt($(ele).parent().siblings().children('.payable_amount').val());
            payable_amount = payable_amount ? payable_amount : 0;



            if (!table_flag) {

                $('.table_flag_err').text('Please provide valid data in table and try again');
                $(ele).prop('checked', false);
                return false;
            }

            let fine_amount = parseInt($(ele).parent().siblings().children('.fine_amount').val());
            fine_amount = fine_amount ? fine_amount : 0;

            if (deduction_type)
                deduction_amount = parseInt($(ele).parent().siblings().children('.dynamic_discount').val());

            let ele_amount;

            if (!payable_amount) {
                let pending_fee = $(ele).parent().siblings('.row_fee_amount').text();
                ele_amount = payable_amount = parseInt(pending_fee.trim());

                $(ele).parent().siblings().children('.payable_amount').val(payable_amount);
            }

            sum_total_fees += (ele_amount - deduction_amount) + fine_amount;
            total = sum_total_fees;
            $('#total_amount_span').text(sum_total_fees.toFixed(2));

            if (ele.checked) {
                courseFeeId = $(ele).siblings('.sop_id').text();
                fee_total_amount = $(ele).siblings('.fee_total_amount').text();

                data_to_store.push({
                    index: i + 1,
                    courseFeeId,
                    fee_total_amount,
                    deduction_type,
                    deduction_amount,
                    fine_amount,
                    payable_amount
                })
                console.log(data_to_store);

            }
        })

        if (!this.checked) {

            $('.checkbox').prop('checked', false);
            data_to_store = [];
            total = 0;
            $('.deduction_type').val(null);
            $('.fine_amount').val(null);
            $('.payable_amount').val(null);
            $('.dynamic-td').empty();
            $('#total_amount_span').text('0.00');
        }

    });

    const launchModal = () => {

        if ($('.fee-msg-err').length > 0) {
            $('.fee-msg-err').remove();
        }
        if ($('.each_dd_err').length > 0) {
            $('.each_dd_err').remove();
        }


        if ($('.dynamic_discount').length > 0) {
            let returnFlag = false;
            $('.dynamic_discount').each((i, ele) => {
                if (!ele.value) {
                    $(ele).after('<span style="color:red" class="each_dd_err">Please enter an amount</span>');
                    returnFlag = true;
                    return;

                }
            });

            if (returnFlag) {
                return false;
            }
        }

        if (data_to_store.length == 0) {
            $('.icon-spinne-ref').after(
                '<div><span style="color:red;font-size:14px" class="fee-msg-err">Please select atleast 1 fee to pay</span></div>'
            );
        } else {
            $('#exampleModalCenter').modal('show');
        }
    }

    const submitTableFees = (ele) => {
        // console.log(ele.id);
        let selectBox = $('#selectBox'),
            banktransaction = '';

        if ($('#bank_err').length > 0)
            $('#bank_err').hide();

        if ($('#pt_err').length > 0)
            $('#pt_err').hide();

        if (!$(selectBox).find(":selected").val()) {
            $(selectBox).after('<div id="pt_err" style="color:red">Please select one payment type</div>')
            return;
        }

        if ($('#bank_transaction').is(":visible") > 0 && !$('#bank_transaction').val()) {
            $('#bank_err').text('Please enter a bank-transaction id');
            $('#bank_err').show();
            return;
        }

        if (data_to_store.length == 0) {
            $('#exampleModalCenter').modal('hide');
            $('.icon-spinne-ref').after(
                '<div><span style="color:red;font-size:14px" class="fee-msg-err">Please select atleaset 1 fee to pay</span></div>'
            );
        }

        let jsonText = JSON.stringify(data_to_store);
        let payment_type = $(selectBox).find(":selected").val();
        let bank_transaction_id = $('#bank_transaction').val() ? $('#bank_transaction').val() : null;

        // $('.fee-add-btn').toggle();
        // $('.submit-spinner').toggle();

        // console.log(jsonText);

        $.ajax({
            url: '<?php echo base_url() ?>' + 'admin/ajax_pay_table_fees',
            data: {
                feeData: jsonText,
                payment_type,
                bank_transaction_id,
                student_id: <?= $student_id ?>
            },
            type: 'POST',
            async: false,
            beforeSend: function() {
                $("#loader").show();
                $('#' + ele.id).attr("disabled", true);
            },
            success: function(data) {

                // console.log(data);


                location.reload();
            }
        });


    }

    const AlphaNumericValid = (e) => {
        var keyCode = e.keyCode || e.which;

        //Regex for Valid Characters i.e. Alphabets and Numbers.
        var regex = /^[A-Za-z0-9]+$/;

        //Validate TextBox value against the Regex.
        var isValid = regex.test(String.fromCharCode(keyCode));

        return isValid;
    }

    function changeFunc() {
        if ($('#pt_err').length > 0)
            $('#pt_err').hide();

        var selectBox = document.getElementById("selectBox");
        var selectedValue = selectBox.options[selectBox.selectedIndex].value;

        if (selectedValue == "bank-transfer") {
            $('#textboxes').show();
        } else if (selectedValue == '') {
            $(selectBox).after('<div id="pt_err" style="color:red">Please select one payment type</div>')
        } else {
            $('#textboxes').hide();
        }
    }
</script>

<!-- Table Payments End -->

<script>
    $(document).ready(function() {
        let globalForm = $('.syllabus-main form')[0];
        globalForm = getFormData(globalForm);

        //table js
        $('.tbl').DataTable({

            'aLengthMenu': [
                [25, 50, 100, 200, -1],
                [25, 50, 100, 200, "All"]
            ],
            'iDisplayLength': -1,
            "order": [
                [0, "asc"]
            ]
        });

        //table js
        $('.tbl2').DataTable({
            "lengthMenu": [
                [10, 25, 50, 75, 100, "All"],
                [10, 25, 50, 75, 100, "All"]
            ],
            "order": [
                [1, "desc"]
            ]
        });

    });
</script>

<script>
    const createDynamicForm = (studentId, ele, install_key, sot_id, fee_amount, course_fee = 0, payment_info = null) => {

        $(ele).hide();
        payment_info = payment_info ? JSON.stringify(payment_info) : null;

        let LiElement = $(ele).parent().parent().parent();
        LiElement.after(() => {
            let base_url = '';
            let html = '<li>';
            html +=
                '<form id="feecollectionForm" onSubmit="return validateAmount(this,event)" action="<?= base_url() ?>admin/pay_offline_student_fees" method="post">';
            html += '<input type="hidden" name="install_key" value="' + install_key + '"/>';
            html += '<input type="hidden" name="sot_id" value="' + sot_id + '"/>';
            html += '<input type="hidden" name="course_fee_id" value="' + course_fee + '">';
            html += '<input type="hidden" name="payment_info" value=\'' + payment_info + '\'/>';
            html += '<input type="hidden" name="studentId" value="' + studentId + '"/>';
            html +=
                '<div class="mb-2 payment-type-dropdown"><label class="mb-0">Select type of payment<span style="color:red">*</span></label>';
            html +=
                '<select class="form-control" id="pType" onchange="checkForPtype(this)" name="payment_type">';
            html += '<option value="" Selected>Select type of payment</option>';
            html += '<option value="cash">Cash</option>';
            html += '<option value="bank-transfer">Bank Transfer</option>';
            html += '</select></div>';

            html += '<div><label class="mb-0">Select type of deduction</label><span style="color:red">*</span>';
            html +=
                '<select class="form-control" id="disabledSelect" disabled onChange="showDiscountBox(this,' +
                fee_amount + ')" name="deduction_type">';
            html += '<option value="" Selected>Choose type of reimbursement</option>';
            html += '<option value="none">None</option>';
            html += '<option value="discount">Discount</option>';
            html += '<option value="scholarship">Scholarship</option>';
            html += '</select></div>';
            html += '</form>';
            html += '</li>';
            return html;
        });

    }

    const checkForPtype = (ele) => {
        if ($('.dd_div').length > 0) {
            $('.dd_div').remove();
        }
        if (ele.value !== '') {
            $('#disabledSelect').prop('disabled', false);
        } else {
            if ($('#payment_btn_textbox').length > 0) {
                $('#payment_btn_textbox').remove();
            }


            $('#disabledSelect').prop('disabled', true);
        }

        if (ele.value == 'bank-transfer') {
            $(ele).after(
                '<div class="dd_div"><label class="mb-0 mt-2">DD/Cheque No..<span style="color:red">*</span></label><input type="text" id="dd_textbox" class="form-control" onkeypress="return AlphaNumericValid(event)" name="bank_transaction_id" placeholder="DD/Cheque ID" /></div>'
            );
        }
    }

    const showDiscountBox = (ele, fee) => {
        if ($('#payment_btn_textbox').length > 0)
            $('#payment_btn_textbox').remove();

        let value = ele.value;
        let html = '<div id="payment_btn_textbox">'
        html += '<input type="hidden" id="total_fee_ref" value="' + fee + '">';
        if (value == "none") {
            html += '<div class="mt-2"><input type="submit" class="btn pay-btn" value="Pay Fee"/></div>';
            html += '</div>';
            $(ele).after(html);
        } else if (value != '' && value != 'none') {
            html +=
                '<input type="text" onkeypress="return numbersOnlyValidation(event)" min="0" name="deducted_amount" id="deducted_amount" class="form-control mt-2" value="" placeholder="Enter Amount"/><div style="color:red;display:none" id="discount_amount_err"></div>';
            html += '<div class="mt-2"><input type="submit" class="btn pay-btn" value="Pay Fee"/></div>';
            html += '</div>';
            $(ele).after(html);
        } else {
            $('#payment_btn_textbox').remove();
        }

    }

    const validateAmount = (form, e) => {

        if ($('.dd_err').length > 0) {
            $('.dd_err').remove();
        }

        if ($('#dd_textbox').length > 0) {
            if (!$('#dd_textbox').val()) {

                $('#dd_textbox').after('<span class="dd_err" style="color:red">Please enter a DD/Cheque No.</span>');
                return false;
            }

        }

        if ($(form).find('select[name="deduction_type"]').val() == 'none') {
            return true;
        }

        $('#discount_amount_err').text('');
        let feeAmount = $('#total_fee_ref').val();
        let value = $('#deducted_amount').val() ? $('#deducted_amount').val() : 0;
        if (!value) {
            $('#discount_amount_err').show();
            $('#discount_amount_err').append('Please enter an amount');
            return false;
        }

        let returnValue = (parseInt(value) <= parseInt(feeAmount));

        if (!returnValue) {
            $('#discount_amount_err').show();
            $('#discount_amount_err').append('Please enter an amount which is less than fee amount(' + feeAmount + ')');
        }

        return returnValue;
    }

    const get_payment_details = function(ele, course_fee_id) {


        let payment_type_id = ele.value;
        let container = $(ele).parent().parent();

        $.ajax({
            type: 'POST',
            url: "<?php echo base_url(); ?>admin/ajax_get_fee_installments",
            data: {
                installment_type: payment_type_id,
                course_fee_id: course_fee_id,
                student_id: <?= $student_id ?>
            },
            success: function(response) {
                $(container).empty();
                if (!response) {
                    $(container).append(
                        '<p style="color:red">Could Not fetch amount, Please try again later</p>');
                } else {
                    $(container).append(response);
                }

            },
        });

    }

    const get_subject_attendance = (form, e) => {
        e.preventDefault();
        globalForm = getFormData(form);
        data = getFormData(form);

        $('#Datepicker1').datepicker('setDate', 'today');

        $.ajax({
            type: 'POST',
            url: "<?php echo base_url(); ?>admin/ajax_get_student_attendance",
            data: {
                inputs: data
            },
            success: function(data) {

                data = JSON.parse(data);

                if (data != 'failed') {
                    $('.att-row').empty();
                    $("#student-attendance").empty();
                    $('.att-row').append(data['attendance_upper']);
                    $("#student-attendance").append(data['attendance_lower']);

                } else {
                    $('.att-row').empty();
                    $("#student-attendance").empty();
                    $('.att-row').append('<span>No Attendance of this subject</span>');
                    $("#student-attendance").append('<span>No Attendance of this subject</span>');
                }

            }
        });

    }

    function getFormData(form) {
        var unindexed_array = $(form).serializeArray();
        var indexed_array = {};


        $.map(unindexed_array, function(n, i) {
            indexed_array[n['name']] = n['value'];
        });

        return indexed_array;
    }



    $(document).ready(function() {
        $('#chkParent').click(function() {
            var isChecked = $(this).prop("checked");
            $('#tbl1 tr:has(td)').find('input[type="checkbox"]').prop('checked', isChecked);
        });

        $('#tbl1 tr:has(td)').find('input[type="checkbox"]').click(function() {
            var isChecked = $(this).prop("checked");
            var isHeaderChecked = $("#chkParent").prop("checked");
            if (isChecked == false && isHeaderChecked)
                $("#chkParent").prop('checked', isChecked);
            else {
                $('#tbl1 tr:has(td)').find('input[type="checkbox"]').each(function() {
                    if ($(this).prop("checked") == false)
                        isChecked = false;
                });
                // console.log(isChecked);
                $("#chkParent").prop('checked', isChecked);
            }
        });

        $('[data-toggle="tooltip"]').tooltip()
    });


    function Popup(data, winload = false) {
        var frame1 = $('<iframe />').attr("id", "printDiv");
        frame1[0].name = "frame1";
        frame1.css({
            "position": "absolute",
            "top": "-1000000px"
        });
        $("body").append(frame1);
        var frameDoc = frame1[0].contentWindow ? frame1[0].contentWindow : frame1[0].contentDocument.document ? frame1[0]
            .contentDocument.document : frame1[0].contentDocument;
        frameDoc.document.open();
        //Create a new HTML document.
        frameDoc.document.write('<html>');
        frameDoc.document.write('<head>');
        frameDoc.document.write('<title></title>');
        frameDoc.document.write('<link rel="stylesheet" href="<?php echo base_url(); ?>assets_admin/css/invoice.css">');
        frameDoc.document.write('</head>');
        frameDoc.document.write('<body>');
        frameDoc.document.write(data);
        frameDoc.document.write('</body>');
        frameDoc.document.write('</html>');
        frameDoc.document.close();
        setTimeout(function() {
            document.getElementById('printDiv').contentWindow.focus();
            document.getElementById('printDiv').contentWindow.print();
            // frame1.remove();
            if (winload) {
                window.location.reload(true);
            }
        }, 500);


        return true;
    }



    $(document).on('click', '.download_multiple_invoice', function() {
        var invoicelist = [];

        $.each($("input[name='student_inovice_list[]']:checked"), function() {
            var item = $(this).data('transid');
            invoicelist.push(item);
        });

        if (invoicelist.length === 0) {
            alert("Please Select Recent Transactions list");
        } else {
            console.log('invoicelist = ' + invoicelist);
            $.ajax({
                url: "<?= base_url() . 'Admin/downloadAllInvoice'; ?>",
                method: "POST",
                data: {
                    inoviceids: invoicelist,
                    student_id: "<?= $student_id ?>"
                },
                success: function(response) {
                    Popup(response);
                }
            });
        }
    });
</script>