<?php 
$isEdit = !empty($model->id);
$isActive = false;
if (!empty($expenseModels) && isset($expenseModels[0]->isActive)) {
    $isActive = ($expenseModels[0]->isActive == 'Y');
}

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

<div class="tab-content">
    <div class="tab-pane active">
        <ul class="clearfix form-ul material">
            <?php if (!$isEdit): ?>
            <li class="col-sm-6">
                <?php echo $form->textField($model, 'expense_date', array(
                    'class' => 'datepicker text-bold',
                    'data-label' => 'Expense Date',
                    'value' => $model->expense_date ? date('d-m-Y', strtotime($model->expense_date)) : date('d-m-Y')
                )); ?>
            </li>
            <?php endif; ?>

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

        <div class="table-responsive">
            <table class="table table-bordered" id="expense_table_modal">
                <thead>
                    <tr>
                        <th style="width:40px;">S.No</th>
                        <th>Expense Type</th>
                        <th>Description</th>
                        <th style="width:120px;">Amount</th>

                        <?php if (!$isEdit): ?>
                        <th class="text-center">
                            <button type="button" class="btn btn-xs btn-success" onclick="addExpenseRow()">
                                <i class="fa fa-plus"></i>
                            </button>
                        </th>
                        <?php endif; ?>
                    </tr>
                </thead>

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

                        <td>
                            <?php echo CHtml::dropDownList(
                                "Expense[$i][expense_type_id]",
                                isset($row->expense_type_id) ? $row->expense_type_id : '',
                                $expenseTypes,
                                array('class'=>'form-control','prompt'=>'Select Expense Type')
                            ); ?>
                        </td>

                        <td>
                            <?php echo CHtml::textField(
                                "Expense[$i][description]",
                                isset($row->description) ? $row->description : '',
                                array('class'=>'form-control','placeholder'=>'Enter description')
                            ); ?>
                        </td>

                        <td>
                         <?php echo CHtml::textField(
                            "Expense[$i][amount]",
                            isset($row->amount) ? $row->amount : '',
                            array(
                                'class'      => 'form-control text-right',
                                'style'      => 'width:120px; padding-right:5px;',
                                'onkeypress' => 'return isNumber(event)',
                                'oninput'    => 'allowOnlyNumberDecimal(this)'
                            )
                        ); ?>
                        </td>

                        <?php if (!$isEdit): ?>
                        <td class="text-center">
                            <button type="button" class="btn btn-xs btn-danger" onclick="removeExpenseRow(this)">
                                <i class="fa fa-times"></i>
                            </button>
                        </td>
                        <?php endif; ?>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <?php if (!($isEdit && $isActive)): ?>
    <?php
        $url = Yii::app()->createUrl('/expense/save');
        echo CHtml::ajaxSubmitButton('Save', $url, array(
            'dataType' => 'json',
            'type' => 'post',
            'beforeSend' => 'function(){
                if(window.expenseSubmitting){ return false; }
                window.expenseSubmitting = true;
                $("#loader").show();
                $(".expense-save-btn").prop("disabled", true).addClass("btn_loding").removeClass("btn-theme");
            }',
            'success' => 'function(data){
                $("#loader").hide();
                window.expenseSubmitting = false;
                $(".expense-save-btn").prop("disabled", false).removeClass("btn_loding").addClass("btn-theme");

                if(data.status=="success"){
                    t8.success(data.message || "Expense Saved Successfully!");

                    // Close modal
                    $(".modal").modal("hide");

                    // Reload full page
                    window.location.reload();
                } else {
                    t8.error(data.message || "Error while saving!");
                }
            }',
            'error' => 'function(){
                window.expenseSubmitting = false;
                $("#loader").hide();
                $(".expense-save-btn").prop("disabled", false).removeClass("btn_loding").addClass("btn-theme");
                t8.error("Something went wrong!");
            }'
        ), array('class'=>'expense-save-btn btn btn-theme'));
    ?>
    <?php endif; ?>
</div>

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

<!-- JAVASCRIPT -->
<script type="text/javascript">
function addExpenseRow() {
    var tbody = document.querySelector('#expense_table_modal tbody');
    var rowCount = tbody.rows.length;
    var row = tbody.rows[0].cloneNode(true);
    row.id = 'row_' + rowCount;

    var inputs = row.querySelectorAll('input, select');
    for (var i = 0; i < inputs.length; i++) {
        var name = inputs[i].getAttribute('name');
        if (name) {
            inputs[i].setAttribute('name', name.replace(/\d+/, rowCount));
        }
        if (!inputs[i].name.includes('[id]') && !inputs[i].name.includes('[expense_id]')) {
            inputs[i].value = '';
        } else {
            inputs[i].value = '';
        }
    }

    row.querySelector('input[name*="[serial_no]"]').value = rowCount + 1;
    tbody.appendChild(row);
}

function removeExpenseRow(btn) {
    var tbody = document.querySelector('#expense_table_modal tbody');
    if (tbody.rows.length > 1) {
        btn.closest('tr').remove();
        for (var i = 0; i < tbody.rows.length; i++) {
            tbody.rows[i].querySelector('input[name*="[serial_no]"]').value = i + 1;
        }
    } else {
        alert('At least one row is required');
    }
}

function isNumber(evt) {
    var charCode = evt.which ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) return false;
    return true;
}
function isNumber(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    // Allow: numbers (48-57), dot (46), backspace (8)
    if (
        (charCode >= 48 && charCode <= 57) || 
        charCode === 46 || 
        charCode === 8
    ) {
        return true;
    }
    return false;
}
function allowOnlyNumberDecimal(input) {
    let value = input.value;
    value = value.replace(/[^0-9.]/g, '');
    const parts = value.split('.');
    if (parts.length > 2) {
        value = parts[0] + '.' + parts.slice(1).join('');
    }
 
    input.value = value;
}
</script>
