<div class="row">
    <div class="container">
        <ol class="breadcrumb">
            <li><a href="#">نظام المحاسبة</a></li>
            <li><a href="forms.php?do=show"> استمارات</a></li>
            <li class="active">اضافة</li>
        </ol>
        <div class="panel panel-default panel-m">
            <div class="panel-heading">
                <h3 class="panel-title">اضافة</h3>
            </div>
            <div class="panel-body"> {literal}
                <form class="nameToBeChecked form-horizontal" role="form" action="forms.php?do=add"
                      method="post" enctype="multipart/form-data" id="spform">
                    {/literal}

                    
                    

            
                    <!--==============================-->
                   <div class="form-group">
                        <label for="lawyer_id" class="col-lg-2 control-label"> المقاول</label>
                        <div class="col-lg-4">
                            <select name="member_name" id="member_name" class="form-control select2" required>
                                <option value="-1">--- اختر المقاول ---</option>
                                {foreach $showData as $data}
                                    <option value="{$data->id}">{$data->member_name}</option>
                                {/foreach}
                            </select>
                        </div>
                    </div>
                   <div class="form-group">
                        <label for="lawyer_id" class="col-lg-2 control-label">رقم القيد</label>
                        <div class="col-lg-4">
                            <select name="entry_no" id="entry_no" class="form-control select2" required>
                                <option value="-1">--- اختر القيد ---</option>
                                {foreach $entry as $entr}
                                    <option value="{$entr->entry_no}">{$entr->entry_no}</option>
                                {/foreach}
                            </select>
                        </div>
                    </div>
                    <!--==============================-->
                      <div class="form-group">
                        <label for="lawyer_id" class="col-lg-2 control-label">رقم الشيك </label>
                        <div class="col-lg-4">
                            <select name="checks[]" id="checks" multiple class="form-control select2" required >
                                <option value="-1">--- اختر الشيك ---</option>
                                {foreach $checks as $check}
                                    <option value="{$check.check_num}">{$check.check_num}</option>
                                {/foreach}
                            </select>
                        </div>
                    </div>
                    <!--==============================-->

                    <div class="form-group">
                        <label for="notes" class="col-lg-2 control-label">اجمالي قيمة حساب البنك</label>
                        <div class="col-lg-4">
                            <input type="number" name="total_bank_value" id="total_bank_value" class="form-control" oninput="validateChecksTotal()">
                        </div>
                        <span class="textfieldRequiredMsg">*</span>
                    </div>
                    <!--==============================-->
                    <div class="form-group">
                        <label for="court_decision" class="col-lg-2 control-label">نعليق</label>
                        <div class="col-lg-4">
                            <textarea name="comment" id="comment" class="form-control" rows="4" ></textarea>
                        </div>
                    </div>
                    <!--==============================-->
                    
                    <!--==============================-->
                    
                    <div class="form-group">
                        <label class="col-lg-2 control-label"> صورة الاستمارة</label>
                        <div class="col-lg-4">
                            <input type="file" name="image[]" id="image" multiple  accept=".jpg, .jpeg, .png, .pdf" />
                        </div>
                    </div>
                        <!-- =================================================   -->
                    <div class="form-group">
                        <div class="col-lg-offset-2 col-lg-4">
                            <button type="button" class="btn btn-primary pull-left" id="spbutton" disabled>حفظ</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

{literal}
<script type="text/javascript">
    var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1");
    var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2");
    
    $('#spbutton').live('click', function (e) {
        if (!$('#spbutton').hasClass("processing")) {
            $('#spbutton').addClass("processing");
            var myForm = document.getElementById("spform");
            var SS = Spry.Widget.Form.validate(myForm);
            if (SS == true) {
                myForm.submit();
            } else {
                $('#spbutton').removeClass("processing");
            }
        }
    });

    $(document).ready(function() {
        $('#nature').on('change', function() {
            if ($(this).val() === 'other') {
                $('#other_input_container').show();
            } else {
                $('#other_input_container').hide(); 
                $('#other_nature').val(''); 
            }
        });

        $(document).on('input', '.opponent-input', function() {
            let currentInput = $(this);
            let parentRow = currentInput.closest('.opponent-row');
            let nextRow = parentRow.next('.opponent-row');
            if (currentInput.val().trim() !== "") {
                nextRow.show(); 
            } else {
                if(nextRow.find('input').val() === "") {
                 nextRow.hide(); 
                }
            }
        });

        $('#checks').on('change.select2', function() {
            validateChecksTotal();
        });
    });

    async function validateChecksTotal() {
        const totalAmountInput = document.getElementById('total_bank_value');
        const saveButton = document.getElementById('spbutton');
        
        if (!totalAmountInput || !saveButton) return;

        const totalAmount = parseFloat(totalAmountInput.value) || 0;
        
        let selectedChecks = $('#checks').val() || [];
        
        selectedChecks = selectedChecks.filter(function(val) {
            return val !== "-1";
        });

        if (selectedChecks.length === 0 || totalAmount === 0) {
            saveButton.disabled = true;
            return;
        }

        try {
            const response = await fetch('forms.php?do=checkTotal', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ checks: selectedChecks })
            });

            const data = await response.json();
            const checksTotalFromDB = parseFloat(data.total_payments) || 0;

            if (checksTotalFromDB === totalAmount) {
                saveButton.disabled = false; 
            } else {
                saveButton.disabled = true;  
            }

        } catch (error) {
            console.error("حدث خطأ أثناء فحص الشيكات:", error);
            saveButton.disabled = true; 
        }
    }
</script>
{/literal}