<?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['main']['auto_id'])) {
    ?>
    <div class="alert alert-danger" role="alert">
        <button class="close" data-dismiss="alert"></button>
        <strong>Danger: </strong>you can not edit this customer coupon invoice! 
        <br>
        This customer coupon invoice is not available.
    </div>
    <?php
    die();
}
?>
<style type="text/css">
    #InventoryPurchaseTable .TotalTD{
        width: auto;
        display: inline-block;
        text-align: center;
        font-size: 20px;
        font-weight: bold;
    }
    .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;
    }
    .datepicker thead tr .dow {
        color:#4c0870!important;
    }
    .datepicker table tr td.day:hover {
        background: #4c0870!important;
        color:#fff;
    }
    .datepicker table tr td.active {
        background-color: #4c0870!important;
color:#ed9421 !important;    }
    .datepicker thead tr .datepicker-switch {
        color: #4c0870 !important;
        font-size: 13px;
    }
    .datepicker table tr td span.active {
        background-color: #4c0870!important;
color:#ed9421 !important;    }
    .datepicker table tr td span:hover {
        background-color: #4c0870!important;
color:#ed9421 !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;
    }
    #InventoryPurchaseTable .select2-container .select2-choice {
        background-image: none;
        border-radius: 2px;
        border: 1px solid rgba(0,0,0,0.07);
        padding: 5px 9px 16px;
        transition: border 0.2s linear 0s;
        height: 40px;
        background-color: #e5e5e5;
        width: 150px;
    }
    #InvoicePaymentSetup .nav.nav-tabs a {
        padding: 7px 14px;
        font-size: 11px;
    }
    .InputSpinner{
        width: 60px;
    }
    .InputSpinner > .form-control{
        border-color: rgb(221, 221, 221);
        height:36px;
        margin:0;
        padding:0;
        text-align: center;
    }
    .InputSpinner > .input-group-btn-vertical {
        position: relative;
        white-space: nowrap;
        width: 25px;
        vertical-align: middle;
        display: table-cell;
    }
    .InputSpinner > .input-group-btn-vertical > .btn {
        height:19px;
        display: block;
        float: none;
        width: 100%;
        max-width: 100%;
        padding: 8px;
        margin-left: -1px;
        position: relative;
        border-radius: 0;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:first-child {
        border-top-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical > .btn:last-child {
        margin-top: -2px;
        border-bottom-right-radius: 4px;
    }
    .InputSpinner > .input-group-btn-vertical i{
        position: absolute;
        top: 50%;
        left: 6px;
        margin-top:-9px;
        font-size: 18px;
    }
    .InputSpinner .input-group-btn-vertical .btn.btn-default{
        font-size: 10px;
        padding: 6px 10px;
    }
    #InvoicePaymentSetup .table tbody > tr:last-child > td{
        border:0;
    }
    .select2-container > .select2-choice {
        width: 100% !important;
    }
    .invoice{
        padding-top:0 !important;
    }
    .right-div .form-group{
        margin-bottom:0px;
    }
    .AddRow{
        background: #e5e5e5;
        padding: 10px;
        border-radius: 6px;
        margin-bottom: 10px;
    }
    .title-color{
        color:#eb9220;
    }
    .p-r-0{
        padding-right:0px !important;
    }
</style>
<form method="POST" action="javascript:void(0);" onsubmit="return false" id="customerCouponForm">
    <div class="container-fluid container-fixed-lg">
        <div class="panel panel-default">
            <div class="panel-body">
                <div id = "PurchaseSuccess" class = "hidden"></div>
                <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 class = "row " style = "display:flex;">
                                    <div class = "col-md-6">
                                        <h2 class = "font-montserrat all-caps hint-text"><?php echo CommonLanguage::getMessage('customer_coupons');
?> </h2>
                                    </div>
                                </div>
                                <div class='row form-group'>
                                    <div class="input-group  col-md-4 center-margin pull-left " >
                                        <label><?php print CommonLanguage::getMessage('choose_customer'); ?>
                                            <span class="red-star">*</span>
                                        </label>
                                        <span class="fa fa-plus-circle m-l-5 openFrame" data-src="Inventory/CustomerList?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span>
                                        <input class="search_customer full-width" id="search_customer" name="search_customer" type="hidden" value="<?= $IsEdit ? $edit_arr['main']['Customer_ID'] : ''; ?>" data-select-name='<?= json_encode(($IsEdit) ? $edit_arr['main']['Customer_Name'] : ""); ?>' required />
                                    </div>
                                    <div class="input-group  col-md-4 center-margin pull-left " >
                                        <label><?php print CommonLanguage::getMessage('bone_type'); ?>
                                            <span class="red-star">*</span>
                                        </label>
                                        <input class="bone_type_id full-width" id="bone_type_id" name="bone_type_id" type="hidden" value="<?= $IsEdit ? $edit_arr['main']['bone_type_id'] : ''; ?>" data-select-name='<?= json_encode(($IsEdit) ? $edit_arr['main']['bone_type_name'] : ""); ?>' required />
                                    </div>
                                </div>
                                <div class="row form-group">
                                    <?php if ($permissions->hasPermission('edit_customer_coupon')) { ?>

                                        <div class="col-md-4" >
                                            <label><?php print CommonLanguage::getMessage('customer_coupons'); ?>
                                            </label>
                                            <input class="customer_coupons_search full-width" id="customer_coupons_search" name="customer_coupons_search" type="hidden" value="" data-select-name=''  />
                                        </div>
                                    <?php } ?>
                                </div>
                                <br>
                            </div>
                            <div class="right-div col-md-4 col-sm-height col-bottom sm-no-padding sm-p-b-20" style="vertical-align: top;">
                                <div  style="display: flex">
                                    <div  class="form-group " style="width: 48%;margin-right:2%;">
                                        <label><?php print CommonLanguage::getMessage('Date'); ?></label>
                                        <input id="invoice_date" name="invoice_date" class="form-control" value="<?php echo ($IsEdit ? $edit_arr['main']['invoice_date'] : $today); ?>" required />
                                    </div>

                                </div>
                                <div  id="depot" class="form-group " style="display: flex;">
                                    <div style="width: 48%;margin-right:2%;" >
                                        <label><?php print CommonLanguage::getMessage('Depot'); ?>
                                            <span class="red-star">*</span>
                                        </label>
                                        <span class="fa fa-plus-circle m-l-5 openFrame" data-src="Stock/ListDepot?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span>
                                        <input required id="Depot_Loc" name="Depot_Loc" class="full-width Depot_Loc" type="hidden" <?php echo $permissions->hasPermission('change_depot') ? '' : 'disabled' ?> data-old="<?php echo $IsEdit ? $edit_arr['main']['depot_id'] : ''; ?>" value="<?= $IsEdit ? $edit_arr['main']['depot_id'] : (smc_session()['user_accounts']['depot_id'] ? smc_session()['user_accounts']['depot_id'] : smc_session()['default_depot_id']) ?>" data-select-name='<?= json_encode($IsEdit ? $edit_arr['main']['Depot_Name'] : (smc_session()['user_accounts']['Depot_Name'] ? smc_session()['user_accounts']['Depot_Name'] : smc_session()['default_depot_name'])) ?>'  required/>
                                    </div>
                                    <div style="width: 50%;" >
                                        <div  class="form-group " >
                                            <label><?php print CommonLanguage::getMessage('exchange_rate'); ?></label>
                                            <input type="number" step="any" min="0" id="current_rate" name="current_rate" class="form-control full-width current_rate" <?php echo ($DefaultCurrencyID == smc_session()['local_currency']) ? 'disabled' : '' ?>  value="<?php echo ($IsEdit ) ? $edit_arr['main']['current_rate'] : '' ?>" />
                                        </div>
                                    </div>
                                </div>
                                <div id="CurrencyIDContainer" class=" m-t-10" >
                                    <div class="form-group form-material floating ">
                                        <div class="input-group-btn DropDownForForms Closable" id="CurrencyDropDown" data-symbol="<?php echo $IsEdit ? $edit_arr['main']['Currency_Symbol'] : smc_session()['local_currency_symbol']; ?>">
                                            <button type="button" class="btn btn-primary btn-block dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                                <span><strong><?php echo $IsEdit ? ($edit_arr['main']['Currency_Name'] . ' - ' . $edit_arr['main']['Currency_Symbol']) : (smc_session()['local_currency_name'] . ' - ' . smc_session()['local_currency_code']); ?></strong></span>
                                                <input type="hidden"  value="<?php echo $IsEdit ? $edit_arr['main']['Currency_ID'] : smc_session()['local_currency'] ?>" class="form-control ignore" onkeyup="return false" onkeydown="return false" name="Currency_ID" id="Currency_ID" required/>
                                            </button>
                                            <ul class="dropdown-menu">
                                                <?php echo $CurList ?>
                                                <li class="divider"></li>
                                                <li><a class="LoadMore">More..</a></li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group " style="display: flex;">
                                    <div class="m-b-10" style="width: 48%;" >
                                        <label><?php echo CommonLanguage::getMessage('job') ?></label>
                                        <input type="hidden" class="full-width" id="job_id" value="<?php echo $IsEdit ? $edit_arr['main']['job_id'] : '' ?>" data-select-name="<?= $IsEdit ? $edit_arr['main']['job_name'] : '' ?>"/>
                                    </div>
                                </div>
                            </div>
                            <br>
                        </div>
                    </div>
                    <h3 class="bold title-color"><?php echo CommonLanguage::getMessage('bone'); ?></h3>
                    <div class="AddRow m-b-10 form-group bone-div"  >
                        <div class="row">
                            <div class="col-md-12  m-b-10 form-group"  >
                                <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('product') ?></label></div>
                                <div class="col-md-1"><label><?php print CommonLanguage::getMessage('Date'); ?></label></div>
                                <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('liters') ?></label></div>
                                <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('unit_price') ?></label></div>
                                <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('disc') ?></label></div>
                                <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('discount_percent') ?></label></div>
                                <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('coupon_number') ?></label></div>
                                <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('note') ?></label></div>
                                <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('vat') ?></label></div>
                                <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('vat_percent') ?></label></div>
                                <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('total') ?></label></div> </div>
                        </div>
                        <?php
                        if ($IsEdit) {
                            foreach ($edit_arr['details']['coupons'] as $row) {
                                ?>
                                <div class="row bone-row ">
                                    <div class="col-md-12 m-b-10 "  >
                                        <div class="col-md-1 p-r-0"><input type="hidden" class="bone_product_id full-width" value="<?php echo $row['Product_ID']; ?>" data-select-name="<?php echo $row['prod']; ?>"/></div>
                                        <div class="col-md-1 p-r-0"><input type="text" class="bone_date form-control" name="bone_date" value="<?php echo $row['coupon_date']; ?>"/></div>
                                        <div class="col-md-1 p-r-0"><input type="number" class="form-control liters" min="0" step="any" value="<?php
                                            echo str_replace(',', '', $row['current_quantity']);
                                            ;
                                            ?>"/></div>
                                        <div class="col-md-1 p-r-0"><input type="number" class="form-control bone_unit_price" min="0" step="any" value="<?php echo $row['unit_price']; ?>"/></div>
                                        <div class="col-md-1 p-r-0"><input type="number" class="form-control bone_discount_amount" min="0" step="any" value="<?php echo $row['discount_amount']; ?>"/></div>
                                        <div class="col-md-1 p-r-0"><input type="number" class="form-control bone_discount_percent" min="0" step="any"  max="100" value="<?php echo $row['discount_percent']; ?>"/></div>
                                        <div class="col-md-1 p-r-0"><input type="text" class="form-control coupon_number" nam="coupon_number" value="<?php echo $row['coupon_number']; ?>"/></div>
                                        <div class="col-md-1 p-r-0"><input type="text" class="form-control bone_note" nam="bone_note" value="<?php echo $row['note']; ?>"/></div>
                                        <div class="col-md-1 p-r-0"><input type="number" class="form-control bone_vat" min="0" step="any" value="<?php echo $row['vat_amount']; ?>"/></div>
                                        <div class="col-md-1 p-r-0"><input type="number" class="form-control bone_vat_percent" min="0" step="any" value="<?php echo $row['vat_percent']; ?>"/></div>

                                        <div class="col-md-1 p-r-0"><input type="number"  class="form-control bone-total" bone-total="<?php echo $row['total_price']; ?>" min="0" step="any" value="<?php echo $row['total_price']; ?>"/></div>
                                        <div class="col-md-1">
                                            <span class="fa fa-plus-circle m-l-5 " style="color:#8a7dbe;cursor:pointer"></span>
                                            <span class="fa fa-minus-circle m-l-5 " style="color:#ed9421;cursor:pointer"></span>
                                        </div>
                                    </div>
                                </div>

                                <?php
                            }
                        } else {
                            ?>
                            <div class="row bone-row ">
                                <div class="col-md-12 m-b-10 "  >
                                    <div class="col-md-1 p-r-0"><input type="hidden" class="bone_product_id full-width"/></div>
                                    <div class="col-md-1 p-r-0"><input type="text" class="bone_date form-control" name="bone_date"/></div>
                                    <div class="col-md-1 p-r-0"><input type="number" class="form-control liters" min="0" step="any"/></div>
                                    <div class="col-md-1 p-r-0"><input type="number" class="form-control bone_unit_price" min="0" step="any"/></div>
                                    <div class="col-md-1 p-r-0"><input type="number" class="form-control bone_discount_amount" min="0" step="any" value=""/></div>
                                    <div class="col-md-1 p-r-0"><input type="number" class="form-control bone_discount_percent" min="0" step="any" value="" max="100"/></div>
                                    <div class="col-md-1 p-r-0"><input type="text" class="form-control coupon_number" nam="coupon_number" /></div>
                                    <div class="col-md-1 p-r-0"><input type="text" class="form-control bone_note" nam="bone_note"/></div>
                                    <div class="col-md-1 p-r-0"><input type="number" class="form-control bone_vat" min="0" step="any"/></div>
                                    <div class="col-md-1 p-r-0"><input type="number" class="form-control bone_vat_percent" min="0" step="any"/></div>

                                    <div class="col-md-1 p-r-0"><input type="number"  class="form-control bone-total" bone-total="0" min="0" step="any"/></div>
                                    <div class="col-md-1">
                                        <span class="fa fa-plus-circle m-l-5 " style="color:#8a7dbe;cursor:pointer"></span>
                                        <span class="fa fa-minus-circle m-l-5 " style="color:#ed9421;cursor:pointer"></span>
                                    </div>
                                </div>
                            </div>
                        <?php } ?>
                    </div>
                    <h3 class="bold title-color"><?php echo CommonLanguage::getMessage('product'); ?></h3>
                    <div class="AddRow m-b-10 form-group prod-div"  >
                        <div class="row  m-b-10 form-group"  >
                            <div class="col-md-12">
                                <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('product') ?></label></div>
                                <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('qty') ?></label></div>
                                <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('UOM') ?></label></div>
                                <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('unit_price') ?></label></div>
                                <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('disc') ?></label></div>
                                <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('discount_percent') ?></label></div>
                                <div class="col-md-2"><label><?php echo CommonLanguage::getMessage('description') ?></label></div>
                                <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('vat') ?></label></div>
                                <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('vat_percent') ?></label></div>
                                <div class="col-md-1"><label><?php echo CommonLanguage::getMessage('total') ?></label></div> </div>
                        </div>
                        <?php
                        if ($IsEdit && !empty($edit_arr['details']['products'])) {
                            foreach ($edit_arr['details']['products'] as $prod) {
                                ?>
                                <div class="row prod-row  "  >
                                    <div class="col-md-12">
                                        <div class="col-md-1 p-r-0"><input type="hidden" class="inv_product_id full-width" value="<?php echo $prod['Product_ID'] ?>" data-select-name="<?= $prod['prod'] ?>"/></div>
                                        <div class="col-md-1 p-r-0"><input type="number" class="form-control prod_qty" min="0" step="any" value="<?php echo $prod['current_quantity'] ?>"/></div>
                                        <div class="col-md-1 p-r-0"><input type="hidden" class="uom_id full-width" value="<?php echo $prod['UOM_ID'] ?>" data-select-name="<?= $prod['UOM_Name'] ?>"/></div>
                                        <div class="col-md-1 p-r-0"><input type="number" class="form-control prod_unit_price full-width"  min="0" step="any" value="<?php echo $prod['unit_price'] ?>"/></div>
                                        <div class="col-md-1 p-r-0"><input type="number" class="form-control prod_disc_amount" min="0" step="any" value="<?php echo $prod['discount_amount'] ?>"/></div>
                                        <div class="col-md-1 p-r-0"><input type="number" class="form-control prod_disc_percent" min="0" step="any" max="100" value="<?php echo $prod['discount_percent'] ?>"/></div>
                                        <div class="col-md-2 p-r-0"><input type="text" class="form-control prod_desc" value="<?php echo $prod['note'] ?>" /></div>
                                        <div class="col-md-1 p-r-0"><input type="number" class="form-control prod_vat" min="0" step="any" value="<?php echo $prod['vat_amount'] ?>"/></div>
                                        <div class="col-md-1 p-r-0"><input type="number" class="form-control prod_vat_percent" min="0" step="any" value="<?php echo $prod['vat_percent'] ?>"/></div>
                                        <div class="col-md-1 p-r-0"><h5 class="total_div"><strong><span class="prod-total" prod-total="0"><?php echo $prod['total_price']; ?></span>&nbsp;<span class="CurrencyIndicator"><?php echo smc_session()['local_currency_symbol'] ?></span></strong></h5></div>
                                        <div class="col-md-1">
                                            <span class="fa fa-plus-circle m-l-5 " style="color:#8a7dbe;cursor:pointer"></span>
                                            <span class="fa fa-minus-circle m-l-5 " style="color:#ed9421;cursor:pointer"></span>
                                        </div>
                                    </div>
                                </div>
                                <?php
                            }
                        } else {
                            ?>
                            <div class="row prod-row  "  >
                                <div class="col-md-12">
                                    <div class="col-md-1 p-r-0"><input type="hidden" class="inv_product_id full-width"/></div>
                                    <div class="col-md-1 p-r-0"><input type="number" class="form-control prod_qty" min="0" step="any"/></div>                                
                                    <div class="col-md-1 p-r-0"><input type="hidden" class="uom_id full-width"/></div>
                                    <div class="col-md-1 p-r-0"><input type="number" class="form-control prod_unit_price full-width"  min="0" step="any"/></div>
                                    <div class="col-md-1 p-r-0"><input type="number" class="form-control prod_disc_amount" min="0" step="any"/></div>
                                    <div class="col-md-1 p-r-0"><input type="number" class="form-control prod_disc_percent" min="0" step="any" max="100"/></div>
                                    <div class="col-md-2 p-r-0"><input type="text" class="form-control prod_desc" /></div>
                                    <div class="col-md-1 p-r-0"><input type="number" class="form-control prod_vat" min="0" step="any"/></div>
                                    <div class="col-md-1 p-r-0"><input type="number" class="form-control prod_vat_percent" min="0" step="any"/></div>
                                    <div class="col-md-1 p-r-0"><h5 class="total_div"><strong><span class="prod-total" prod-total="0">0</span>&nbsp;<span class="CurrencyIndicator"><?php echo smc_session()['local_currency_symbol'] ?></span></strong></h5></div>
                                    <div class="col-md-1">
                                        <span class="fa fa-plus-circle m-l-5 " style="color:#8a7dbe;cursor:pointer"></span>
                                        <span class="fa fa-minus-circle m-l-5 " style="color:#ed9421;cursor:pointer"></span>
                                    </div>
                                </div>
                            </div>
                        <?php } ?>
                    </div>
                    <br>
                    <div class="container-sm-height" >
                        <div class="row row-sm-height b-a b-grey">
                            <div class="col-sm-6 col-sm-height   clearfix" style="border-left: 1px solid #eee;border-right: 1px solid #eee;padding-right:0">
                                <div class="col-sm-12  " style="padding-right:0">
                                    <textarea id="invoice_note" name="invoice_note" class="form-control NoteTextArea" placeholder="<?php print CommonLanguage::getMessage('enter_note'); ?> ..." aria-invalid="false"><?php echo $IsEdit ? $edit_arr['main']['description'] : '' ?></textarea>
                                </div>
                                <div class="col-sm-12  " style="padding-right:0">
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold"><?php print CommonLanguage::getMessage('payment'); ?><span class="fa fa-plus-circle m-l-5 openFrame" data-src="ACC/viewlibrary/1?is_pop=1" style="color:#8a7dbe;cursor:pointer"></span></h5>
                                    <div id="InvoicePaymentSetup" class="no-print">
                                        <div class="Body">
                                            <div class="">
                                                <ul class="nav nav-tabs">
                                                    <li class="active"><a data-toggle="tab" href="#SetPaidFormTab_1"><i class="fa fa-money"></i>&nbsp;&nbsp;<?php print CommonLanguage::getMessage('cash'); ?></a></li>
                                                    <li><a data-toggle="tab" href="#SetPaidFormTab_2"><i class="fa fa-file-text-o"></i>&nbsp;&nbsp;<?php print CommonLanguage::getMessage('check'); ?></a></li>
                                                    <li><a data-toggle="tab" href="#SetPaidFormTab_3"><i class="fa fa-cc-visa"></i>&nbsp;&nbsp;<?php print CommonLanguage::getMessage('credit_card'); ?></a></li>
                                                </ul>
                                                <div class="tab-content" style="padding:0;overflow:visible">
                                                    <div id="SetPaidFormTab_1" class="tab-pane fade in active">
                                                        <table class="table" cellpadding="0" cellspacing="0">
                                                            <tbody>
                                                                <tr>
                                                                    <td style="width: 65%;"><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('amount'); ?></span></td>
                                                                    <td>
                                                                        <div class="input-group InputSpinner" style="width:120px">
                                                                            <input type="text" class="form-control" value="<?php echo ($IsEdit && array_key_exists('Cash', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cash']['Transaction_Amount'] : '0' ?>" onblur="InputMustBeAtleastN(this, 0);" />
                                                                            <div class="input-group-btn-vertical">
                                                                                <button class="btn btn-default more" type='button'><i class="fa fa-caret-up"></i></button>
                                                                                <button class="btn btn-default" type='button'><i class="fa fa-caret-down"></i></button>
                                                                            </div>
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('type'); ?></span></td>
                                                                    <td style="text-align:center">
                                                                        <input class="cash_account full-width" id="cash_account" name="cash_account" type="hidden"  value="<?php echo ($IsEdit && array_key_exists('Cash', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cash']['Account_ID'] : smc_session()['user_accounts']['cash_account_id'] ?>" data-select-name='<?php echo ($IsEdit && array_key_exists('Cash', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cash']['P_Name'] : smc_session()['user_accounts']['c_name'] ?>' />
                                                                    </td>
                                                                </tr>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                    <div id="SetPaidFormTab_2" class="tab-pane fade in">
                                                        <table class="table" cellpadding="0" cellspacing="0">
                                                            <tbody>
                                                                <tr>
                                                                    <td style="width: 65%;"><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('amount'); ?></span></td>
                                                                    <td>
                                                                        <div class="input-group InputSpinner" style="width:120px">
                                                                            <input type="text" class="form-control" value="<?php echo ($IsEdit && array_key_exists('Cheque', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cheque']['Transaction_Amount'] : "0" ?>" onblur="InputMustBeAtleastN(this, 0);" />
                                                                            <div class="input-group-btn-vertical">
                                                                                <button class="btn btn-default more" type='button'><i class="fa fa-caret-up"></i></button>
                                                                                <button class="btn btn-default" type='button'><i class="fa fa-caret-down"></i></button>
                                                                            </div>
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('Type'); ?></span></td>
                                                                    <td style="text-align:center">
                                                                        <input class="check_account full-width" id="check_account" name="check_account" type="hidden" value="<?php echo ($IsEdit && array_key_exists('Cheque', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cheque']['Account_ID'] : smc_session()['user_accounts']['cheque_account_id'] ?>" data-select-name='<?php echo ($IsEdit && array_key_exists('Cheque', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cheque']['P_Name'] : "" ?>' />
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"> <?php print CommonLanguage::getMessage('check'); ?>#</span></td>
                                                                    <td style="text-align:center"><input type="text" class="form-control CheckNumValue" value="<?php echo ($IsEdit && array_key_exists('Cheque', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cheque']['check_nb'] : '' ?>" /></td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"> <?php print CommonLanguage::getMessage('check_due_date'); ?></span></td>
                                                                    <td style="text-align:center"><input type="text" class="form-control check_due_date" value="<?php echo ($IsEdit && array_key_exists('Cheque', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cheque']['due_date'] : '' ?>"/></td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"> <?php print CommonLanguage::getMessage('value_date'); ?></span></td>
                                                                    <td style="text-align:center"><input type="text" class="form-control value_date" value="<?php echo ($IsEdit && array_key_exists('Cheque', $edit_arr['Payment'])) ? $edit_arr['Payment']['Cheque']['value_date'] : '' ?>"/></td>
                                                                </tr>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                    <div id="SetPaidFormTab_3" class="tab-pane fade in">
                                                        <table class="table" cellpadding="0" cellspacing="0">
                                                            <tbody>
                                                                <tr>
                                                                    <td style="width: 65%;"><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('amount'); ?></span></td>
                                                                    <td>
                                                                        <div class="input-group InputSpinner" style="width:120px">
                                                                            <input type="text" class="form-control" value="<?php echo ($IsEdit && array_key_exists('Credit_Card', $edit_arr['Payment'])) ? $edit_arr['Payment']['Credit_Card']['Transaction_Amount'] : "" ?>" onblur="InputMustBeAtleastN(this, 0);" />
                                                                            <div class="input-group-btn-vertical">
                                                                                <button class="btn btn-default more" type='button'><i class="fa fa-caret-up"></i></button>
                                                                                <button class="btn btn-default" type='button'><i class="fa fa-caret-down"></i></button>
                                                                            </div>
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <tr>
                                                                    <td><span class="SpanInTableInPayment"><?php print CommonLanguage::getMessage('Type'); ?></span></td>
                                                                    <td style="text-align:center">
                                                                        <input class="credit_account full-width" id="credit_account" name="credit_account" type="hidden"  value="<?php echo ($IsEdit && array_key_exists('Credit_Card', $edit_arr['Payment'])) ? $edit_arr['Payment']['Credit_Card']['Account_ID'] : "" ?>" data-select-name='<?php echo ($IsEdit && array_key_exists('Credit_Card', $edit_arr['Payment'])) ? $edit_arr['Payment']['Credit_Card']['P_Name'] : "" ?>' />
                                                                    </td>
                                                                </tr>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-sm-3 col-sm-height col-middle clearfix " style="text-align:center">
                                <div  class="col-md-12" style="text-align: left;display: inline-block;">
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold" ><?php print CommonLanguage::getMessage('vat_ten'); ?><input class="form-control ignore" readonly id="InvoiceVAT" value="<?php echo $IsEdit ? $edit_arr['main']['total_vat'] : '' ?>"/> </h5>
                                </div>
                                <div  class="col-md-12" style="text-align: left;display: inline-block;">
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold" > <?php print CommonLanguage::getMessage('discount_percent'); ?><input type="text" class="form-control ignore "  id="discount_percent" value="<?php echo $IsEdit ? $edit_arr['main']['discount_percent'] : 0 ?>"/></h5>
                                </div>
                                <div  class="col-md-12" style="text-align: left;display: inline-block;">
                                    <h5 class="font-montserrat all-caps small no-margin hint-text bold" > <?php print CommonLanguage::getMessage('discount_amount'); ?><input type="text" class="form-control ignore "  id="discount_amount" value="<?php echo $IsEdit ? $edit_arr['main']['discount_amount'] : 0 ?>"/></h5>
                                </div>

                            </div>
                            <div class="col-sm-3 text-right bg-menu col-sm-height padding-15" style="text-align:left !important">
                                <div style="text-align: left;display: inline-block;">
                                    <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="overall_total"><?php echo $IsEdit ? $edit_arr['main']['net_total'] : 0; ?></span></h1>
                                    <h5 class="font-montserrat all-caps small no-margin hint-text text-white bold"><?php print CommonLanguage::getMessage('overall_total'); ?></h5>
                                    <h1 class="no-margin text-white Total"><span class="CurrencyIndicator"></span>&nbsp;<span id="overall_total_after_discount"><?php echo $IsEdit ? $edit_arr['main']['net_total'] : 0; ?></span></h1>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="container-sm-height" >
                        <button class=" btn btn-primary btn-cons m-b-10 pull-right " id="InvoiceSubmitButton" 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:253px;" type="button">
                            <i class="fa fa-print"></i>
                            <span class="bold"><?php print CommonLanguage::getMessage('print'); ?></span>
                        </button>
                    </div>
                    <hr>
                </div>
            </div>
        </div>
    </div>
</form>

<script>
    var RequiredField = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
            Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            max_discount = <?php echo json_encode(smc_session()['user_accounts']['max_discount']); ?>,
            ignore_zero_item_disc = <?php echo json_encode(smc_session()['default_setting']['ignore_zero_item_disc']) ?>,
            IsEditMode = <?php echo $IsEdit ? "true" : "false"; ?>,
            ID_Edit = IsEditMode ? <?php echo json_encode($id); ?> : '',
            is_actual = <?php echo $is_actual ? "true" : "false"; ?>,
            local_currency = <?php echo json_encode(smc_session()['local_currency']); ?>,
            inv_nb = <?php echo json_encode(CommonLanguage::getMessage('invoice_nb')); ?>;
    var overall_total = 0, bon_total = 0, total_vat = 0, bon_vat = 0, prod_total = 0, prod_vat = 0, percent_flag = 0;
    $(function () {
//        $('#customerCouponForm').on('focus', 'input[type=number]', function (e) {
//            $(this).on('mousewheel.disableScroll', function (e) {
//                e.preventDefault()
//            });
//        });

        build_select2($("#search_customer"), ("xhr/customerSearch") + (IsEditMode ? "?is_edited=" + $("#search_customer").val() : "?Status_ID=1"))
        build_select2($(".Depot_Loc"), "xhr/depotSearch")
        build_select2($("#job_id"), "ACCAjax/JobSearch")
        build_select2($("#cash_account"), ("xhr/accIDSearch?type=cash"))
        build_select2($("#check_account"), ("xhr/accIDSearch?type=check"))
        build_select2($("#credit_account"), ("xhr/accIDSearch?type=credit_card"))

        build_select2($("#bone_type_id"), "xhr/CommonSearch?col_id=bone_type_id&col_name=bone_type_name&table=tbl_bone_type")
        build_select2($("input.bone_product_id,input.inv_product_id"), ("xhr/ProductSearch"));
        build_select2($("input.uom_id"), "xhr/productuomSearch?pid=" + $("input.inv_product_id").val())
        $(".check_due_date,.value_date,.bone_date,#invoice_date").datepicker({autoclose: true});
        $("#search_customer").on('change', function () {
            build_select2($("#customer_coupons_search"), ("xhr/customerCouponSearch?customer_id=" + $(this).val()))
        });
        build_select2($("#customer_coupons_search"), ("xhr/customerCouponSearch?customer_id=" + $("#search_customer").val()))
        $('#customer_coupons_search').on('change', function () {
            window.location = 'Inventory/customer_coupons/' + $(this).val()
        })
        $(".bone-div").on("click", " .fa-plus-circle", function (e) {
            //        $(".bone-div  .fa-minus-circle").css("display", "inline-block")
            var Parent = $(this).parents(".bone-row"), NewItem = Parent.clone().insertAfter(Parent);
            NewItem.find("input").val('');
            NewItem.find(".select2-container").remove()
            NewItem.find("input.bone_date").datepicker({autoclose: true});
            NewItem.find("input.bone_product_id").val('').attr("data-select-name", "");
            build_select2(NewItem.find("input.bone_product_id"), ("xhr/ProductSearch"))
            $(".select2-container", NewItem).show()
        })
        $(".bone-div").on("click", ".fa-minus-circle", function (e) {
            if ($(".bone-row").length == 1) {
                var parent = $(this).parents('.bone-row');
                $('input', parent).val('');
                $('input.bone_product_id', parent).trigger('change');
                parent.attr('total_changed', 0);
                parent.attr('disc_amount_changed', 0);
                $(percent_flag == 2 ? "#discount_amount" : "#discount_percent").trigger("keyup")
                update_bon_total()
                return;
            }
            $(this).closest(".bone-row").empty().remove();
            $(percent_flag == 2 ? "#discount_amount" : "#discount_percent").trigger("keyup")
            update_bon_total()
        });
        $(".bone-div").on("change", ".bone_product_id", function () {
            var row = $(this).parents('.bone-row');
            checkProductPrice(row)

        });
        $(".bone-div").on("changeDate", ".bone_date", function () {
            var row = $(this).parents('.bone-row');
            checkProductPrice(row);
        });
        $(".bone-div").on("change", ".liters,.bone_unit_price,.bone_vat_percent,.bone_vat,.bone-total,.bone_discount_percent,.bone_discount_amount", function () {
                  var  mytr = $(this).parents(".bone-row");
                  mytr.find(".bone_unit_price").val(public_round_number(mytr.find(".bone_unit_price").val()))

                mytr.find(".bone_vat_percent").val(public_round_number(mytr.find(".bone_vat_percent").val()))

                mytr.find(".bone_vat").val(public_round_number(mytr.find(".bone_vat").val()))

                mytr.find(".bone-total").val(public_round_number(mytr.find(".bone-total").val()))
                mytr.find(".bone_discount_percent").val(public_round_number(mytr.find(".bone_discount_percent").val()))
                mytr.find(".bone_discount_amount").val(public_round_number(mytr.find(".bone_discount_amount").val()))


        });

        $(".bone-div").on("keyup", ".liters,.bone_unit_price,.bone_vat_percent,.bone_vat,.bone-total,.bone_discount_percent,.bone_discount_amount", function () {
            var unit_price = parseFloat($(this).parents(".bone-row").find(".bone_unit_price").val() || 0),
                    mytr = $(this).parents(".bone-row");
            mytr.attr("total_changed", 0)
            mytr.attr("disc_amount_changed", 0)
            if ($(this).hasClass("bone_discount_amount")) {
                var discount_amount = parseFloat($(this).val() || 0),
                        qty = parseFloat(mytr.find(".liters").val()),
                        discount_percent = (discount_amount / (unit_price * qty) * 100);
                mytr.find(".bone_discount_percent").val(discount_percent)
                mytr.attr("disc_amount_changed", 1)
            }
            if ($(this).hasClass("bone-total")) {
                var myval = parseFloat($(this).val() || 0),
                        vat_percent = parseFloat(mytr.find(".bone_vat_percent").val()) || 0,
                        vat_amount = myval * (vat_percent / 100) / (1 + (vat_percent / 100)),
                        total = myval - vat_amount;
                $(this).attr("bone-total", myval)
                mytr.attr("total_changed", 1)
                mytr.find(".bone_vat").val(public_round_number(vat_amount))
                $(this).parents(".bone-row").find(".liters").val((total / unit_price))
            }
            $(percent_flag == 2 ? "#discount_amount" : "#discount_percent").trigger("keyup")
            update_bon_total()
        });
        $(".prod-div").on("click", " .fa-plus-circle", function (e) {
            //        $(".prod-div  .fa-minus-circle").css("display", "inline-block")
            var Parent = $(this).parents(".prod-row"), NewItem = Parent.clone().insertAfter(Parent);
            NewItem.find("input").val('');
            NewItem.find(".select2-container").remove()
            NewItem.find("input.inv_product_id,input.uom_id").val('').attr("data-select-name", "");
            build_select2(NewItem.find("input.inv_product_id"), ("xhr/ProductSearch"))
            build_select2(NewItem.find("input.uom_id"), "xhr/productuomSearch?pid=" + NewItem.find("input.inv_product_id").val())
            $(".select2-container", NewItem).show()
        })
        $(".prod-div").on("click", ".fa-minus-circle", function (e) {
            if ($(".prod-row").length == 1) {
                var parent = $(this).parents('.prod-row');
                $('input', parent).val('');
                $('input.inv_product_id', parent).trigger('change');
                $('input.uom_id', parent).trigger('change');
                parent.attr('total_changed', 0)
                parent.attr('disc_amount_changed', 0)
                $('span.prod-total', parent).html('');
                $('span.prod-total', parent).attr('prod-total', 0);
                $(percent_flag == 2 ? "#discount_amount" : "#discount_percent").trigger("keyup")
                update_prod_total()
                return;
            }
            $(this).closest(".prod-row").empty().remove();
            $(percent_flag == 2 ? "#discount_amount" : "#discount_percent").trigger("keyup")
            update_prod_total()
        })
        $(".prod-div").on("change", "input.inv_product_id", function () {
            var row = $(this).parents(".prod-row");
            row.find(".prod_unit_price").val('')
            row.find("input.uom_id").val('').attr("data-select-name", "")
            build_select2(row.find("input.uom_id"), "xhr/productuomSearch?pid=" + $(this).val())
            $.ajax({
                url: "InventoryAjax/get_product_by_id",
                data: {pid: $(this).val()},
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        $(".prod_vat_percent", row).val(v1.responseJSON['Product_VAT'] ? v1.responseJSON['vat_percent'] : '')
                        //                    update_prod_total()
                    }
                }
            })
        });
        $(".prod-div").on("keyup", ".prod_unit_price,.prod_vat_percent,.prod_vat,.prod_qty,.prod_disc_amount,.prod_disc_percent", function () {
            var unit_price = parseFloat($(this).parents(".prod-row").find(".prod_unit_price").val() || 0),
                    mytr = $(this).parents(".prod-row");
            mytr.attr("total_changed", 0)
            mytr.attr("disc_amount_changed", 0)
            if ($(this).hasClass("prod_disc_amount")) {
                var discount_amount = parseFloat($(this).val() || 0),
                        qty = parseFloat(mytr.find(".prod_qty").val()),
                        discount_percent = (discount_amount / (unit_price * qty) * 100);
                mytr.find(".prod_disc_percent").val(discount_percent)
                mytr.attr("disc_amount_changed", 1)
            }
            var myval = parseFloat($(this).val() || 0),
                    vat_percent = parseFloat(mytr.find(".prod_vat_percent").val()) || 0,
                    vat_amount = myval * (vat_percent / 100) / (1 + (vat_percent / 100)),
                    total = myval - vat_amount;
            mytr.find(".prod_vat").val(public_round_number(vat_amount))
            $(percent_flag == 2 ? "#discount_amount" : "#discount_percent").trigger("keyup")
            update_prod_total();
        });
        $(".prod-div").on("change", ".prod_unit_price,.prod_vat_percent,.prod_vat,.prod_qty,.prod_disc_amount,.prod_disc_percent", function () {
                 var   mytr = $(this).parents(".prod-row");
                 mytr.find(".prod_unit_price").val(public_round_number(mytr.find(".prod_unit_price").val()))

                mytr.find(".prod_vat_percent").val(public_round_number(mytr.find(".prod_vat_percent").val()))

                mytr.find(".prod_vat").val(public_round_number(mytr.find(".prod_vat").val()))

                mytr.find(".prod_disc_amount").val(public_round_number(mytr.find(".prod_disc_amount").val()))
                mytr.find(".prod_disc_percent").val(public_round_number(mytr.find(".prod_disc_percent").val()))


        });

        $(".prod-div").on("change", "input.uom_id", function () {
            var row = $(this).parents('.prod-row');
            $.ajax({
                url: "InventoryAjax/get_prod_price",
                data: {uom: $(this).val(), pid: $("input.inv_product_id", row).val()},
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        $(".prod_unit_price", row).val(v1.responseJSON)
                        update_prod_total()
                    }
                }
            })
        })
        $("#InvoiceSubmitButton").on("click", function () {
            if (!$("#customerCouponForm").valid()) {
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
            var data = {
                customer_id: $("#search_customer").val(),
                bone_type_id: $("#bone_type_id").val(),
                depot_id: $("#Depot_Loc").val(),
                current_rate: $("#current_rate").val(),
                currency_id: $("#Currency_ID").val(),
                invoice_date: $("#invoice_date").val(),
                is_actual: is_actual ? 1 : 0,
                auto_id: ID_Edit,
                invoice_vat: $("#InvoiceVAT").val(),
                overall_total: $("#overall_total_after_discount").html().replace(/,/g, ""),
                discount_percent: $('#discount_percent').val(),
                discount_amount: $('#discount_amount').val(),
                description: $("#invoice_note").val(),
                Cash_Amount: $("#SetPaidFormTab_1 .InputSpinner > input").eq(0).val(),
                Cash_Account: $("#cash_account").val(),
                Check_Amount: $("#SetPaidFormTab_2 .InputSpinner > input").eq(0).val(),
                Check_Account: $("#check_account").val(),
                Card_Amount: $("#SetPaidFormTab_3 .InputSpinner > input").eq(0).val(),
                Card_Account: $("#credit_account").val(),
                check_due_date: $(".check_due_date").val(),
                value_date: $(".value_date").val(),
                Check_Num: $("#SetPaidFormTab_2 .CheckNumValue").eq(0).val(),
                Card_Code: $("#SetPaidFormTab_3 .CardApproval").eq(0).val(),
                Net_Total: $("#overall_total_after_discount").html().replace(/,/g, ""),
                Sub_Total: parseFloat($("#overall_total").html().replace(/,/g, "")) - parseFloat($('#InvoiceVAT').val()),
                job_id: $("#job_id").val(),
                coupon: [],
                product: []
            };
            var is_negative_value = false;
            validate = true
            $(".bone-row").each(function () {
                if (parseFloat($("input.bone_discount_percent", $(this)).val()) > 100) {
                    validate = false;
                    $("input.bone_discount_percent", $(this)).addClass("wrong")
                } else {
                    $("input.bone_discount_percent", $(this)).removeClass("wrong")
                }
                $("div.bone_product_id .select2-chosen", $(this)).removeClass("wrong")
                if (parseFloat($("input.liters ", $(this)).val()) < 0 || parseFloat($("input.bone_unit_price ", $(this)).val()) < 0 || parseFloat($("input.bone_discount_percent ", $(this)).val()) < 0 || parseFloat($("input.bone_discount_amount ", $(this)).val()) < 0 || parseFloat($("input.bone_vat_percent ", $(this)).val()) < 0 || parseFloat($("input.bone_vat ", $(this)).val()) < 0 || parseFloat($("input.bone-total ", $(this)).attr('bone-total')) < 0) {
                    is_negative_value = true;
                }

                if ($("input.bone_product_id ", $(this)).val() != '' && $('input.bone_date', $(this)).val() != ''
                        && $("input.liters ", $(this)).val() != '' && $("input.bone_unit_price ", $(this)).val() != ''
                        && $("input.liters ", $(this)).val() != 0 && $("input.bone_unit_price ", $(this)).val() != 0) {
                    data.coupon.push({
                        product_id: $("input.bone_product_id", $(this)).val(),
                        bone_date: $("input.bone_date ", $(this)).val(),
                        liters: $("input.liters ", $(this)).val(),
                        unit_price: $("input.bone_unit_price", $(this)).val(),
                        coupon_number: $("input.coupon_number", $(this)).val(),
                        bone_note: $("input.bone_note", $(this)).val(),
                        vat: $(this).find(".bone_vat").val(),
                        vat_percent: $(this).find(".bone_vat_percent").val(),
                        disc_percent: $("input.bone_discount_percent", $(this)).val() || 0,
                        disc_amount: $("input.bone_discount_amount", $(this)).val() || 0,
                        total: $(this).find(".bone-total").attr("bone-total")
                    })
                } else if ($("input.bone_unit_price", $(this)).val() != '' && $("input.bone_unit_price", $(this)).val() != 0
                        && $("input.liters ", $(this)).val() != ''
                        && $("input.liters ", $(this)).val() != 0) {

                    if ($("input.bone_product_id ", $(this)).val() == '' || $("input.bone_product_id ", $(this)).val() == 0)
                        $("div.bone_product_id .select2-chosen ", $(this)).addClass("wrong")
                    validate = false;
                }
            });
            console.log(validate)
            $(".prod-row").each(function () {
                if (parseFloat($("input.prod_disc_percent", $(this)).val()) > 100) {
                    validate = false;
                    $("input.prod_disc_percent", $(this)).addClass("wrong")
                } else {
                    $("input.prod_disc_percent", $(this)).removeClass("wrong")
                }
                $("div.inv_product_id .select2-chosen,div.uom_id .select2-chosen ", $(this)).removeClass("wrong")
                if (parseFloat($("input.prod_qty ", $(this)).val()) < 0 || parseFloat($("input.prod_unit_price ", $(this)).val()) < 0 || parseFloat($("input.prod_disc_percent ", $(this)).val()) < 0 || parseFloat($("input.prod_disc_amount ", $(this)).val()) < 0 || parseFloat($("input.prod_vat_percent ", $(this)).val()) < 0 || parseFloat($("input.prod_vat ", $(this)).val()) < 0 || parseFloat($("span.prod-total ", $(this)).attr('prod-total')) < 0) {
                    is_negative_value = true;
                }

                if ($("input.inv_product_id", $(this)).val() != '' && $("input.prod_qty ", $(this)).val() != ''
                        && $("input.prod_qty ", $(this)).val() != 0 && $("input.prod_unit_price", $(this)).val() != 0
                        && $("input.uom_id ", $(this)).val() != '' && $("input.prod_unit_price", $(this)).val() != '') {
                    data.product.push({
                        product_id: $("input.inv_product_id", $(this)).val(),
                        qty: $("input.prod_qty ", $(this)).val(),
                        uom_id: $("input.uom_id", $(this)).val(),
                        unit_price: $("input.prod_unit_price", $(this)).val(),
                        disc_percent: $("input.prod_disc_percent", $(this)).val() || 0,
                        disc_amount: $("input.prod_disc_amount", $(this)).val() || 0,
                        desc: $("input.prod_desc", $(this)).val(),
                        vat: $(this).find(".prod_vat").val() || 0,
                        vat_percent: $(this).find(".prod_vat_percent").val() || 0,
                        total: $(this).find(".prod-total").attr("prod-total")
                    });
                } else if ($("input.prod_unit_price", $(this)).val() != '' && $("input.prod_qty ", $(this)).val() != ''
                        && $("input.prod_qty ", $(this)).val() != 0 && $("input.prod_unit_price", $(this)).val() != 0) {
                    if ($("input.uom_id ", $(this)).val() == '' || $("input.uom_id ", $(this)).val() == 0)
                        $("div.uom_id .select2-chosen ", $(this)).addClass("wrong")
                    if ($("input.inv_product_id ", $(this)).val() == '' || $("input.inv_product_id ", $(this)).val() == 0)
                        $("div.inv_product_id .select2-chosen ", $(this)).addClass("wrong")
                    validate = false;
                }
            });
            if (is_negative_value) {
                $("#PurchaseSuccess").attr("class", "alert alert-warning").html('<?php echo CommonLanguage::getMessage('negative_value'); ?>');
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
            if ((data.coupon.length == 0 && data.product.length == 0) || !validate) {
                $("#PurchaseSuccess").attr("class", "alert alert-warning").html('<?php echo CommonLanguage::getMessage('choose_entry'); ?>');
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
            if (parseFloat($("#SetPaidFormTab_1 .InputSpinner > input").eq(0).val()) > parseFloat($("#overall_total_after_discount").html().replace(/,/g, ""))) {
                $("#PurchaseSuccess").attr("class", "alert alert-danger").html('<?php echo CommonLanguage::getMessage('paid_amount_less_total'); ?>');
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
            $.ajax({
                url: IsEditMode ? "InventoryAjax/editCustomerCoupon" : "InventoryAjax/addCustomerCoupon",
                method: "POST",
                data: data,
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == "success") {
                        if (v1.responseJSON[0] == 'OK') {
                            //                            if (!IsEditMode) {
                            Invoice_ID = v1.responseJSON[1];
                            $("#PrintBtn").removeClass("disabled")
                            //                            }
                            $("#PurchaseSuccess").attr("class", "alert alert-success").html(Submitted_Successfully + '&nbsp;<strong>' + inv_nb + ' ' + v1.responseJSON[1] + '</strong>')

                            $("#InvoiceSubmitButton").attr("disabled", "disabled")
                        } else {
                            $("#PurchaseSuccess").attr("class", "alert alert-danger").html(v1.responseJSON[0])
                        }
                    } else {
                        $("#PurchaseSuccess").attr("class", "alert alert-danger").html(Failed_Submit)
                    }
                    $(document.body).animate({scrollTop: 0}, 800)
                    $("#PurchaseDisabler").hide();
                }
            });
        });
        $("#PrintBtn").on("click", function () {
            var myurl = "Inventory/view_customer_coupon/" + Invoice_ID;
            printExternal(myurl)
        });
        $("#discount_percent").on(" keyup", function () {
            percent_flag = 1;
            check_discount($(this), max_discount)
            $("#discount_amount").val(overall_total * (parseFloat($(this).val()) / 100) || 0)
            update_overall_total()
        });
        $("#discount_amount").on("keyup", function () {
            percent_flag = 2;
            if (parseFloat($(this).val()) > (overall_total * max_discount / 100))
                $(this).val((overall_total * max_discount / 100));
            $("#discount_percent").val((parseFloat($(this).val()) / overall_total * 100) || 0);
            update_overall_total()
        })
        $("#discount_amount,#discount_percent").on("change", function () {
            $("#discount_amount").val(public_round_number($("#discount_amount").val()));
            $("#discount_percent").val(public_round_number($("#discount_percent").val()));
            update_overall_total()

        })

        if (IsEditMode) {
            update_bon_total()
            update_prod_total()
            update_overall_total()
        }
    });
    function checkProductPrice(row) {
        $.ajax({
            url: "InventoryAjax/get_prod_default_price",
            data: {pid: $('input.bone_product_id', row).val(), bone_date: $('input[name=bone_date]', row).val()},
            dataType: 'json',
            complete: function (v1, v2) {
                if (v2 == "success") {
                    $(".bone_unit_price", row).val(v1.responseJSON).trigger('keyup')
                    //                    update_bon_total()
                }
            }
        })
    }
    function update_prod_total() {
        prod_total = 0;
        prod_vat = 0;
        $(".prod-row").each(function () {
            var qty = parseFloat($(".prod_qty", $(this)).val() || 0),
                    unit_price = parseFloat($(".prod_unit_price", $(this)).val() || 0),
                    disc_percent = parseFloat($(".prod_disc_percent", $(this)).val() || 0),
                    disc_amount = parseFloat(qty * unit_price * disc_percent / 100),
                    vat_percent = parseFloat($(".prod_vat_percent", $(this)).val() || 0),
                    vat_amount = (((qty * unit_price) - disc_amount) * vat_percent / 100),
                    total = (qty * unit_price * (100 - disc_percent) / 100) + vat_amount;
            prod_total += total;
            prod_vat += vat_amount;
            if ($(this).attr("disc_amount_changed") == 0) {
                $(".prod_disc_amount", $(this)).val(disc_amount)
            }
            $(".prod_vat", $(this)).val(vat_amount)
            $(".prod-total", $(this)).html(AddCommas(public_round_number(total))).attr("prod-total", total)
        })
        update_overall_total()
    }

    function update_bon_total() {
        bon_total = 0;
        bon_vat = 0;
        $(".bone-row").each(function () {
            var liters = parseFloat($(".liters", $(this)).val() || 0),
                    unit_price = parseFloat($(".bone_unit_price", $(this)).val() || 0),
                    disc_percent = parseFloat($(".bone_discount_percent", $(this)).val() || 0),
                    disc_amount = liters * unit_price * disc_percent / 100,
                    vat_percent = parseFloat($(".bone_vat_percent", $(this)).val() || 0),
                    vat_amount = (((liters * unit_price) - disc_amount) * vat_percent / 100),
                    total = (liters * unit_price * (100 - disc_percent) / 100) + vat_amount;
            //console.log(vat_amount)
            bon_total += total;
            bon_vat += vat_amount;
            $(".bone_vat", $(this)).val(vat_amount)
            if ($(this).attr("disc_amount_changed") == 0) {
                $(".bone_discount_amount", $(this)).val(disc_amount)
            }
            if ($(this).attr("total_changed") == 0) {
                $(".bone-total", $(this)).val(total).attr("bone-total", total)
            }
        })
        update_overall_total()
    }
    function update_overall_total() {
        overall_total = bon_total + prod_total;
        total_vat = bon_vat + prod_vat;
        $("#overall_total").html(AddCommas(public_round_number(overall_total)))
        $("#InvoiceVAT").val(public_round_number(total_vat))
        if (percent_flag == 1) {
            $("#discount_amount").val(public_round_number(overall_total * (parseFloat($("#discount_percent").val()) / 100)) || 0)
        }
        if (percent_flag == 2) {
            $("#discount_percent").val(public_round_number(parseFloat($("#discount_amount").val()) / overall_total * 100) || 0)
        }
        var overall_total_after_discount = overall_total - parseFloat($("#discount_amount").val() || 0)
        $('#overall_total_after_discount').html(AddCommas(public_round_number(overall_total_after_discount)))
    }
    function check_discount(me, item_disc) {
        if (item_disc > 0 || ignore_zero_item_disc != 1) {
            if (parseFloat(me.val()) > Math.min(parseFloat(max_discount), item_disc))
                me.val(Math.min(parseFloat(max_discount), item_disc))
        } else if (parseFloat(me.val()) > parseFloat(max_discount))
            me.val(parseFloat(max_discount))

    }
</script>
