<?php 
$stateModels = isset($stateModels) ? $stateModels : array(new States());
?>

<?php
$isEdit = !empty($stateModels[0]->id);

$form = $this->beginWidget('CActiveForm', array(
    'id' => 'state-form',
    'enableAjaxValidation' => false,
    'enableClientValidation' => false,
)); 
?>

<div class="tab-content">
    <div class="tab-pane active">

        <?php echo $form->hiddenField($model, 'id'); ?>

        <div class="table-responsive">
            <table class="table table-bordered" id="state_table_modal">
                <thead>
                    <tr>
                        <th style="width:40px;">S.No</th>
                        <th>Country <span style="color:red;">*</span></th>
                        <th>State Name <span style="color:red;">*</span></th>
                    </tr>
                </thead>

                <tbody>
                    <?php 
                    $stateModels = isset($stateModels) ? $stateModels : array(new States());
                    foreach ($stateModels as $i => $row): ?>
                    <tr id="row_<?php echo $i; ?>">

                        <td>
                            <?php echo CHtml::hiddenField("States[$i][id]", isset($row->id) ? $row->id : ''); ?>
                            <?php echo CHtml::textField(
                                "States[$i][serial_no]",
                                $i + 1,
                                array('class'=>'form-control text-center','readonly'=>true,'style'=>'width:40px;')
                            ); ?>
                        </td>

                        <td>
                            <?php echo CHtml::dropDownList(
                                "States[$i][country_id]",
                                isset($row->country_id) ? $row->country_id : '',
                                $countryList,
                                array('class'=>'form-control state-country','prompt'=>'Select Country')
                            ); ?>
                        </td>

                        <td>
                            <?php echo CHtml::textField(
                                "States[$i][state_name]",
                                isset($row->state_name) ? $row->state_name : '',
                                array('class'=>'form-control state-name','placeholder'=>'Enter State Name')
                            ); ?>
                        </td>

                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="button" class="btn btn-theme" id="btn-save-state">Save</button>
</div>

<?php $this->endWidget(); ?>

<script>
$(document).ready(function(){

    $('#btn-save-state').off('click').on('click', function(){

        var btn = $(this);

        // Clear previous red borders
        $('#state_table_modal tbody tr .state-country, #state_table_modal tbody tr .state-name').css('border-color', '');

        // Client side validation — show red borders instantly
        var hasEmpty = false;
        $('#state_table_modal tbody tr').each(function(){
            var country = $(this).find('.state-country');
            var state   = $(this).find('.state-name');

            if(!country.val()){
                country.css('border', '1px solid red');
                hasEmpty = true;
            }
            if(!state.val()){
                state.css('border', '1px solid red');
                hasEmpty = true;
            }
        });

        if(hasEmpty){
            t8.error("Country and State Name are required!");
            return;
        }

        btn.prop('disabled', true);
        $("#loader").show();

        $.ajax({
            type: 'POST',
            url: '<?php echo Yii::app()->createUrl("state/save"); ?>',
            dataType: 'json',
            data: $('#state-form').serialize(),
            success: function(data){
                $("#loader").hide();
                btn.prop('disabled', false);

                if(data.status == "success"){
                    t8.success("State Saved Successfully!");
                    $(".x.close").click();
                    reloadTable("#tbl_state");
                } else {
                    // Server side red borders as fallback
                    $('#state_table_modal tbody tr').each(function(){
                        var country = $(this).find('.state-country');
                        var state   = $(this).find('.state-name');
                        if(!country.val()) country.css('border', '1px solid red');
                        if(!state.val())   state.css('border', '1px solid red');
                    });
                    t8.error(data.message || "Please fill all required fields!");
                }
            },
            error: function(xhr){
                $("#loader").hide();
                btn.prop('disabled', false);
                t8.error("Something went wrong.");
            }
        });

    });

    // Clear red border on input change
    $('#state_table_modal').on('change', '.state-country', function(){
        $(this).css('border', '');
    });

    $('#state_table_modal').on('input', '.state-name', function(){
        $(this).css('border', '');
    });

});
</script>