<?php 
$isEdit   = !empty($model->id);
$isActive = ($model->isActive == 'Y');
$form = $this->beginWidget('CActiveForm', array(
    'id'                     => 'subcategory-form',
    'enableAjaxValidation'   => false,
    'enableClientValidation' => false,
)); 
?>

<div class="tab-content">
    <div class="tab-pane active">
        <ul class="clearfix form-ul material">

            <li class="col-sm-6">
                <?php echo $form->dropDownList(
                    $model,
                    'category_id',
                    $categories,
                    array(
                        'class'      => 'form-control',
                        'prompt'     => 'Select Category',
                        'data-label' => 'Category'
                    )
                ); ?>
            </li>

            <li class="col-sm-6">
                <?php echo $form->textField(
                    $model,
                    'sub_category_name',
                    array(
                        'class'       => 'form-control',
                        'data-label'  => 'Sub Category No',
                        'placeholder' => 'Enter Sub Category Number'
                    )
                ); ?>
            </li>

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

        <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-subcategory">Save</button>
        </div>
    </div>
</div>

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

<script>
$('#btn-save-subcategory').off('click').on('click', function () {

    var $btn = $(this);

    // Prevent multiple clicks
    if ($btn.data('sending')) return;
    $btn.data('sending', true);
    $btn.prop('disabled', true).text('Saving...');

    var formData = $('#subcategory-form').serialize();

    $('#loader').show();

    $.ajax({
        type    : 'POST',
        url     : '<?php echo Yii::app()->createUrl("subcategory/Save") ?>',
        data    : formData,
        dataType: 'json',
        success : function (data) {
            $('#loader').hide();
            if (data.status === 'success') {
                t8.success('Sub Category Saved Successfully!');
                // Force DataTable reload first, then close modal
                reloadTable('#tbl_subcategory');
                setTimeout(function () {
                    $('.modal').modal('hide');
                }, 300);
            } else {
                t8.error(data.message);
            }
        },
        error: function () {
            $('#loader').hide();
            t8.error('An unexpected error occurred. Please try again.');
        },
        complete: function () {
            // Re-enable button after request completes
            $btn.data('sending', false);
            $btn.prop('disabled', false).text('Save');
        }
    });
});
</script>