<?php
$editId = isset($editId) ? $editId : 0;
$isEditMode = $editId > 0;
$title = $isEditMode ? 'Edit Customer Location' : 'Add New Customer Locations';
?>

<style>
body .modal-content { background: #fdf8f2 !important; border-radius: 12px !important; }
body .modal-header { background: linear-gradient(135deg, #0f1724, #182035) !important; color:#fff !important; }
body .form-table td { padding:10px; vertical-align:middle; }
.btn-add-main { display: <?php echo $isEditMode ? 'none' : 'inline-block'; ?> !important; }
.btn-remove { display: <?php echo $isEditMode ? 'none' : 'inline-block'; ?> !important; }
</style>

<?php
$form = $this->beginWidget('CActiveForm', array(
    'id' => 'customer-location-form',
    'enableAjaxValidation' => false,
    'enableClientValidation' => false,
));
?>

<input type="hidden" name="edit_id" value="<?php echo $editId; ?>">

<div class="modal-body">
    <h4 style="margin-bottom:20px;"><?php echo $title; ?></h4>
    
    <table class="table table-bordered form-table" id="customer-table">
        <thead>
            <tr>
                <th style="width:45%;">Customer</th>
                <th style="width:45%;">Location</th>
                <th style="width:10%; text-align:center;">
                    <button type="button" class="btn btn-success btn-add-main">+</button>
                </th>
            </tr>
        </thead>
        <tbody>
            <?php if ($isEditMode): ?>
                <?php 
                $existingData = CustomerLocations::model()->findByPk($editId);
                if ($existingData):
                ?>
                <tr class="data-row">
                    <td>
                        <?php echo CHtml::dropDownList(
                            'CustomerLocations[0][customer_id]',
                            $existingData->customer_id,
                            CHtml::listData(Customers::model()->findAll(array('condition'=>'isActive="Y"')), 'id', 'customer_name'),
                            array('class'=>'form-control')
                        ); ?>
                    </td>
                    <td>
                        <input type="text" 
                               name="CustomerLocations[0][customer_locations]" 
                               class="form-control" 
                               value="<?php echo CHtml::encode($existingData->customer_locations); ?>">
                    </td>
                    <td style="text-align:center;">
                        <!-- Hidden remove button in edit mode -->
                    </td>
                </tr>
                <?php endif; ?>
            <?php else: ?>
                <!-- ADD MODE first row -->
                <tr class="data-row">
                    <td>
                        <?php echo CHtml::dropDownList(
                            'CustomerLocations[0][customer_id]',
                            '',
                            CHtml::listData(Customers::model()->findAll(array('condition'=>'isActive="Y"')), 'id', 'customer_name'),
                            array('class'=>'form-control', 'prompt'=>'Select Customer')
                        ); ?>
                    </td>
                    <td>
                        <input type="text" name="CustomerLocations[0][customer_locations]" class="form-control" placeholder="Enter Location">
                    </td>
                    <td style="text-align:center;">
                        <button type="button" class="btn btn-danger btn-remove">x</button>
                    </td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>
</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-customer-location">
        <?php echo $isEditMode ? 'Update' : 'Save'; ?>
    </button>
</div>

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

<script>
$(document).ready(function() {
    window.customerRowIndex = $('#customer-table tbody tr').length;
    
    var isEditMode = $('input[name="edit_id"]').val() > 0;
    
    // Hide add/remove in edit mode
    if (isEditMode) {
        $('.btn-add-main, .btn-remove').hide();
    }
});

// ======================= ADD ROW =======================
$(document).off('click', '.btn-add-main').on('click', '.btn-add-main', function(){
    if ($('input[name="edit_id"]').val() > 0) return;
    
    var rowIndex = window.customerRowIndex;
    var newRow = `
        <tr class="data-row">
            <td>
                <select name="CustomerLocations[${rowIndex}][customer_id]" class="form-control">
                    <option value="">Loading...</option>
                </select>
            </td>
            <td>
                <input type="text" name="CustomerLocations[${rowIndex}][customer_locations]" class="form-control" placeholder="Enter Location">
            </td>
            <td style="text-align:center;">
                <button type="button" class="btn btn-danger btn-remove">x</button>
            </td>
        </tr>
    `;
    
    $('#customer-table tbody').append(newRow);
    populateCustomerDropdown($(`select[name="CustomerLocations[${rowIndex}][customer_id]"]`));
    window.customerRowIndex++;
});

function populateCustomerDropdown($select) {
    $select.html('<option value="">Loading...</option>');
    $.ajax({
        url: '<?php echo Yii::app()->createUrl("customerlocations/getCustomers"); ?>',
        type: 'GET',
        dataType: 'json',
        success: function(data) {
            $select.html('<option value="">Select Customer</option>');
            $.each(data, function(key, customer) {
                $select.append('<option value="' + customer.id + '">' + customer.customer_name + '</option>');
            });
        }
    });
}

// ======================= REMOVE ROW =======================
$(document).off('click', '.btn-remove').on('click', '.btn-remove', function(){
    if ($('input[name="edit_id"]').val() > 0) return;
    if ($('#customer-table tbody tr').length > 1) {
        $(this).closest('tr').remove();
    } else {
        alert('At least one row is required.');
    }
});

// ======================= SAVE =======================
$(document).off('click', '#btn-save-customer-location').on('click', '#btn-save-customer-location', function(){
    var btn = $(this);
    var originalText = btn.text();
    btn.prop('disabled', true).text('Saving...');

    // Client validation
    var isValid = true;
    $('#customer-table tbody tr').each(function() {
        var $select = $(this).find('select');
        var $input = $(this).find('input[type="text"]');
        var customerId = $select.val();
        var location = $input.val().trim();
        
        if (!customerId || !location) {
            isValid = false;
            alert('Please fill all fields.');
            return false;
        }
    });
    
    if (!isValid) {
        btn.prop('disabled', false).text(originalText);
        return;
    }

    $.ajax({
        type: 'POST',
        url: '<?php echo Yii::app()->createUrl("customerlocations/save"); ?>',
        data: $('#customer-location-form').serialize(),
        dataType: 'json',
        success: function(data){
            btn.prop('disabled', false).text(originalText);
            if(data.status === "success"){
                t8.success(data.message);
                if (typeof reloadTable === 'function') {
                    reloadTable("#tbl_CustomerLocations");
                }
                $('.modal').modal('hide');
            } else {
                t8.error(data.message || "Something went wrong.");
            }
        },
        error: function(){
            btn.prop('disabled', false).text(originalText);
            t8.error("Something went wrong.");
        }
    });
});
</script>
