<?php if ($IsEdit && $check_lock != '') { ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong><?php echo $check_lock ?>
    </div>
<?php
    return;
}
if ($IsEdit && $IsReceipt && !empty($edit_data['main']['payment_app_id']) && smc_session()['default_setting']['edit_receipt_from_app'] == 0) {
?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong>you can not edit this receipt!
        <br>
        This receipt from application.
    </div>
<?php
    return;
}
if ($IsEdit && $IsReceipt && !empty($edit_data['main']['subscription_fees_id'])) {
?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong>you can not edit this Receipt!
        <br>
        This Receipt is related to subscription.
    </div>
<?php
    return;
}
if ($IsEdit && empty($edit_data['payments'])) {
?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong>you can not edit this <?php echo $IsReceipt ? 'Receipt' : 'Payment' ?>!
        <br>
        This <?php echo $IsReceipt ? 'receipt' : 'payment' ?> is not available.
    </div>
<?php
    return;
}
if ($is_main_transfer != 0) {
?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong>you can not edit this <?php echo $IsReceipt ? 'Receipt' : 'Payment' ?>!
        <br>
        This <?php echo $IsReceipt ? 'Receipt' : 'Payment' ?> is transfered to the main branch.
    </div>
<?php
    return;
}

$pay_rec_fields_hide = smc_session()['default_setting']['pay_rec_fields_to_hide'] != '' ? explode(",", smc_session()['default_setting']['pay_rec_fields_to_hide']) : [];
?>
<style type="text/css">
    #PayementTable thead tr th {
        color: #555;
        border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    }

    #PayementTable tbody tr td input {
        width: 100%;
        margin: 0;
        border: 1px solid rgba(0, 0, 0, 0.02);
        background-color: #f0f0f0;
    }

    #PayementTable tbody tr td {
        border: 0;
        /*padding:3px 1px;*/
        padding: 0 !important;
        position: relative;
    }

    #PayementTable tbody tr:first-child td {
        padding-top: 10px;
    }

    #PayementTable .Hint {
        position: absolute;
        font-size: 10px;
        font-weight: bold;
        height: 20px;
        line-height: 20px;
        bottom: 2px;
        right: 4px;
        color: rgb(153, 153, 153);
    }

    #PayementTable .TotalTD {
        width: auto;
        display: inline-block;
        text-align: center;
        font-size: 20px;
        text-indent: 10px;
        font-weight: bold;
    }

    #PayementTable .Disc {
        width: 50px;
    }

    #PayementTable inputX.wrong {
        border: 1px solid rgba(255, 0, 0, 0.2);
        background: rgba(255, 0, 0, 0.05);
    }

    .DropDownForForms>.dropdown-menu {
        width: 100%;
        height: 200px;
        max-height: 200px;
        overflow-y: scroll;
    }

    .DropDownForForms>.dropdown-menu {
        height: auto;
        cursor: pointer;
        overflow-y: auto;
    }

    .DropDownForForms>button {
        position: relative;
        z-index: 999;
    }

    .DropDownForForms>button>input {
        position: absolute;
        left: 5;
        top: 0;
        width: 90%;
        cursor: pointer;
        -webkit-user-select: none;
        -moz-user-select: none;
        user-select: none;
        padding: 0;
        border: 0;
        background: transparent;
    }

    .Disabled {
        cursor: default;
        opacity: 0.5;
    }

    #AdvanceValue {
        width: 102px;
        display: inline-block;
    }

    .my_tr {
        border-bottom: 1px solid rgba(0, 0, 0, 0.07);
        padding: 10px;
    }

    .wrong {
        border: 1px solid rgba(255, 0, 0, 0.2);
        background: rgba(255, 0, 0, 0.05);
    }

    .rem {
        color: #eb9220;
        cursor: pointer;
        font-weight: 700;
    }

    .balance {
        color: red;
        font-weight: 700;
    }
</style>
<script src="<?php echo THEME_PATH; ?>plugins/jquery-validation/js/jquery.validate.min.js"></script>
<form method="POST" action="" onsubmit="return false" id="PaymentForm">
    <div class="container-fluid container-fixed-lg">
        <div class="panel panel-default">
            <div class="panel-body">
                <?php echo Forms::ModalLoader('PaymentIsBusy') ?>
                <div id="paymentAlert"></div>
                <div class="">
                    <div class="">
                        <div class="">
                            <div class="invoice">
                                <div class="container-sm-height">
                                    <div class="row-sm-height">
                                        <div class="col-md-9 col-sm-height sm-no-padding">
                                            <div>
                                                <div class="input-group  col-md-8 center-margin pull-left">
                                                    <div class="sm-m-t-20">
                                                        <h2 class="font-montserrat all-caps hint-text"><?php print $title; ?></h2>
                                                    </div>
                                                </div>
                                                <div class="clearfix"></div>
                                            </div>

                                            <div class=" col-md-4">
                                                <strong>
                                                    <?php echo CommonLanguage::getMessage('account'); ?><span class="red-star">*</span>

                                                </strong>
                                                <span class="fa fa-plus-circle m-l-5 " data-toggle="modal" data-target="#customer_supplier_account_modal" style="color:#4c0870;cursor:pointer"></span>
                                                <?php if ($permissions->hasPermission($is_actual ? 'ActualLedger' : 'ledger')) { ?>
                                                    <span class="flaticon-scale15 m-l-5 openFrame  open_general_ledger " data-main="ACC/ledger<?php echo $is_actual ? '/act' : ''; ?>?is_pop=1" data-src="ACC/ledger<?php echo $is_actual ? '/act' : '' . '?is_pop=1' . (($IsEdit || $is_detail || $is_copy) ? ('/' . $edit_data['main']['Current_Account_Code'] . '') : ''); ?>" style="color:#4c0870;cursor:pointer;"></span>
                                                <?php } ?>
                                                <input class=" full-width" id="accountId" name="accountId" type="hidden" <?php echo ($IsEdit || $is_copy) && !empty($edit_data['main']['pos_customer_id']) ? 'disabled' : '' ?> <?php echo !$is_readonly || $is_collect || !empty($edit_data['main']['receipt_detail_id']) ? '' : 'readonly' ?> value="<?= ($IsEdit || $is_detail || $is_copy) ? $edit_data['main']['Account_ID'] : (isset($get_parameters['account_id']) ? $get_parameters['account_id'] : ''); ?>" data-select-name='<?= json_encode(($IsEdit || $is_detail || $is_copy) ? ($edit_data['main']['Account_Name'] . ' - ' . $edit_data['main']['Current_Account_Code']) : (isset($get_parameters['account_name']) ? ($get_parameters['account_name'] . ' - ' . $get_parameters['account_code']) : '')); ?>' />
                                            </div>
                                            <?php if (!$is_return) { ?>
                                                <div class="<?php echo $IsReceipt ? '' : 'hidden' ?> col-md-4 form-group">
                                                    <label><?php echo CommonLanguage::getMessage('road_customer') ?></label>
                                                    <input id="pos_customer" class="full-width" type="hidden" value="<?php echo ($IsEdit || $is_copy) ? (!empty($edit_data['main']['pos_customer_id']) ? $edit_data['main']['pos_customer_id'] : '') : '' ?>" data-select-name='<?= json_encode(($IsEdit || $is_copy) ? $edit_data['main']['pos_customer_name'] : '') ?>' />
                                                </div>
                                                <div class="col-md-2"><br><button class="btn btn-complete" <?php echo ($IsEdit || isset($get_parameters['account_id'])) ? '' : 'disabled' ?> id="get_inv"><?php echo CommonLanguage::getMessage('get_invoices'); ?></button></div>
                                                <?php if ($permissions->hasPermission($IsReceipt ? ($is_actual ? 'act_rec_auto_close_invoices' : 'rec_auto_close_invoices') : ($is_actual ? 'act_pay_auto_close_invoices' : 'pay_auto_close_invoices')) && smc_session()['default_setting']['activate_autoclose_rec_pay'] == 1) { ?>
                                                    <div class="col-md-2 " style="    padding-right: 0;padding-left: 0;"><br>
                                                        <button class="btn btn-complete full-width" id="auto_close_inv_btn"><?php echo CommonLanguage::getMessage('auto_close_inv') ?></button>
                                                    </div>
                                                <?php } ?>
                                            <?php } ?>
                                            <div class="clearfix"></div>

                                            <div class="col-md-4 account_balance_div hidden">
                                                <strong><?php echo CommonLanguage::getMessage('Balance') ?>:&nbsp;</strong>
                                                <span id="account_balance"></span>
                                            </div>



                                        </div>
                                        <div class="col-md-4 col-sm-height col-bottom sm-no-padding sm-p-b-20" style="vertical-align: top;">
                                            <div class="sm-m-t-20">
                                                <h4><?php print CommonLanguage::getMessage($IsReceipt ? 'receipt' : 'payment'); ?> # <?php
                                                                                                                                        if (!$IsEdit) {
                                                                                                                                            echo '--';
                                                                                                                                        } else {
                                                                                                                                            echo $edit_data['main']['prefix'] . $edit_data['main']['pay_rec_nb'];
                                                                                                                                        }
                                                                                                                                        ?></h4>
                                            </div>
                                            <div class="form-group form-group-default input-group">
                                                <label class="fade"><?php print CommonLanguage::getMessage('Date'); ?></label>
                                                <input id="PaymentDate" name="PaymentDate" class="form-control" value="<?php echo ($IsEdit) ? $edit_data['main']['payment_date'] : $today; ?>" aria-required="true" aria-invalid="false">
                                                <span class="input-group-addon bg-complete"><i class="fa fa-calendar"></i></span>
                                            </div>
                                            <div id="CurrencyIDContainer" class=" m-t-10">
                                                <div class="form-group form-material floating ">
                                                    <div class="input-group-btn DropDownForForms Closable  " id="CurrencyDropDown">
                                                        <button type="button" class="btn btn-complete btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false" <?php echo $is_readonly ? 'disabled' : '' ?>>
                                                            <span><?php echo ($IsEdit || $is_detail || $is_copy || $is_collect) ? ($edit_data['main']['Currency_Name'] . ' - ' . $edit_data['main']['Currency_Symbol']) : (isset($get_parameters['currency_name']) ? $get_parameters['currency_name'] : $currency_symbol) ?></span>
                                                            <input type="hidden" name="Currency_ID" value="<?php echo ($IsEdit || $is_detail || $is_copy || $is_collect) ? $edit_data['main']['Currency_ID'] : (isset($get_parameters['currency_id']) ? $get_parameters['currency_id'] : $DefaultCurrencyID) ?>" class="form-control ignore" onkeyup="return false" onkeydown="return false" />
                                                        </button>
                                                        <ul class="dropdown-menu">
                                                            <?php echo $CurList ?>
                                                            <li class="divider"></li>
                                                            <li><a class="LoadMore">More..</a></li>
                                                        </ul>
                                                    </div>
                                                </div>
                                            </div>
                                            <div style="display:flex;">

                                                <div style="width: 48%;margin-right:2%">
                                                    <div class="form-group ">
                                                        <label><?php print CommonLanguage::getMessage('exchange_rate') . '<span class="red-star">(' . smc_session()['local_currency_symbol'] . ')</span>'; ?></label>
                                                        <input type="number" step="any" min="0" id="current_rate" name="current_rate" class="form-control full-width current_rate" <?php echo ($IsEdit && smc_session()['local_currency'] == $edit_data['main']['Currency_ID']) ? 'disabled' : (!$IsEdit && ($DefaultCurrencyID == smc_session()['local_currency']) ? 'disabled' : '') ?> <?php echo $is_readonly ? 'readonly' : '' ?> value="<?php echo ($IsEdit || $is_detail || $is_copy || $is_collect) ? $edit_data['main']['current_rate'] : '' ?>" />
                                                    </div>
                                                </div>
                                                <div <?php echo smc_session()['default_setting']['activate_second_currency'] == 1 ? '' : 'hidden'; ?> style="width: 50%;">
                                                    <div class="form-group ">
                                                        <label><?php print CommonLanguage::getMessage('exchange_rate') . ' <span class="red-star">(' . smc_session()['second_currency']['symbol'] . ')</span>'; ?></label>
                                                        <input type="number" step="any" min="0" id="second_currency_rate" name="second_currency_rate" class="form-control full-width second_currency_rate" <?php echo ($IsEdit && smc_session()['default_setting']['second_currency'] == $edit_data['main']['Currency_ID']) ? 'disabled' : (!$IsEdit && ($DefaultCurrencyID == smc_session()['default_setting']['second_currency']) ? 'disabled' : '') ?> <?php echo $is_readonly ? 'readonly' : '' ?> value="<?php echo ($IsEdit || $is_detail || $is_copy || $is_collect) ? $edit_data['main']['second_currency_rate'] : '' ?>" />
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="form-group " style="display: flex;">
                                                <div class="form-group <?php echo smc_session()['default_setting']['activate_accounting_job'] == 1 ? '' : 'hidden' ?>" style="width: 48%;margin-right:2%;">
                                                    <label><?php echo CommonLanguage::getMessage('job') ?></label>
                                                    <input type="hidden" class="full-width" id="job_id" <?php echo $is_readonly ? 'readonly' : '' ?> value="<?php echo ($IsEdit || $is_detail || $is_copy) ? $edit_data['main']['job_id'] : '' ?>" data-select-name="<?= ($IsEdit || $is_detail || $is_copy) ? $edit_data['main']['job_name'] : '' ?>" />
                                                </div>
                                                <div class="<?php echo smc_session()['default_setting']['activate_project'] == 1 ? '' : 'hidden' ?>" style="width: 50%;">
                                                    <label><?php echo CommonLanguage::getMessage('project') ?></label>
                                                    <input type="hidden" class="full-width" id="project_id" <?php echo $is_readonly ? 'readonly' : '' ?> value="<?php echo (($IsEdit || $is_detail || $is_copy) && !empty($edit_data['main']['project_id'])) ? $edit_data['main']['project_id'] : '' ?>" data-select-name="<?= ($IsEdit || $is_detail || $is_copy) ? $edit_data['main']['project_name'] : '' ?>" />
                                                </div>

                                            </div>
                                            <div style="display:flex;">

                                                <div style="width:48%;margin-right:2%" class=" <?php echo $permissions->hasPermission('Branches') ? '' : 'hidden'; ?> ">
                                                    <div class=" form-group">
                                                        <label><?php print CommonLanguage::getMessage('branch'); ?></label>
                                                        <input class=" full-width" id="branch_id" name="branch_id" type="hidden" <?php echo $is_readonly ? 'readonly' : '' ?> value="<?= ($IsEdit || $is_detail || $is_copy) ? $edit_data['main']['branch_id'] : (empty(smc_session()['user_accounts']['branch_id']) ? smc_session()['default_branch_id'] : smc_session()['user_accounts']['branch_id']) ?>" data-select-name='<?= json_encode(($IsEdit || $is_detail || $is_copy) ? $edit_data['main']['branch_name'] : (empty(smc_session()['user_accounts']['branch_id']) ? smc_session()['default_branch_name'] : smc_session()['user_accounts']['branch_name'])) ?>' />
                                                    </div>
                                                </div>

                                                <div style="width: 50%;">
                                                    <div class="form-group <?php echo $IsReceipt && !in_array(9, $pay_rec_fields_hide) ? '' : 'hidden' ?>">
                                                        <label><?php print CommonLanguage::getMessage('salesman'); ?></label>
                                                        <input id="salesman_id" name="salesman_id" class="full-width salesman_id" type="hidden" value="<?php echo (($IsEdit || $is_detail || $is_copy) && !empty($edit_data['main']['salesman_id'])) ? $edit_data['main']['salesman_id'] : '' ?>" data-select-name="<?= ($IsEdit || $is_detail || $is_copy) ? $edit_data['main']['salesman_name'] : '' ?>" />
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div>
                                    <div class=""></div>
                                </div>
                                <div class="table-responsive">
                                    <table class="table" id='PaymentTable'>
                                        <thead>
                                            <tr>
                                                <th class="text-center" style="width:5%"><?php print CommonLanguage::getMessage('payment_type'); ?></th>
                                                <th class="text-center <?php echo in_array(7, $pay_rec_fields_hide) ? 'hidden' : '' ?>" style="width:2%"><?php print CommonLanguage::getMessage('currency'); ?></th>
                                                <th class="text-center " style="width:2%"><?php print CommonLanguage::getMessage('amount'); ?></th>

                                                <th class="text-center <?php echo in_array(8, $pay_rec_fields_hide) ? 'hidden' : '' ?>" style="width:2%"><?php print CommonLanguage::getMessage('exchange_rate'); ?></th>
                                                <th class="text-center <?php echo in_array(11, $pay_rec_fields_hide) ? 'hidden' : '' ?>" style="width:2%"><?php print CommonLanguage::getMessage('operation'); ?></th>
                                                <th class="text-center <?php echo in_array(11, $pay_rec_fields_hide) ? 'hidden' : '' ?>" style="width:2%"><?php print CommonLanguage::getMessage('exchange_rate2'); ?></th>


                                                <th class="text-center <?php echo in_array(10, $pay_rec_fields_hide) ? 'hidden' : '' ?>" style="width:2%"><?php print CommonLanguage::getMessage('amount'); ?> <span id="invoice_curr_span"></span></th>
                                                <th class="text-center <?php echo in_array(0, $pay_rec_fields_hide) ? 'hidden' : '' ?>" style="width:5%"><?php print CommonLanguage::getMessage('due_date'); ?></th>
                                                <th class="text-center <?php echo in_array(1, $pay_rec_fields_hide) ? 'hidden' : '' ?>" style="width:5%"><?php print CommonLanguage::getMessage('value_date'); ?></th>
                                                <th class="text-center <?php echo in_array(2, $pay_rec_fields_hide) ? 'hidden' : '' ?>" style="width:2%"><?php print CommonLanguage::getMessage('check') . ' #'; ?></th>
                                                <th class="text-center <?php echo in_array(3, $pay_rec_fields_hide) ? 'hidden' : '' ?>" style="width:2%"><?php print CommonLanguage::getMessage('user_ref') . ' #'; ?></th>
                                                <th class="text-center <?php echo in_array(4, $pay_rec_fields_hide) ? 'hidden' : '' ?>" style="width:5%"><?php print CommonLanguage::getMessage('note'); ?></th>
                                                <th class="text-center <?php echo ((!smc_session()['default_setting']['activate_payment_commession'] && $IsReceipt) ||  in_array(5, $pay_rec_fields_hide)) ? 'hidden' : '' ?>" style="width:5%"><?php print CommonLanguage::getMessage('commession_amount'); ?></th>
                                                <th class="text-center <?php echo ((!smc_session()['default_setting']['activate_payment_commession'] && $IsReceipt) ||  in_array(6, $pay_rec_fields_hide)) ? 'hidden' : '' ?>" style="width:3%"><?php print CommonLanguage::getMessage('commession_account'); ?></th>
                                                <th class="text-center" style="width:2%"></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            if (($IsEdit || $is_detail || $is_copy || $is_collect)) {
                                                for ($i = 0; $i < count($edit_data['payments']); $i++) {
                                            ?>
                                                    <tr class="TableItem" data-auto="<?php echo !$is_copy ? $edit_data['payments'][$i]['pay_rec_id'] : '' ?>" data-entry="<?php echo !$is_copy ? $edit_data['payments'][$i]['payment_detail_id'] : '' ?>" data-is-returned="<?php echo !$is_copy ? $edit_data['payments'][$i]['is_returned'] : '' ?>" data-is-collected="<?php echo !$is_copy ? $edit_data['payments'][$i]['is_collected'] : '' ?>">


                                                        <td>
                                                            <div class="form-group BootstrapDropDown">
                                                                <select id="paymentType" class="full-width AccountCode" name="paymentType" data-init-plugin="select2" <?php echo $is_readonly || (($edit_data['payments'][$i]['is_returned'] == 1 || $edit_data['payments'][$i]['is_collected'] == 1) && !$is_copy) ? 'disabled' : '' ?>>
                                                                    <?php foreach ($payment_type as $type) : ?>
                                                                        <option value="<?php echo $type['Account_ID']; ?>" data-currency="<?php echo $type['Currency_ID'] ?>" <?php echo $type['Account_ID'] == $edit_data['payments'][$i]['payment_account_id'] ? 'selected' : '' ?>><?php echo $type['Account_Code'] . ' - ' . $type['Account_Name']; ?></option>
                                                                    <?php endforeach; ?>
                                                                </select>
                                                            </div>
                                                        </td>
                                                        <td class="text-center <?php echo in_array(7, $pay_rec_fields_hide) ? 'hidden' : '' ?>">
                                                            <select class="full-width det_currency_id" data-init-plugin="select2" <?php echo $is_readonly || (($edit_data['payments'][$i]['is_returned'] == 1 || $edit_data['payments'][$i]['is_collected'] == 1) && !$is_copy) ? 'disabled' : '' ?>>
                                                                <option value="0"><?php echo CommonLanguage::getMessage('select'); ?></option>
                                                                <?php foreach ($currency_list as $currency) : ?>
                                                                    <option mysymbol="<?php echo $currency['Currency_Symbol']; ?>" <?php echo $edit_data['payments'][$i]['currency_id'] == $currency['Currency_ID'] ? 'selected' : '' ?> value="<?php echo $currency['Currency_ID']; ?>"><?php echo $currency['Currency_Name'] . " - " . $currency['Currency_Code']; ?></option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                        </td>
                                                        <td><textarea type="text" class="form-control Amount  " <?php echo $is_readonly || (($edit_data['payments'][$i]['is_returned'] == 1 || $edit_data['payments'][$i]['is_collected'] == 1) && !$is_copy) ? 'readonly' : '' ?> value="<?php echo $edit_data['payments'][$i]['payment_amount'] ?>"><?php echo $edit_data['payments'][$i]['payment_amount'] ?></textarea></td>

                                                        <td><textarea type="text" class="form-control ex_rate  <?php echo in_array(8, $pay_rec_fields_hide) ? 'hidden' : '' ?> " <?php echo $edit_data['payments'][$i]['currency_id'] == smc_session()['local_currency'] || $is_readonly || (($edit_data['payments'][$i]['is_returned'] == 1 || $edit_data['payments'][$i]['is_collected'] == 1) && !$is_copy) ? 'readonly' : '' ?> value="<?php echo $edit_data['payments'][$i]['current_rate'] ?>"><?php echo $edit_data['payments'][$i]['current_rate'] ?></textarea></td>



                                                        <td class="<?php echo in_array(11, $pay_rec_fields_hide) ? 'hidden' : '' ?>">
                                                            <div class="form-group BootstrapDropDown">
                                                                <select id="operation_type" class="full-width operation_type" name="operation_type" data-init-plugin="select2">
                                                                    <option value=""><?php echo CommonLanguage::getMessage('select'); ?></option>
                                                                    <option value="*"><?php echo CommonLanguage::getMessage('*'); ?></option>
                                                                    <option value="-"><?php echo CommonLanguage::getMessage('/'); ?></option>
                                                                </select>
                                                            </div>
                                                        </td>







                                                        <td <?php echo in_array(11, $pay_rec_fields_hide) ? 'hidden' : '' ?>><textarea type="text" class="form-control ex_rate2  <?php echo in_array(11, $pay_rec_fields_hide) ? 'hidden' : '' ?> " <?php echo $edit_data['payments'][$i]['currency_id'] == smc_session()['local_currency'] || $is_readonly || (($edit_data['payments'][$i]['is_returned'] == 1 || $edit_data['payments'][$i]['is_collected'] == 1) && !$is_copy) ? 'readonly' : '' ?> value="<?php echo $edit_data['payments'][$i]['ex_rate2'] ?>"><?php echo $edit_data['payments'][$i]['ex_rate2'] ?></textarea></td>

                                                        <td><textarea type="text" class="form-control loc_amt  <?php echo in_array(10, $pay_rec_fields_hide) ? 'hidden' : '' ?> " <?php echo $edit_data['payments'][$i]['currency_id'] == smc_session()['local_currency'] || $is_readonly || (($edit_data['payments'][$i]['is_returned'] == 1 || $edit_data['payments'][$i]['is_collected'] == 1) && !$is_copy) ? 'readonly' : '' ?>></textarea></td>

                                                        <td class=" <?php echo in_array(0, $pay_rec_fields_hide) ? 'hidden' : '' ?>"><input type="text" name="check_date" class="form-control check_date" <?php echo $is_readonly || (($edit_data['payments'][$i]['is_returned'] == 1 || $edit_data['payments'][$i]['is_collected'] == 1) && !$is_copy) ? 'readonly' : '' ?> value="<?php echo !$is_copy ? $edit_data['payments'][$i]['payment_due_date'] : '' ?>" /></td>
                                                        <td class=" <?php echo in_array(1, $pay_rec_fields_hide) ? 'hidden' : '' ?>"><input type="text" name="value_date" class="form-control value_date" <?php echo $is_readonly || (($edit_data['payments'][$i]['is_returned'] == 1 || $edit_data['payments'][$i]['is_collected'] == 1) && !$is_copy) ? 'readonly' : '' ?> value="<?php echo !$is_copy ? $edit_data['payments'][$i]['value_date'] : '' ?>" /></td>
                                                        <td class=" <?php echo in_array(2, $pay_rec_fields_hide) ? 'hidden' : '' ?>"><textarea type="text" name="check_number" class="form-control check_number" <?php echo $is_readonly || (($edit_data['payments'][$i]['is_returned'] == 1 || $edit_data['payments'][$i]['is_collected'] == 1) && !$is_copy) ? 'readonly' : '' ?> value="<?php echo $edit_data['payments'][$i]['cheque_nb'] ?>"><?php echo $edit_data['payments'][$i]['cheque_nb'] ?></textarea></td>

                                                        <td class=" <?php echo in_array(3, $pay_rec_fields_hide) ? 'hidden' : '' ?>"><textarea type="text" name="user_ref" class="form-control user_ref" <?php echo (($edit_data['payments'][$i]['is_returned'] == 1 || $edit_data['payments'][$i]['is_collected'] == 1) && !$is_copy) ? 'readonly' : '' ?> value="<?php echo $edit_data['payments'][$i]['user_ref'] ?>"><?php echo $edit_data['payments'][$i]['user_ref'] ?></textarea></td>

                                                        <td class=" <?php echo in_array(4, $pay_rec_fields_hide) ? 'hidden' : '' ?>"><textarea type="text" class="form-control Payment_Note" name="Payment_Note" <?php echo (($edit_data['payments'][$i]['is_returned'] == 1 || $edit_data['payments'][$i]['is_collected'] == 1) && !$is_copy) ? 'readonly' : '' ?> placeholder="<?php print CommonLanguage::getMessage('enter_note'); ?>" value="<?php echo $edit_data['payments'][$i]['payment_note'] ?>"><?php echo $edit_data['payments'][$i]['payment_note'] ?></textarea></td>

                                                        <td class="<?php echo (!smc_session()['default_setting']['activate_payment_commession'] && $IsReceipt) ||  in_array(5, $pay_rec_fields_hide) ? 'hidden' : '' ?>"> <input type="text" class="form-control commession_amount  " <?php echo (($edit_data['payments'][$i]['is_returned'] == 1 || $edit_data['payments'][$i]['is_collected'] == 1) && !$is_copy) ? 'readonly' : '' ?> value="<?php echo $edit_data['payments'][$i]['commission_amount'] ?>"></td>
                                                        <td class="<?php echo (!smc_session()['default_setting']['activate_payment_commession'] && $IsReceipt) ||  in_array(6, $pay_rec_fields_hide) ? 'hidden' : '' ?>"><input type="hidden" class="full-width commession_account  " <?php echo (($edit_data['payments'][$i]['is_returned'] == 1 || $edit_data['payments'][$i]['is_collected'] == 1) && !$is_copy) ? 'readonly' : '' ?> value="<?php echo $edit_data['payments'][$i]['commission_acc_id'] ?>" data-select-name="<?= ($IsEdit || $is_detail || $is_copy) ? $edit_data['payments'][$i]['commission_acc_name'] : '' ?>"></td>

                                                        <td>
                                                            <div class="col-xs-12 AddButtons <?php echo $is_readonly ? 'hidden' : '' ?>">
                                                                <span class="fa fa-plus-circle" style="color:#4c0870;margin-top:15px;margin-right:25px"></span>
                                                                <span class="fa fa-minus-circle  <?php echo (($edit_data['payments'][$i]['is_returned'] == 1 || $edit_data['payments'][$i]['is_collected'] == 1) && !$is_copy) ? 'hidden' : '' ?> " style="color:#ed9421;margin-top:15px;"></span>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php
                                                }
                                            } else {
                                                //check_here
                                                ?>
                                                <tr class="TableItem">
                                                    <td>
                                                        <div class="form-group BootstrapDropDown">
                                                            <select id="paymentType" class="full-width AccountCode" data-init-plugin="select2">
                                                                <?php
                                                                $i = 0;
                                                                $acc_cur = 0;
                                                                foreach ($payment_type as $type) :
                                                                    if (smc_session()['default_setting']['pay_rec_account_currency'] == 1) {
                                                                        $acc_cur = $i == 0 || ($type['Account_ID'] == smc_session()['user_accounts']['cash_account_id']) ? $type['Currency_ID'] : $acc_cur;
                                                                    }
                                                                ?>
                                                                    <option value="<?php echo $type['Account_ID']; ?>" data-currency="<?php echo $type['Currency_ID'] ?>" <?php echo $type['Account_ID'] == smc_session()['user_accounts']['cash_account_id'] ? 'selected' : '' ?>><?php echo $type['Account_Code'] . ' - ' . $type['Account_Name']; ?></option>
                                                                <?php
                                                                    $i++;
                                                                endforeach;
                                                                ?>
                                                            </select>
                                                        </div>
                                                    </td>
                                                    <td class="text-center <?php echo in_array(7, $pay_rec_fields_hide) ? 'hidden' : '' ?>">
                                                        <select class="full-width det_currency_id" data-init-plugin="select2">
                                                            <option value="0"><?php echo CommonLanguage::getMessage('select'); ?></option>
                                                            <?php foreach ($currency_list as $currency) : ?>
                                                                <option mysymbol="<?php echo $currency['Currency_Symbol']; ?>" value="<?php echo $currency['Currency_ID']; ?>" <?php echo $acc_cur == $currency['Currency_ID'] || smc_session()['local_currency'] == $currency['Currency_ID']  ? 'selected' : '' ?>><?php echo $currency['Currency_Name'] . " - " . $currency['Currency_Code']; ?></option>
                                                            <?php endforeach; ?>
                                                        </select>
                                                    </td>
                                                    <td><textarea type="text" class="form-control Amount  " value="<?php echo (isset($get_parameters['amount']) ? $get_parameters['amount'] : '') ?>"><?php echo (isset($get_parameters['amount']) ? $get_parameters['amount'] : '') ?></textarea></td>

                                                    <td class=" <?php echo in_array(8, $pay_rec_fields_hide) ? 'hidden' : '' ?> "><textarea type="text" class="form-control ex_rate " <?php echo $acc_cur == smc_session()['local_currency'] ? 'readonly' : '' ?>></textarea></td>
                                                    <td class="<?php echo in_array(11, $pay_rec_fields_hide) ? 'hidden' : '' ?>">
                                                        <div class="form-group BootstrapDropDown">
                                                            <select id="operation_type" class="full-width operation_type" name="operation_type" data-init-plugin="select2">
                                                                <option value=""><?php echo CommonLanguage::getMessage('select'); ?></option>
                                                                <option value="*"><?php echo CommonLanguage::getMessage('*'); ?></option>
                                                                <option value="-"><?php echo CommonLanguage::getMessage('/'); ?></option>
                                                            </select>
                                                        </div>
                                                    </td>

                                                    <td class=" <?php echo in_array(11, $pay_rec_fields_hide) ? 'hidden' : '' ?> "><textarea type="text" class="form-control ex_rate2 " <?php echo $acc_cur == smc_session()['local_currency'] ? 'readonly' : '' ?>></textarea></td>

                                                    <td class="<?php echo in_array(10, $pay_rec_fields_hide) ? 'hidden' : '' ?>"><textarea type="text" class="form-control loc_amt   " <?php echo $acc_cur == smc_session()['local_currency'] ? 'readonly' : '' ?>></textarea></td>

                                                    <td class=" <?php echo in_array(0, $pay_rec_fields_hide) ? 'hidden' : '' ?>"><input type="text" class="form-control check_date" name="check_date" /></td>
                                                    <td class=" <?php echo in_array(1, $pay_rec_fields_hide) ? 'hidden' : '' ?>"><input type="text" class="form-control value_date" value="" name="value_date" /></td>

                                                    <td class=" <?php echo in_array(2, $pay_rec_fields_hide) ? 'hidden' : '' ?>"><textarea type="text" class="form-control check_number" name="check_number"></textarea></td>
                                                    <td class=" <?php echo in_array(3, $pay_rec_fields_hide) ? 'hidden' : '' ?>"><textarea type="text" name="user_ref" class="form-control user_ref" value=""></textarea></td>
                                                    <td class=" <?php echo in_array(4, $pay_rec_fields_hide) ? 'hidden' : '' ?>"><textarea type="text" class="form-control Payment_Note" name="Payment_Note" placeholder="<?php print CommonLanguage::getMessage('enter_note'); ?>"></textarea></td>

                                                    <td class="<?php echo (!smc_session()['default_setting']['activate_payment_commession'] && $IsReceipt) ||  in_array(5, $pay_rec_fields_hide) ? 'hidden' : '' ?>"><input type="text" class="form-control commession_amount "></td>
                                                    <td class="<?php echo (!smc_session()['default_setting']['activate_payment_commession'] && $IsReceipt) ||  in_array(6, $pay_rec_fields_hide) ? 'hidden' : '' ?>"><input type="hidden" class="full-width commession_account  "></td>

                                                    <td>
                                                        <div class="col-xs-12 AddButtons">
                                                            <span class="fa fa-plus-circle" style="color:#4c0870;margin-top:15px;margin-right:25px"></span>
                                                            <span class="fa fa-minus-circle" style="color:#ed9421;margin-top:15px;display:none"></span>
                                                        </div>
                                                    </td>
                                                </tr>
                                            <?php } ?>
                                        </tbody>
                                    </table>
                                </div>
                                <br>
                                <div class="container-sm-height">
                                    <div class="row row-sm-height b-a b-grey">
                                        <div class="col-sm-8 col-sm-height col-middle clearfix sm-p-b-15">
                                        </div>
                                        <div class="col-sm-4 text-right bg-menu col-sm-height padding-15">
                                            <!--                                                <h5 class="font-montserrat all-caps small no-margin hint-text text-white bold">Total</h5>-->
                                            <?php // if ($IsReceipt) {  
                                            ?>
                                            <h5 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('total_invoices'); ?></h5>
                                            <h1 class="no-margin text-white Total"><span class="CurrencyIndicator"></span>&nbsp;<span id="InvoicesTotal">0</span></h1>
                                            <?php // }  
                                            ?>
                                            <h5 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('total'); ?></h5>
                                            <h1 class="no-margin text-white Total"><span class="CurrencyIndicator"></span>&nbsp;<span id="PaymentTotalDetails">0</span></h1>
                                            <h5 hidden class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('local_amount'); ?></h5>
                                            <h1 hidden class="no-margin text-white "><span><?php echo smc_session()['local_currency_symbol'] ?></span>&nbsp;<span id="local_total_amount">0</span></h1>
                                        </div>
                                    </div>
                                </div>
                                <div class="container-sm-height">

                                    <button class=" btn btn-complete btn-cons m-b-10 pull-right " name="PaymentSubmitButton" id="PaymentSubmitButton" style="padding-top: 10px;top: 20px;min-width:253px;" type="button"><i class="pg-form"></i> <span class="bold"><?php print CommonLanguage::getMessage('Save'); ?></span></button>


                                    <?php if (smc_session()['default_setting']['print_template_settings'] == 0 || smc_session()['default_setting']['print_template_settings'] == 1 || !$IsReceipt) { ?>
                                        <button class=" btn btn-danger btn-cons m-b-10 pull-right disabled " id="PrintBtn" style="padding-top: 10px;top: 20px;min-width:253px;" type="button"><i class="fa fa-print"></i> <span class="bold"><?php print CommonLanguage::getMessage('print'); ?></span></button>

                                        <?php
                                    } else {
                                        foreach ($templates as $temp) {
                                        ?>
                                            <button class=" btn btn-danger btn-cons m-b-10 pull-right disabled check_temp_key" data-id="<?php print $temp['template_id']; ?>" style="padding-top: 10px;top: 20px;min-width:200px;" type="button"><i class="fa fa-print"></i> <span class="bold"><?php print $temp['template_name']; ?></span></button>

                                    <?php
                                        }
                                    }
                                    ?>
                                    <div class="is_flex form-group col-md-3 pull-right m-t-20 <?php echo !$is_return && $permissions->hasPermission($IsReceipt ? ($is_actual ? 'add_act_pending_receipt' : 'add_pending_receipt') : ($is_actual ? 'add_act_pending_payment' : 'add_pending_payment')) ? '' : 'hidden' ?>">
                                        <label><?php echo CommonLanguage::getMessage('pending') . ' ?' ?></label>
                                        <input type="checkbox" id="is_pending" <?php echo ($IsEdit || $is_detail || $is_copy) && $edit_data['main']['is_pending'] == 1 ? 'checked' : '' ?> />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>
<?php // if ($IsReceipt) {  
?>
<div class="modal fade" data-backdrop="static" id="invoice_modal" data-currency="<?php echo ($IsEdit) ? $edit_data['main']['Currency_ID'] : '' ?> " data-customer="<?php echo ($IsEdit) ? $edit_data['main']['Account_ID'] : '' ?> " data-pos-cust="<?php echo ($IsEdit && $IsReceipt) ? $edit_data['main']['pos_customer_id'] : '0' ?> " tabindex="-1" role="dialog" aria-hidden="true" style="width:80%;margin:0 auto">
    <div class="modal-dialog ">
        <div class="modal-content">
            <div class="modal-header clearfix text-left">
                <button type="button" class="close" id="close_modal" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-14"></i></button>
                <h5><span class="semi-bold"><?php print CommonLanguage::getMessage('invoices'); ?></span></h5>
            </div>
            <div class="modal-body form-group">
                <div id="InvoicesModalAlert"></div>
                <div class="row row_head" style="border-bottom: 1px solid #eb9220;">
                    <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('invoice') ?>&nbsp;#</label></div>
                    <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('customer') ?></label></div>
                    <div class="col-md-2"><label><?php echo CommonLanguage::getMessage('Date') ?></label></div>
                    <div class="col-md-2"><label><?php echo CommonLanguage::getMessage('net_total') ?></label></div>
                    <div class="col-md-2"><label><?php echo CommonLanguage::getMessage('remaining') ?></label></div>
                    <div class="col-md-2"><label><?php echo CommonLanguage::getMessage('amount') ?></label></div>
                    <div class="col-md-2"><label><?php echo CommonLanguage::getMessage('Balance') ?></label></div>

                </div>
                <div id="inv_body">

                    <?php
                    if (($IsEdit)) {
                        foreach ($edit_data['pay_inv'] as $inv_pay) {
                    ?>
                            <div class="row m-b-10 my_tr" data-id="<?php echo $inv_pay['Invoice_ID_Auto'] ?>" data-cur="<?php echo $inv_pay['Invoice_Currency'] ?>">
                                <div class="col-md-1"><?php echo $inv_pay['Invoice_ID'] ?></div>
                                <div class="col-md-1"><?php echo $inv_pay['Customer_Name'] ?></div>
                                <div class="col-md-2"><?php echo $inv_pay['Invoice_Date'] ?></div>
                                <div class="col-md-2"><?php echo number_format($inv_pay['Invoice_Net_Total']) . ' ' . $edit_data['payments'][0]['Currency_Symbol'] ?></div>
                                <div class="col-md-2 rem"><?php echo number_format(($inv_pay['Remaining_Amount'] + $inv_pay['inv_pay_amount'])) . ' ' . $edit_data['payments'][0]['Currency_Symbol'] ?></div>
                                <div class="col-md-2"><input type="text" class="form-control" value="<?php echo $inv_pay['inv_pay_amount'] > 0 ? $inv_pay['inv_pay_amount'] : '' ?>" data-max="<?php echo $inv_pay['Remaining_Amount'] + $inv_pay['inv_pay_amount'] ?>" /></div>
                                <div class="col-md-2 balance"><?php echo number_format($inv_pay['Remaining_Amount']) . ' ' . $edit_data['payments'][0]['Currency_Symbol'] ?></div>
                            </div>
                    <?php
                        }
                    }
                    ?>
                </div>
            </div>
            <div class="modal-footer">
                <div class="">
                    <button class="btn btn-complete pull-right" id="CloseInv" data-dismiss="modal"> <?php print CommonLanguage::getMessage('continue'); ?> </button>
                    <button class="btn bg-danger white pull-left" id="ClearInv"> <?php print CommonLanguage::getMessage('clear'); ?> </button>
                </div>
            </div>
        </div>
    </div>
</div>
<?php // }  
?>
<div class="modal fade slide-up" id="choose_template_modal" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content-wrapper">
            <div class="modal-content">
                <div class="modal-header clearfix text-left">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-20"></i>
                    </button>
                    <h5 class="add-label bold"></h5>
                </div>
                <div class="modal-body">
                    <div class="row ">
                        <?php foreach ($templates as $temp) { ?>
                            <div class="col-md-4">
                                <button type="button" class="btn btn-primary  check_temp_key  full-width" data-id="<?php echo $temp['template_id']; ?>"> <?php echo $temp['template_name']; ?></button>
                            </div>
                        <?php } ?>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>
<script>
    var Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
        Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
        change_amounts = <?php echo json_encode(CommonLanguage::getMessage('change_amounts')); ?>,
        check_pay_amounts = <?php echo json_encode(CommonLanguage::getMessage('check_pay_amounts')); ?>,
        user_prefix = <?php echo json_encode($prefix) ?>,
        print_template_settings = <?php echo json_encode(smc_session()['default_setting']['print_template_settings']); ?>,
        pay_rec_account_currency = <?php echo json_encode(smc_session()['default_setting']['pay_rec_account_currency']); ?>,
        only_cust_supp_acc = <?php echo json_encode(smc_session()['default_setting'][$IsReceipt ? 'view_only_cust_accts_receipt' : 'view_only_supp_accts_payment']); ?>,
        acc_main_type = <?php echo json_encode($IsReceipt ? 'cust' : 'supp'); ?>,
        Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>;
    var CurrencySymbol = '',
        cash_customer_arr = <?php echo json_encode($cash_customer); ?>,
        CurrencyRate = <?php echo json_encode($Extable); ?>,
        local_currency = <?php echo json_encode(smc_session()['local_currency']); ?>,
        second_currency = <?php echo json_encode(smc_session()['default_setting']['second_currency']); ?>,
        activate_autoclose_rec_pay = <?php echo json_encode(smc_session()['default_setting']['activate_autoclose_rec_pay']); ?>,
        stop_auto_close_inv = 0,
        IsReceipt = <?php echo $IsReceipt ? "true" : "false" ?>,
        is_collect = <?php echo $is_collect ? "true" : "false" ?>,
        IsActual = <?php echo $is_actual ? "true" : "false" ?>,
        IsEdit = <?php echo $IsEdit ? "true" : "false" ?>,
        is_return = <?php echo $is_return ? "true" : "false" ?>,
        is_readonly = <?php echo $is_readonly ? "true" : "false" ?>,
        is_detail = <?php echo $is_detail ? "true" : "false" ?>,
        edit_id = <?php echo $id; ?>,
        detail_id = <?php echo $detail_id; ?>,
        Paytotal = 0,
        current_prefix,
        receipt_no_invoice = <?php echo json_encode($permissions->hasPermission($is_actual ? 'act_receipt_without_close_invoice' : 'receipt_without_close_invoice')); ?>,
        unique_id = <?php echo json_encode(!$IsEdit ? $unique_id : '') ?>;
    $(function() {
        //        alert(IsActual)
        <?php if (isset($get_parameters['amount'])) {  ?>
            $("#InvoicesTotal").html(AddCommas(public_round_number(parseFloat(Math.round(<?php echo (isset($get_parameters['amount']) ? $get_parameters['amount'] : '0') ?>)))))
        <?php } ?>

        new Switchery($("#is_pending").get(0), {
            color: $.Pages.getColor("complete")
        });
        build_select2($("#salesman_id"), "xhr/employeeSearch")
        build_select2($("#pos_customer"), "xhr/poscustomerSearch")

        build_select2($("#accountId"), ("xhr/accIDSearch?type=" + (only_cust_supp_acc == 1 ? acc_main_type : 'Payment') + "&") + (IsEdit ? ("is_edited=" + $("#accountId").val()) : "Status_ID=1"))
        build_select2($("input.commession_account"), ("xhr/accIDSearch?type=Payment&") + (IsEdit ? ("is_edited=" + $("#accountId").val()) : "Status_ID=1"))
        build_select2($("#branch_id"), "xhr/CommonSearch?col_id=branch_id&col_name=branch_name&table=tbl_organization_branches")
        //        build_select2($("#job_id"), "xhr/CommonSearch?col_id=job_id&col_name=job_name&table=tbl_accounting_jobs")
        build_select2($("#job_id"), "ACCAjax/JobSearch")
        build_select2($("#project_id"), "ACCAjax/projectSearch")
        if (IsEdit) {
            $("#invoice_modal input[value!='']").trigger("keyup")
        }
        $("#pos_customer").on("change", function() {
            if (activate_autoclose_rec_pay == 1) {
                get_cust_invoices(0, 1)
            }
            if ($(this).val() != '') {
                $("#accountId").val(cash_customer_arr['Account_ID']).attr("data-select-name", cash_customer_arr['Account_Name'] + ' - ' + cash_customer_arr['Account_Code'])
                build_select2($("#accountId"), ("xhr/accIDSearch?type=" + (only_cust_supp_acc == 1 ? acc_main_type : 'Payment') + "&") + (IsEdit ? ("is_edited=" + $("#accountId").val()) : "Status_ID=1"))
                $("#accountId").prop("disabled", true)
                getAccBalance()
            } else {
                $("#accountId").val('').attr("data-select-name", '')
                build_select2($("#accountId"), ("xhr/accIDSearch?type=" + (only_cust_supp_acc == 1 ? acc_main_type : 'Payment') + "&") + (IsEdit ? ("is_edited=" + $("#accountId").val()) : "Status_ID=1"))
                $("#accountId").prop("disabled", false)

            }
        })
        $(".CurrencyIndicator").html($("#CurrencyDropDown ul li[value=" + $("#CurrencyDropDown button input").val() + "]").attr("mysymbol"))
        $("#invoice_curr_span").html($("#CurrencyDropDown ul li[value=" + $("#CurrencyDropDown button input").val() + "]").attr("mysymbol"))

        $("#PaymentTable").on("change", "select.AccountCode", function(e) {
            if (pay_rec_account_currency == 1)
                $(this).parents("tr").find('select.det_currency_id').val($("option:selected", $(this)).attr("data-currency")).select2().trigger("change")
        })
        $("#PaymentTable").on("change", "select.det_currency_id", function(e) {
            var tr = $(this).parents('tr'),
                amount = parseFloat($(".Amount", tr).val()) || 0,
                row_cur = parseFloat(tr.find("select.det_currency_id").val()) || 0,
                cur_rate = parseFloat(ConvertCurrency2(1, row_cur, local_currency)) || 0;
            if ($(this).val() == local_currency) {
                $(".ex_rate", tr).val(1).prop('readonly', true)
                $(".loc_amt", tr).val($(".Amount", tr).val()).prop('readonly', true)
            } else {
                $(".ex_rate", tr).val(cur_rate).prop('readonly', false)
                $(".loc_amt", tr).val(amount * cur_rate).prop('readonly', false)
            }
            update_total()
        })
        $("#PaymentTable").on("click", ".AddButtons > .fa-plus-circle", function(e) {
            $(".AddButtons > .fa-minus-circle").css("display", "")
            var Parent = $(this).parents(".TableItem"),
                NewItem = Parent.clone().insertAfter(Parent);
            NewItem.find("input").val('');
            NewItem.find("input,select").removeAttr('disabled').removeAttr('readonly');
            NewItem.attr("data-entry", 0)
            NewItem.attr("data-is-returned", 0)
            NewItem.attr("data-is-collected", 0)
            $(".select2-container", NewItem).empty().remove()
            NewItem.find(".AccountCode").show().select2()
            NewItem.find(".det_currency_id").show().select2()
            NewItem.find(".operation_type").show().select2()
            NewItem.find("input.commession_account").val('').attr("data-select-name", "")
            NewItem.find(".fa-minus-circle").removeClass("hidden")
            build_select2(NewItem.find("input.commession_account"), ("xhr/accIDSearch?type=Payment&Status_ID=1"))

            $(".check_date,.value_date").datepicker({
                autoclose: true
            })
            $(".select2-container", NewItem).show();
        })
        $("#PaymentTable").on("click", ".AddButtons > .fa-minus-circle", function(e) {
            $(this).closest(".TableItem").empty().remove();
            $("#PaymentTable").each(function() {
                $(".AddButtons > .fa-minus-circle", $(this).parent()).css({
                    "display": $(".AddButtons", $(this).parent()).length <= 1 ? "none" : "inline-block"
                })
            });
            update_total()
            //            Paytotal = 0;
            //            $("#PaymentTable .Amount").each(function () {
            //                Paytotal += parseFloat($(this).val()) || 0;
            //            });
            //            $("#PaymentTotalDetails").attr({"MyValue": Paytotal}).text(AddCommas(Paytotal.toXFixed(3)))
        })
        $("#add_payment").on("show.bs.modal", function() {
            $("#PaymentValidationAlert").remove();
            $("#PaymentTotalDetails").html("0");
            //            $("#PaymentTable input").val("")
        });
        $("#PrintBtn").on("click", function() {
            if (print_template_settings == 0) {
                var myurl = "ACC/ViewReceipt" + (IsReceipt ? "/Receipt" : "") + (IsActual ? "/act" : "") + "/" + edit_id;
                printExternal(myurl)
            } else {
                $("#choose_template_modal").modal("show")
            }
        })
        $(".check_temp_key").on("click", function() {
            var myurl = "ACC/ViewReceipt" + (IsReceipt ? "/Receipt" : "") + (IsActual ? "/act" : "") + "/" + edit_id + '&template_id=' + $(this).attr("data-id");
            printExternal(myurl)
        })
        if (!is_readonly) {
            $("#PaymentTable .check_date,#PaymentTable .value_date").each(function() {
                $(this).datepicker({
                    autoclose: true
                })
            })
        }
        $("#PaymentDate").datepicker({
            autoclose: true
        });
        $("#accountId").on("change", function() {
            if (activate_autoclose_rec_pay == 1) {
                get_cust_invoices(0, 1)
            }
            if ($(this).val() != '') {
                $("#pos_customer").prop("disabled", true)
            } else {
                $("#pos_customer").prop("disabled", false)
            }
            if (IsReceipt && $(this).select2("data").main_type == 'cust' && $(this).select2("data").sub_type == 'main') {
                check_salesman()
            }
            getAccBalance()
            var flag = false;
            $("#inv_body input").each(function() {
                if ($(this).val() != '') {
                    flag = true;
                }
            })
            if (flag) {
                toastr.error(change_amounts)
            }
            if ($(this).val()) {
                $('.open_general_ledger').attr('data-src', $('.open_general_ledger').attr('data-main') + '/' + $(this).select2('data').Account_Code);
            } else {
                $('.open_general_ledger').attr('data-src', $('.open_general_ledger').attr('data-main'));
            }
        })
        $("#PaymentSubmitButton").on("click", function() {
            if ($('#accountId').val() && $('#accountId').select2('data').job_required == 1 && !$('#job_id').val()) {
                toastr.error('<?php echo CommonLanguage::getMessage('job_is_required'); ?>');
                return;
            }
            $("#PaymentSubmitButton").addClass("disabled");
            var IsValidated = true;
            $("#PaymentTable .Amount").each(function() {
                if ($(this).val() == "" || ($(this).hasClass("Amount") && ($(this).val()).match(/^\s*?([\d]+(\.\d+)?|\.\d{1,2})\s*$/) == null)) {
                    IsValidated = false;
                }
            })
            if ($("#accountId").val() == '') {
                IsValidated = false;
            }
            if (!IsValidated) {
                $("#paymentAlert").attr("class", " alert alert-danger").empty().html(Required_Fields)
                $("#PaymentSubmitButton").removeClass("disabled");
                $(document.body).animate({
                    scrollTop: 0
                }, 800)
                return false;
            }
            //            if (IsReceipt) {
            var total = 0;
            $("#inv_body input").each(function() {
                total += parseFloat($(this).val()) || 0;
            })
            if (total > parseFloat($("#PaymentTotalDetails").attr('myvalue'))) {
                $("#paymentAlert").attr("class", " alert alert-danger").empty().html(check_pay_amounts)
                $("#PaymentSubmitButton").removeClass("disabled");
                $(document.body).animate({
                    scrollTop: 0
                }, 800)
                return false;
            }
            //            }

            var Data = {
                Payment_Date: $("#PaymentDate").val(),
                Currency_ID: $("#PaymentForm #CurrencyDropDown  input").val(),
                Account_Code: $("#accountId").val(),
                Account_Name: $("#s2id_accountId a span:eq(0)").html(),
                total_payment: public_round_number($("#PaymentTotalDetails").attr('myvalue')),
                branch_id: $("#branch_id").val(),
                IsReceipt: IsReceipt ? 1 : 0,
                Status_ID: IsActual ? 1 : 0,
                is_return: is_return ? 1 : 0,
                is_collect: is_collect ? 1 : 0,
                is_detail: is_detail ? 1 : 0,
                Currency_Rate: $("#current_rate").val(),
                second_currency_rate: $("#second_currency_rate").val(),
                job_id: $("#job_id").val(),
                project_id: $("#project_id").val(),
                salesman_id: $("#salesman_id").val(),
                pos_customer_id: $("#pos_customer").val(),
                is_pending: $("#is_pending").is(":checked") ? 1 : 0,
                Payment_Note: '',
                unique_id: unique_id,
                detail_id: detail_id,
                payment: [],
                close_arr: []
            };
            $(".TableItem").each(function() { //yousif get row
                var me = $(this);
                Data.payment.push({
                    Payment_Type_ID: me.find("#paymentType").val(),
                    currency_id: me.find("select.det_currency_id").val(),
                    ex_rate: me.find(".ex_rate").val(),
                    ex_rate2: me.find(".ex_rate2").val(),
                    Payment_Amount: me.find(".Amount").val(),
                    Check_Date: me.find(".check_date").val(),
                    value_date: me.find(".value_date").val(),
                    Check_Number: me.find(".check_number").val(),
                    Payment_Note: me.find(".Payment_Note").val(),
                    commession_amount: me.find(".commession_amount").val(),
                    commession_account: me.find("input.commession_account").val(),
                    user_ref: me.find(".user_ref").val(),
                    auto_id: me.attr("data-auto"),
                    detail_id: me.attr("data-entry"),
                    is_collected: me.attr("data-is-collected"),
                    is_returned: me.attr("data-is-returned"),
                })
            })
            //            if (IsReceipt) {
            $(".my_tr").each(function() {
                var tr = $(this);
                if (tr.find("input").val() != '' && tr.find("input").val() != 0) {
                    Data.close_arr.push({
                        inv_id: tr.attr("data-id"),
                        inv_amount: tr.find("input").val(),
                        inv_currency: tr.attr("data-cur")
                    })
                }

            })
            //            }
            if (Data.payment.length == 0) {
                $("#paymentAlert").attr("class", "alert alert-warning").html('<?php echo CommonLanguage::getMessage('choose_entry'); ?>');
                $("#PaymentSubmitButton").removeClass("disabled");
                $(document.body).animate({
                    scrollTop: 0
                }, 800)
                return;
            }
            //            if (Data.close_arr.length == 0) {
            //                $("#paymentAlert").attr("class", "alert alert-warning").html('<?php echo CommonLanguage::getMessage('close_inv_first'); ?>');
            //                $("#PaymentSubmitButton").removeClass("disabled");
            //                $(document.body).animate({scrollTop: 0}, 800)
            //                return;
            //            }
            if (IsEdit) {
                Data.pay_id = edit_id;
                //                Data.prefix = user_prefix;
            }

            $("#PaymentIsBusy").removeClass('hidden')
            $.ajax({
                url: IsEdit ? "ACCAjax/editPayment" : "ACCAjax/addPayment",
                method: "POST",
                data: Data,
                dataType: "json",
                complete: function(v1, v2) {
                    if (v2 == 'success') {
                        if (v1.responseJSON[0] == 'OK') {
                            edit_id = v1.responseJSON[3];
                            current_prefix = v1.responseJSON[2];
                            $("#PrintBtn,.check_temp_key").removeClass("disabled");

                            $("#paymentAlert").attr("class", " alert alert-success").empty().html(Submitted_Successfully + '&nbsp;<strong>' + '<?php echo CommonLanguage::getMessage($IsReceipt ? 'rec_nb' : 'pay_nb') ?>' + ' ' + v1.responseJSON[2] + v1.responseJSON[1]);
                            stop_auto_close_inv = 0;
                        } else {
                            $("#paymentAlert").attr("class", " alert alert-danger").empty().html(v1.responseJSON[0])
                            $("#PaymentSubmitButton").removeClass("disabled");
                        }
                    } else {
                        $("#PaymentValidationAlert").attr("class", "alert alert-danger").empty().html(v1.responseJSON[0]);
                        $("#PaymentSubmitButton").removeClass("disabled");
                    }
                    $("#PaymentIsBusy").addClass("hidden")
                    $(document.body).animate({
                        scrollTop: 0
                    }, 800)
                }
            })
        });
        $("#auto_close_inv_btn").on("click", function() {
            auto_close_rec_inv()
        })
        $("#PaymentTable").on("keyup", ".Amount", function() {
            var tr = $(this).parents("tr"),
                amount = parseFloat($(this).val()) || 0,
                row_cur = parseFloat(tr.find("select.det_currency_id").val()) || 0,
                row_rate = parseFloat(tr.find('.ex_rate').val()) || 0;
            cur_rate = tr.find('.ex_rate').val() != '' ? row_rate : parseFloat(ConvertCurrency2(1, row_cur, local_currency)) || 0;
            $(".loc_amt", tr).val(amount * cur_rate)
            update_total()
        })
        $("#PaymentTable").on("keyup", ".ex_rate", function() {
            var tr = $(this).parents("tr"),
                ex_rate = parseFloat($(this).val()) || 0,
                row_cur = parseFloat(tr.find("select.det_currency_id").val()) || 0,
                operation_type = tr.find("select.operation_type").val() || 0,
                amount = parseFloat(tr.find(".Amount").val()) || 0;
            if ($(this).val() == '')
                ex_rate = parseFloat(ConvertCurrency2(1, row_cur, local_currency)) || 0
            $(".loc_amt", tr).val(amount * ex_rate)
            update_total()
        })


        $("#PaymentTable").on("change", ".ex_rate2", function() {
            var tr = $(this).parents("tr"),ex_rate = 0,
                loc_amt = parseFloat(tr.find(".loc_amt").val()) || 0,
                amount = parseFloat(tr.find(".Amount").val()) || 0,
                operation_type = tr.find("select.operation_type").val() || 0,
                ex_rate2 = parseFloat(tr.find(".ex_rate2").val()) || 0,
                row_cur = parseFloat(tr.find("select.det_currency_id").val()) || 0,

                rate = parseFloat(tr.find(".ex_rate").val()) || 0;

                ex_rate = parseFloat(1/ex_rate2) || 0;
                $(".ex_rate", tr).val(ex_rate)

            if (operation_type != '' && ex_rate2 != 0 && loc_amt != 0) {

                amount = operation_type == '*' ? loc_amt * ex_rate2 : loc_amt / ex_rate2;
                // ex_rate = operation_type == '*' ? 1 * ex_rate2 : 1 / ex_rate2;
                $(".Amount", tr).val(amount)
                update_total()

            }
            else if (operation_type != '' && ex_rate2 != 0 && amount != 0) {
                loc_amt = operation_type == '*' ? amount * ex_rate2 : amount / ex_rate2;
                // ex_rate = operation_type == '*' ? 1 * ex_rate2 : 1 / ex_rate2;

                $(".loc_amt", tr).val(loc_amt)

                update_total()

            }

        })
 
        // $("#PaymentTable").on("change", ".Amount,.loc_amt,.ex_rate", function() {
        //     var tr = $(this).parents("tr");
        //     tr.find('input.Amount').val(public_round_number((tr.find('input.Amount').val())))
        //     tr.find('input.loc_amt').val(public_round_number((tr.find('input.loc_amt').val())))
        //     if (tr.find('input.ex_rate2') <= 0 || tr.find('input.ex_rate2') == '') {

        //         tr.find('input.ex_rate').val(public_round_number((tr.find('input.ex_rate').val())))
        //     }

        // })

        $(".Amount").trigger("keyup")
        //        $(".CurrencyIndicator").html($("#CurrencyDropDown li").attr("mysymbol"))
    })

    $("#CurrencyDropDown li").on("click", function() {

        CurrencySymbol = $(this).attr("mysymbol")
        $("#invoice_curr_span").html(CurrencySymbol)
        $(".CurrencyIndicator").html($(this).attr("mysymbol"))
        if ($(this).attr("value") == local_currency) {
            $("#current_rate").val(1).attr("disabled", "disabled")
        } else
            $("#current_rate").val("").removeAttr("disabled")
        if ($(this).attr("value") == second_currency) {
            $("#second_currency_rate").val(1).attr("disabled", "disabled")
        } else
            $("#second_currency_rate").val("").removeAttr("disabled")
        var flag = false;
        $("#inv_body input").each(function() {
            if ($(this).val() != '') {
                flag = true;
            }
        })
        if (flag && activate_autoclose_rec_pay == 0) {
            toastr.error(change_amounts)
        }
        setTimeout(function() {
            getAccBalance()
            update_total()
            if (activate_autoclose_rec_pay == 1) {
                get_cust_invoices(0, 0)
            }

        }, 300)



    })
    //    if (IsReceipt) {
    $("#ClearInv").on("click", function() {
        $("#inv_body input").val("").trigger("keyup")
    })
    $("#get_inv").on("click", function() {

        if ((($("#invoice_modal").attr("data-customer") != "" && $("#invoice_modal").attr("data-customer").trim() == $("#accountId").val().trim()) || (($("#invoice_modal").attr("data-pos-cust") != "" && $("#invoice_modal").attr("data-pos-cust") != "0" && (parseFloat($("#invoice_modal").attr("data-pos-cust").trim()) || 0) == (parseFloat($("#pos_customer").val().trim()) || 0)))) &&
            ($("#invoice_modal").attr("data-currency") != "" && $("#invoice_modal").attr("data-currency").trim() == $("#CurrencyDropDown button input").val().trim())
        ) {
            $("#invoice_modal").modal("show")
            //                alert()
            return false
        }
        get_cust_invoices(1, 1)
        //            alert()

    })

    $("#inv_body").on("click", ".rem", function() {
        var input = $(this).parents(".my_tr").find("input");
        input.val(input.attr("data-max")).trigger("keyup")
    })
    $("#inv_body").on("keyup", "input", function() {
        //        console.log('here')
        stop_auto_close_inv = 1;
        var symbol = $("#CurrencyDropDown ul li[value=" + $("#CurrencyDropDown button input").val() + "]").attr("mysymbol");
        var amount = parseFloat($(this).val()) || 0,
            max_amount = parseFloat($(this).attr("data-max"));
        $(this).parents(".my_tr").find(".balance").html(AddCommas(public_round_number(parseFloat(((max_amount - amount) || 0)))) + ' ' + symbol)

        if (amount > max_amount || amount < 0) {
            $(this).addClass("wrong")

        } else {
            $(this).removeClass("wrong")
        }
        var tr_total = 0,
            validate = true;
        $("#inv_body input").each(function() {
            tr_total += parseFloat($(this).val()) || 0;
            if ($(this).hasClass("wrong"))
                validate = false;
        })
        if (!validate) {
            $("#CloseInv").attr("disabled", "disabled")
            $("#close_modal").addClass("hidden")
        } else {
            $("#CloseInv").removeAttr("disabled")
            $("#close_modal").removeClass("hidden")
        }

        $("#InvoicesTotal").html(AddCommas(public_round_number(parseFloat(Math.round(tr_total))))) //yousif get total
        var count = 0;
        $(".TableItem").each(function() { //yousif get row
            if (count == 0) {
                var me = $(this);
                me.find(".Amount").val(public_round_number(parseFloat(Math.round(tr_total))));
                me.find(".loc_amt").val(public_round_number(parseFloat(Math.round(tr_total))));
                me.find(".loc_amt").trigger("keyup")
            } else {
                return false;
            }
            count++
        })
    })

    function update_table() {

    }
    //    }
    function getAccBalance() {
        if ($("#accountId").val() == '') {
            $(".account_balance_div").addClass("hidden")
            $("#get_inv").attr("disabled", "disabled")
            return
        }
        $.ajax({
            url: "ACCAjax/getAccountBalance",
            method: "GET",
            data: {
                account: $("#accountId").val(),
                currency: $("#CurrencyDropDown button input").val(),
                is_actual: (IsActual ? 1 : 0),
                pos_customer: $("#pos_customer").val()
            },
            dataType: 'json',
            complete: function(v1, v2) {
                if (v2 == 'success') {
                    $(".account_balance_div").removeClass("hidden")
                    $("#account_balance").html(AddCommas(public_round_number(parseFloat(v1.responseJSON['Balance']))) + ' ' + $("#CurrencyDropDown ul li[value=" + $("#CurrencyDropDown button input").val() + "]").attr("mysymbol"))
                    $("#get_inv").removeAttr("disabled")
                }
            }
        })
    }

    function update_total() {

        Paytotal = 0, local_amount = 0;
        $("#PaymentTable .Amount").each(function() {
            var tr = $(this).parents("tr"),
                row_cur = $("select.det_currency_id", tr).val(),
                ex_rate = $(".ex_rate", tr).val(),
                ex_rate2 = $(".ex_rate2", tr).val(),
                loc_amt =  parseFloat($(".loc_amt", tr).val())|| 0,
                amount = parseFloat($(this).val()) || 0;

            if (row_cur == 0) {
                Paytotal += amount;
                local_amount += parseFloat(ConvertCurrency2(amount, row_cur, local_currency)) || 0;
                //                console.log(Paytotal + '===')
            } else {
                if (ex_rate2 == '' && ex_rate == ''){
                    local_amount += parseFloat(ConvertCurrency2(parseFloat($(this).val() || 0), row_cur, local_currency)) || 0;
                    Paytotal += parseFloat(ConvertCurrency2(parseFloat($(this).val() || 0), row_cur, $("#CurrencyDropDown input").val())) || 0;

                }else{
 
                    local_amount +=   loc_amt ;
                    Paytotal += loc_amt ;
 
                }
            }
            //            console.log(amount + '===' + ex_rate + '===' + Paytotal)

        })
        if (stop_auto_close_inv == 0 && activate_autoclose_rec_pay == 1)
            auto_close_rec_inv()
        $("#local_total_amount").text(AddCommas((public_round_number(local_amount))))
        //        console.log(Paytotal)
        $("#PaymentTotalDetails").attr({
            "MyValue": Paytotal
        }).text(AddCommas((public_round_number(Paytotal))))
    }

    function check_salesman() {
        $.ajax({
            url: "ACCAjax/checksalesman_ajax",
            method: "GET",
            data: {
                customer_id: $("#accountId").select2("data").main_id
            },
            dataType: 'json',
            complete: function(v1, v2) {
                if (v2 == 'success') {
                    var data = v1.responseJSON;
                    //                    console.log(data.length)
                    //                    console.log(data)
                    if ('id' in data) {
                        $("#salesman_id").val(data['id']).attr("data-select-name", data['text'])
                        build_select2($("#salesman_id"), "xhr/employeeSearch?customer_id=" + $("#search_supplier").val())
                    }
                }
            }
        })
    }

    function auto_close_rec_inv() {
        //        console.log('hereeee')
        var symbol = $("#CurrencyDropDown ul li[value=" + $("#CurrencyDropDown button input").val() + "]").attr("mysymbol");

        $("#PaymentSubmitButton").prop("disabled", true)
        var amount = parseFloat(Paytotal) || 0;
        $("#InvoicesTotal").html(AddCommas(public_round_number(parseFloat(amount))))
        $("#inv_body input").each(function() {
            var row_max = parseFloat($(this).attr("data-max")) || 0,
                temp = parseFloat(Math.min(amount, row_max));
            //            console.log(row_max + '===' + temp + '===' + amount)
            $(this).val(temp == 0 ? '' : temp);
            $(this).parents(".my_tr").find(".balance").html(AddCommas(public_round_number(parseFloat(((row_max - temp) || 0)))) + ' ' + symbol)

            amount -= temp;
            if (amount <= 0)
                return false;
        })

        $("#PaymentSubmitButton").prop("disabled", false)

    }

    function get_cust_invoices(open_modal, auto_close) {
        $("#PaymentSubmitButton").prop("disabled", true)
        $("#InvoicesTotal").html('0')
        $("#invoice_modal").attr("data-customer", $("#accountId").val())
        $("#invoice_modal").attr("data-pos-cust", $("#pos_customer").val())
        $("#invoice_modal").attr("data-currency", $("#CurrencyDropDown button input").val())
        $.ajax({
            url: "ACCAjax/getUnpaidInvoicesByCustomer",
            method: "GET",
            data: {
                account: $("#accountId").val(),
                currency: $("#CurrencyDropDown button input").val(),
                is_actual: (IsActual ? 1 : 0),
                pos_customer: $("#pos_customer").val(),
                is_receipt: (IsReceipt ? 1 : 0),
                type: (IsReceipt ? 'rec' : 'pay')
            },
            dataType: 'json',
            complete: function(v1, v2) {
                if (v2 == 'success') {
                    $("#inv_body").empty()
                    var data = v1.responseJSON;
                    //inv_body
                    var TR = '';
                    var symbol = $("#CurrencyDropDown ul li[value=" + $("#CurrencyDropDown button input").val() + "]").attr("mysymbol");
                    for (var i = 0; i < data.length; i++) {
                        TR += '<div class="row m-b-10 my_tr" data-id="' + data[i]['Invoice_ID_Auto'] + '" data-cur = "' + data[i]['Invoice_Currency'] + '">' +
                            '<div class="col-md-1">' + data[i]['Invoice_ID'] + '</div>' +
                            '<div class="col-md-1">' + data[i]['Customer_Name'] + '</div>' +
                            '<div class="col-md-2">' + data[i]['Invoice_Date'] + '</div>' +
                            '<div class="col-md-2">' + AddCommas(public_round_number(parseFloat(data[i]['Invoice_Net_Total']))) + ' ' + symbol + '</div>' +
                            '<div class="col-md-2 rem" >' + AddCommas(public_round_number(parseFloat(data[i]['Remaining_Amount']))) + ' ' + symbol + '</div>' +
                            '<div class="col-md-2"><input type="text" class="form-control" data-max="' + data[i]['Remaining_Amount'] + '" /></div>' +
                            '<div class="col-md-2 balance" >' + AddCommas(public_round_number(parseFloat(data[i]['Remaining_Amount']))) + ' ' + symbol + '</div></div>';
                    }
                    TR = $(TR)
                    $("#inv_body").append(TR)
                    if (activate_autoclose_rec_pay == 1 && stop_auto_close_inv == 0 && auto_close == 1)
                        auto_close_rec_inv()
                    if (open_modal == 1)
                        $("#invoice_modal").modal("show")
                    $("#PaymentSubmitButton").prop("disabled", false)

                }
            }
        })
    }
</script>
<?php
include 'Views/Settings/supplier-customer-account-button-modal.php';
