<?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 && empty($edit_arr)) { ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong>you can not edit this deposite/withdrawal! 
        <br>
        This deposite/withdrawal is not available.
    </div>
    <?php
    die();
}
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 Deposit/Withdrawal! 
        <br>
        This Deposit/Withdrawal is transfered to the main branch.
    </div>
    <?php
    die();
}
?>
<style>
    .Disabled{
        cursor:default;
        opacity:0.5;
    }
    .datepicker table tr td.day:hover {
        background: #4c0870  !important;
        color:#fff;
    }
    .datepicker table tr td.active {
        background-color: #4c0870  !important;
    }
    .datepicker thead tr .datepicker-switch {
        color: #4c0870   !important;
        font-size: 13px;
    }
    .datepicker table tr td span.active {
        background-color: #4c0870  !important;
    }
    .datepicker table tr td span:hover {
        background-color: #4c0870  !important;
        color:#fff;
    }
    datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #4c0870  !important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
    .datepicker thead tr .next:before, .datepicker thead tr .prev:before {
        color: #4c0870  !important;
        font-family: 'FontAwesome';
        font-size: 10px;
    }
</style>
<script>
    function AddCommas(val) {
        val = parseFloat(val.toString()).toString();
        while (/(\d+)(\d{3})/.test(val.toString())) {
            val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
        }
        return val.replace(/\.0$|\.00$/, "") || "0";
    }
    function FixNumber(val) {
        return AddCommas(public_round_number(parseFloat(val + "")));
    }

</script>

<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 id="DWUpdateValidationAlert" ></div>
                            <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-4 center-margin pull-left" >
                                                <h2 class="font-montserrat all-caps hint-text"><?php print CommonLanguage::getMessage('deposit_withdrawal'); ?></h2>
                                            </div>
                                            <div class="clearfix"></div>
                                        </div>
                                        <br>

                                    </div>
                                    <div class="col-md-4 col-sm-height col-bottom sm-no-padding sm-p-b-20" style="vertical-align: top;">
                                        <div  class="form-group form-group-default input-group">
                                            <label><?php print CommonLanguage::getMessage('Date'); ?></label>
                                            <input id="Deposit_WithDrawal_Date" name="Deposit_WithDrawal_Date" class="form-control" value="<?php echo ($IsEdit ? $edit_arr['Deposit_WithDrawal_Date'] : $today); ?>" />
                                            <span class="input-group-addon bg-complete"><i class="fa fa-calendar"></i></span>
                                        </div>
                                        <div  class="form-group form-group-default input-group">
                                            <label><?php print CommonLanguage::getMessage('due_date'); ?></label>
                                            <input id="due_date" name="due_date" class="form-control" value="<?php echo ($IsEdit ? $edit_arr['due_date'] : $today); ?>" />
                                            <span class="input-group-addon bg-complete"><i class="fa fa-calendar"></i></span>
                                        </div>

                                        <div class=" form-group" >   
                                            <label><?php print CommonLanguage::getMessage('branch'); ?></label>

                                            <input class=" full-width" id="branch_id" name="branch_id" type="hidden"  value="<?= $IsEdit ? $edit_arr['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 ? $edit_arr['branch_name'] : (empty(smc_session()['user_accounts']['branch_id']) ? smc_session()['default_branch_name'] : smc_session()['user_accounts']['branch_name'])) ?>'/>


                                        </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" value="<?php echo $IsEdit ? $edit_arr['job_id'] : '' ?>" data-select-name="<?= $IsEdit ? $edit_arr['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" value="<?php echo ($IsEdit && !empty($edit_arr['project_id'])) ? $edit_arr['project_id'] : '' ?>" data-select-name="<?= $IsEdit ? $edit_arr['project_name'] : '' ?>"/>
                                            </div>

                                        </div>

                                    </div>
                                </div>
                            </div>
                            <div>
                                <div class="clearfix"></div>
                            </div>
                            <div class="table-responsive">
                                <table class="table m-t-50" id='PrepaidTable'>
                                    <thead>
                                        <tr>
                                            <th class="text-center" style="width:5%"></th>
                                            <th class="text-center" style="width:5%"><?php print CommonLanguage::getMessage('account'); ?><span class="red-star">*</span><span class="fa fa-plus-circle m-l-5 openFrame" data-src="ACC/viewlibrary/1?is_pop=1" style="color:#4c0870;cursor:pointer"></span></th>
                                            <th class="text-center" style="width:5%"><?php print CommonLanguage::getMessage('currency'); ?></th>
                                            <th class="text-center" style="width:5%"><?php print CommonLanguage::getMessage('amount'); ?><span class="red-star">*</span></th>
                                            <th class="text-center" style="width:5%"><?php print CommonLanguage::getMessage('exchange_rate'); ?><span class="red-star">(<?php echo smc_session()['local_currency_symbol']?>)</span></th>
                                            <th <?php echo smc_session()['default_setting']['activate_second_currency'] == 1 ? '':'hidden'; ?>  class="text-center" style="width:5%"><?php print CommonLanguage::getMessage('exchange_rate'); ?><span class="red-star">(<?php echo smc_session()['second_currency']['symbol']?>)</span></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr class="TableItem">
                                            <td  class="text-center">
                                                <?php print CommonLanguage::getMessage('From'); ?>: 
                                            </td>
                                            <td>
                                                <div class="form-group BootstrapDropDown">
                                                    <input class="AccountCode full-width" id="From_Account" type="hidden" value="<?php echo $IsEdit ? $edit_arr['From_Account_ID'] : '' ?>"  data-select-name='<?= json_encode($IsEdit ? $edit_arr['from_account_name'] : '' ) ?>'/>

                                                </div>
                                            </td>
                                            <td>
                                                <div class="form-group BootstrapDropDown">
                                                    <select id="Currency_From" class="full-width currency_select" data-init-plugin="select2">
                                                        <?php foreach ($currency_list as $currency): ?>
                                                            <option mysymbol="<?php echo $currency['Currency_Symbol']; ?>" <?php echo ($IsEdit && $currency['Currency_ID'] == $edit_arr['Currency_From']) ? 'selected' : ($currency['Currency_ID'] == $local_currency ? 'selected' : '' ) ?> value="<?php echo $currency['Currency_ID']; ?>"><?php echo $currency['Currency_Name'] . " - " . $currency['Currency_Code']; ?></option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </td>
                                            <td><input type="text" class="form-control Amount isnumber" id="dw_amount" value="<?php echo $IsEdit ? $edit_arr['Deposit_WithDrawal_Amount'] : '' ?>"></td>
                                            <td><input type="text" class="form-control exchange isnumber " <?php echo ($IsEdit && (smc_session()['local_currency'] == $edit_arr['Currency_From'])) || !$IsEdit ? 'disabled' : '' ?> id="rate_from" value="<?php echo $IsEdit ? $edit_arr['current_rate_from'] : '' ?>"></td>
                                            <td <?php echo smc_session()['default_setting']['activate_second_currency'] == 1 ? '':'hidden'; ?> ><input type="text" class="form-control sec_rate isnumber " <?php echo ($IsEdit && (smc_session()['default_setting']['second_currency'] == $edit_arr['Currency_From']))  ? 'disabled' : '' ?> id="sec_rate_from" value="<?php echo $IsEdit ? $edit_arr['second_currency_rate_from'] : '' ?>"></td>
                                        </tr>
                                        <tr class="TableItem">
                                            <td  class="text-center">
                                                <?php print CommonLanguage::getMessage('To'); ?>: 
                                            </td>
                                            <td>
                                                <div class="form-group BootstrapDropDown">
                                                    <input class="AccountCode full-width" id="To_Account" type="hidden" value="<?php echo $IsEdit ? $edit_arr['To_Account_ID'] : '' ?>"  data-select-name='<?= json_encode($IsEdit ? $edit_arr['to_account_name'] : '' ) ?>' />

                                                </div>
                                            </td>
                                            <td>
                                                <div class="form-group BootstrapDropDown">
                                                    <select id="Currency_To" class="full-width currency_select" data-init-plugin="select2">
                                                        <?php foreach ($currency_list as $currency): ?>
                                                            <option mysymbol="<?php echo $currency['Currency_Symbol']; ?>" <?php echo ($IsEdit && $currency['Currency_ID'] == $edit_arr['Currency_To']) ? 'selected' : ($currency['Currency_ID'] == $local_currency ? 'selected' : '' ) ?> value="<?php echo $currency['Currency_ID']; ?>"><?php echo $currency['Currency_Name'] . " - " . $currency['Currency_Code']; ?></option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </td>
                                            <td><input type="text" class="form-control Amount isnumber" id="dw_amount_To" value="<?php echo $IsEdit ? $edit_arr['Deposit_WithDrawal_Amount_To'] : '' ?>"></td>
                                            <td><input type="text" class="form-control exchange isnumber "  <?php echo ($IsEdit && smc_session()['local_currency'] == $edit_arr['Currency_To']) || !$IsEdit ? 'disabled' : '' ?> id="rate_to" value="<?php echo $IsEdit ? $edit_arr['current_rate_to'] : '' ?>"></td>
                                            <td  <?php echo smc_session()['default_setting']['activate_second_currency'] == 1 ? '':'hidden'; ?>><input type="text" class="form-control sec_rate isnumber "  <?php echo ($IsEdit && smc_session()['default_setting']['second_currency'] == $edit_arr['Currency_To'])  ? 'disabled' : '' ?> id="sec_rate_to" value="<?php echo $IsEdit ? $edit_arr['second_currency_rate_to'] : '' ?>"></td>
                                        </tr>
                                    </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">
                                        <textarea id="DW_Description" name="DW_Description" class="form-control NoteTextArea" placeholder="<?php print CommonLanguage::getMessage('enter_description'); ?>"><?php echo $edit_arr['Deposit_WithDrawal_Description'] ?></textarea>
                                    </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"><?php print CommonLanguage::getMessage('total_from'); ?></h5>
                                        <h1 class="no-margin text-white AddWithDrawalTotal"><span class="CurrencyIndicatorFrom"><?php echo $DefaultCurrencySymbol ?></span>&nbsp;<span id="DWTotalDetailsFrom">0</span></h1>
                                        <h5 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('total_to'); ?></h5>
                                        <h1 class="no-margin text-white AddWithDrawalTotalTo"><span class="CurrencyIndicatorTo"><?php echo $DefaultCurrencySymbol ?></span>&nbsp;<span id="DWTotalDetailsTo">0</span></h1>




                                    </div>
                                </div>
                            </div>
                            <div class="container-sm-height" >
                                <button class=" btn btn-complete btn-cons m-b-10 pull-right  "  id="DWSubmitButton" 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>
                            <button class=" btn btn-danger btn-cons m-b-10 pull-right disabled" id="PrintBtn" style="padding-top: 10px;top: 20px;min-width:200px;" type="button"><i class="fa fa-print"></i> <span class="bold"><?php print CommonLanguage::getMessage('print_invoice'); ?></span></button>
                            </div>
                        </div>
                    </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')); ?>,
            eq_total = <?php echo json_encode(CommonLanguage::getMessage('eq_total')); ?>,
            local_currency = <?php echo $local_currency; ?>,
            second_currency = <?php echo smc_session()['default_setting']['second_currency']; ?>,
            CurrencyRate = <?php echo json_encode($Extable); ?>,
            Is_Actual = <?php echo $Is_Actual ? 1 : 0; ?>,
            IsEditMode = <?php echo $IsEdit ? "true" : "false"; ?>,
            ID_Edit = IsEditMode ? <?php echo json_encode($id); ?> : '',
            Invoice_ID = 0,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            unique_id = <?php echo json_encode(!$IsEdit ? $unique_id : '') ?>;
    $(function () {
        build_select2($("#From_Account"), "xhr/accIDSearch?type=''&" + (IsEditMode ? ("is_edited=" + $("#From_Account").val()) : "Status_ID=1"))
        build_select2($("#To_Account"), "xhr/accIDSearch?type=''&" + (IsEditMode ? ("is_edited=" + $("#To_Account").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"), "ACCAjax/JobSearch")
        build_select2($("#project_id"), "ACCAjax/projectSearch")
        $("#Deposit_WithDrawal_Date,#due_date").datepicker({autoclose: true}).on("changeDate", function () {
            $(this).keyup();
        })
//        $(".currency_select").on("change", function (e) {
//            if ($(this).val() == local_currency) {
//                $(this).parents("tr").find('input.exchange').val(1).attr("disabled", "disabled")
//            } else {
//                $(this).parents("tr").find('input.exchange').val('').removeAttr("disabled", "disabled")
//            }
//        })
        $("#dw_amount,#dw_amount_To,#rate_from,#rate_to").on("keyup", function () {
            update_totals()

        })
        
        $("#dw_amount").on("change", function () {
            $("#dw_amount").val(public_round_number(parseFloat($("#dw_amount").val())))
            update_totals()
        })
        $("#dw_amount_To").on("change", function () {
            $("#dw_amount_To").val(public_round_number(parseFloat($("#dw_amount_To").val())))
            update_totals()
        })
        $("#PrintBtn").on("click", function() {
                 var myurl =  "ACC/view_deposit_withdrawal/" + Invoice_ID ;
                 window.location.href = '<?php echo SITE_LINK ?>'+myurl;

         })


        $("#dw_amount").trigger("keyup")
        $("#DWSubmitButton").on("click", function () {
            $("#DWSubmitButton").attr("disabled", "disabled")
            $("#DWTotalDetailsFrom").attr("data-amount")
            $("#DWTotalDetailsTo").attr("data-amount")
            if ($("#DWTotalDetailsFrom").attr("data-amount") != $("#DWTotalDetailsTo").attr("data-amount")) {
                $("#DWUpdateValidationAlert").attr("class", "alert alert-danger").empty().html(eq_total);
                $("#DWSubmitButton").removeAttr("disabled")
                $(document.body).animate({scrollTop: 0}, 800)
                return
            }
            if ($("#From_Account").val() == '' || $("#To_Account").val() == '' || $("#dw_amount").val() == '' || $("#dw_amount_To").val() == '') {
                $("#DWUpdateValidationAlert").attr("class", "alert alert-danger").empty().html(Required_Fields);
                $("#DWSubmitButton").removeAttr("disabled")
                $(document.body).animate({scrollTop: 0}, 800)
                return
            }
            var DataForm = new FormData();
            var Data = {
                From_Account: $("#From_Account").val(),
                To_Account: $("#To_Account").val(),
                Deposit_WithDrawal_Amount: $("#dw_amount").val(),
                Deposit_WithDrawal_Amount_To: $("#dw_amount_To").val(),
                Currency_From: $("#Currency_From").val(),
                Currency_To: $("#Currency_To").val(),
                rate_from: $("#rate_from").val(),
                rate_to: $("#rate_to").val(),
                sec_rate_from: $("#sec_rate_from").val(),
                sec_rate_to: $("#sec_rate_to").val(),
                branch_id: $("#branch_id").val(),
                job_id: $("#job_id").val(),
                project_id: $("#project_id").val(),
                Deposit_WithDrawal_Date: $("#Deposit_WithDrawal_Date").val(),
                due_date: $("#due_date").val(),
                Deposit_WithDrawal_Description: $("#DW_Description").val() ? $("#DW_Description").val() : '',
                Is_Actual: Is_Actual,
                unique_id: unique_id
            };
            if (IsEditMode) {
                Data.dw_id = ID_Edit;
            }
            $.each(Data, function (key, value) {
                DataForm.append(key, value);
            })
            $("#DWIsBusy").remove()
            $("#addDepositWithDrawal").append('<div id="DWIsBusy" style="position:absolute;left:0;right:0;top:0px;height:100%;background:rgba(255,255,255,0.9);z-index:9999;opacity:0"><img class="image-responsive-height demo-mw-50" src="img/demo/progress.svg" alt="Progress" style="position: absolute;left: 50%;top: 50%;margin: -25px 0 0 -25px;" /></div>');

            $.ajax({
                url: IsEditMode ? "ACCAjax/editDepositeWithDrawalAjax" : "ACCAjax/addDepositeWithDrawalAjax",
                method: "POST",
                data: DataForm,
                processData: false,
                contentType: false,
                dataType: 'json',

                complete: function (v1, v2) {
                     if (v2 == 'success') {
                        if (Number.isInteger(parseInt(v1.responseJSON[1]))) {
                            Invoice_ID = v1.responseJSON[1];
                            $("#PrintBtn").removeClass('disabled')

 
//                            ChangeTable();
                            $("#DWUpdateValidationAlert").attr("class", "alert alert-success").empty().html(Submitted_Successfully);
                            setTimeout(function () {
                                $("#addDepositWithDrawal").modal('hide')
                                $("#DWUpdateValidationAlert").addClass('hidden')
                            }, 1500)
                        } else {
                            $("#DWUpdateValidationAlert").attr("class", "alert alert-danger").empty().html(v1.responseText);
                            $("#DWSubmitButton").removeAttr("disabled")
                        }
                    } else {
                        $("#DWUpdateValidationAlert").attr("class", "alert alert-danger").empty().html(Failed_Submit);
                        $("#DWSubmitButton").removeAttr("disabled")
                    }
                    $("#DWIsBusy").remove();
                    $(document.body).animate({scrollTop: 0}, 800)

                }
            })
        });
    })
    $("#Currency_From,#Currency_To").on("change", function () {
        if ($(this).val() == local_currency) {
            $(this).parents("tr").find('input.exchange').val(1).attr("disabled", "disabled")
        } else {
            $(this).parents("tr").find('input.exchange').val('').removeAttr("disabled", "disabled")
        }
        if ($(this).val() == second_currency) {
            $(this).parents("tr").find('input.sec_rate').val(1).attr("disabled", "disabled")
        } else {
            $(this).parents("tr").find('input.sec_rate').val('').removeAttr("disabled", "disabled")
        }
        update_totals()
    })
    function update_totals() {
        var amount = parseFloat($('#dw_amount').val()) || 0,
                amountto = parseFloat($('#dw_amount_To').val()) || 0,
                rate_from = parseFloat($('#rate_from').val()) || 0,
                rate_to = parseFloat($('#rate_to').val()) || 0,
                from_a = rate_from > 0 ? (amount * rate_from) : ConvertCurrency2(amount, $("#Currency_From").val(), local_currency),
                to_a = rate_from > 0 ? (amountto * rate_to) : ConvertCurrency2(amountto, $("#Currency_To").val(), local_currency);
        console.log(from_a)
//        $('.CurrencyIndicatorFrom').html($("#Currency_From option:selected").attr('mysymbol') ? $("#Currency_From option:selected").attr('mysymbol') : '');
//        $('.CurrencyIndicatorTo').html($("#Currency_To option:selected").attr('mysymbol') ? $("#Currency_To option:selected").attr('mysymbol') : '');
        $("#DWTotalDetailsFrom").text(FixNumber(from_a)).attr("data-amount", from_a)
        $("#DWTotalDetailsTo").text(FixNumber(to_a)).attr("data-amount", to_a)

    }
</script>
