@extends('layouts.app')

@section('content')
<div class="card">
    <div class="card-header">
        <div class="row align-items-center">
            <div class="col">
                <h5 class="mb-0">Edit Payroll Adjustment - {{ $payrollAdjustment->payrollGroup->name }}</h5>
            </div>
            <div class="col-auto d-flex align-items-center gap-2">
                <button type="button" class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#importModal">
                    <i class="bi bi-upload"></i> Import Data
                </button>
                <span class="badge bg-{{ $payrollAdjustment->status === 'pending' ? 'warning' : 'info' }}">
                    {{ ucfirst($payrollAdjustment->status) }}
                </span>
            </div>
        </div>
    </div>
    <div class="card-body">
        <!-- Period Info -->
        <div class="row g-3 mb-4">
            <div class="col-md-3">
                <label class="form-label"><strong>From:</strong></label>
                <input type="text" class="form-control" value="{{ $payrollAdjustment->date_from->format('Y-m-d') }}" readonly>
            </div>
            <div class="col-md-3">
                <label class="form-label"><strong>To:</strong></label>
                <input type="text" class="form-control" value="{{ $payrollAdjustment->date_to->format('Y-m-d') }}" readonly>
            </div>
        </div>

        <!-- Employee Selection -->
        <div class="row g-3 mb-4">
            <div class="col-md-12">
                <label class="form-label"><strong>Select Employee:</strong></label>
                <select id="employee-select" class="form-select">
                    <option value="">-- Select Employee --</option>
                    @foreach($employees as $employee)
                        <option value="{{ $employee->id }}">{{ $employee->display_text }}</option>
                    @endforeach
                </select>
            </div>
        </div>

        <!-- Additions and Deductions Side by Side -->
        <div class="row" id="adjustment-section" style="display: none;">
            <!-- Additions Section -->
            <div class="col-md-6">
                <div class="d-flex justify-content-between align-items-center mb-2">                    
                    <div class="col">
                        <h5 class="mb-0">Additions</h5>
                    </div>
                    <div class="col-auto">
                        <button type="button" class="btn btn-success btn-sm" onclick="addAdditionRow()">
                            Add Addition
                        </button>
                    </div>
                </div>
                <div class="table-responsive" style="max-height: 400px; overflow-y: auto;">
                    <table class="table table-sm table-bordered">
                        <thead class="table-light">
                            <tr>
                                <th width="50%">Addition Name</th>
                                <th width="35%">Amount</th>
                                <th width="15%">Action</th>
                            </tr>
                        </thead>
                        <tbody id="additions-tbody">
                            <tr>
                                <td colspan="3" class="text-center text-muted">No additions added</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Deductions Section -->
            <div class="col-md-6">
                <div class="d-flex justify-content-between align-items-center mb-2">                    
                     <div class="col">
                        <h5 class="mb-0">Deductions</h5>
                    </div>
                    <div class="col-auto">
                        <button type="button" class="btn btn-warning btn-sm" onclick="addDeductionRow()">
                            Add Deduction
                        </button>
                    </div>
                </div>
                <div class="table-responsive" style="max-height: 400px; overflow-y: auto;">
                    <table class="table table-sm table-bordered">
                        <thead class="table-light">
                            <tr>
                                <th width="50%">Deduction Name</th>
                                <th width="35%">Amount</th>
                                <th width="15%">Action</th>
                            </tr>
                        </thead>
                        <tbody id="deductions-tbody">
                            <tr>
                                <td colspan="3" class="text-center text-muted">No deductions added</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Save Button -->
        <div class="mt-4" id="save-section" style="display: none;">
            <button type="button" class="btn btn-primary" onclick="saveAdjustments()">
                <i class="bi bi-save"></i> Save Adjustments
            </button>
            <a href="{{ route('payroll.payroll-adjustments.index') }}" class="btn btn-secondary">
                <i class="bi bi-arrow-left"></i> Back
            </a>
        </div>
    </div>
</div>

<!-- Import Data Modal -->
<div class="modal fade" id="importModal" tabindex="-1" aria-labelledby="importModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="importModalLabel">Import Adjustments from File</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- Type selection -->
                <div class="mb-3">
                    <label class="form-label fw-semibold">Type</label>
                    <div class="d-flex gap-4">
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="importType" id="importTypeAddition" value="addition" checked>
                            <label class="form-check-label" for="importTypeAddition">Addition</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="importType" id="importTypeDeduction" value="deduction">
                            <label class="form-check-label" for="importTypeDeduction">Deduction</label>
                        </div>
                    </div>
                </div>

                <!-- Addition dropdown -->
                <div class="mb-3" id="importAdditionGroup">
                    <label for="importAdditionId" class="form-label fw-semibold">Select Addition</label>
                    <select id="importAdditionId" class="form-select">
                        <option value="">-- Select Addition --</option>
                        @foreach($additions as $addition)
                            <option value="{{ $addition->id }}">{{ $addition->name }}</option>
                        @endforeach
                    </select>
                </div>

                <!-- Deduction dropdown -->
                <div class="mb-3 d-none" id="importDeductionGroup">
                    <label for="importDeductionId" class="form-label fw-semibold">Select Deduction</label>
                    <select id="importDeductionId" class="form-select">
                        <option value="">-- Select Deduction --</option>
                        @foreach($deductions as $deduction)
                            <option value="{{ $deduction->id }}">{{ $deduction->name }}</option>
                        @endforeach
                    </select>
                </div>

                <!-- Download template -->
                <div class="mb-3">
                    <a href="{{ route('payroll.payroll-adjustments.import-template', $payrollAdjustment->id) }}"
                       class="btn btn-outline-secondary btn-sm">
                        <i class="bi bi-download"></i> Download Template (CSV)
                    </a>
                    <small class="text-muted ms-2">Template contains <strong>emp_no</strong> and <strong>amount</strong> columns.</small>
                </div>

                <!-- File upload drop zone -->
                <div class="mb-3">
                    <label class="form-label fw-semibold">Upload File</label>
                    <div id="importDropZone"
                         class="border border-2 border-dashed rounded p-4 text-center"
                         style="cursor:pointer; border-style:dashed !important; min-height:120px; display:flex; flex-direction:column; align-items:center; justify-content:center;">
                        <i class="bi bi-cloud-upload fs-2 text-secondary"></i>
                        <p class="mb-1 text-secondary">Drag &amp; drop a CSV or Excel file here</p>
                        <p class="text-muted small mb-2">or</p>
                        <button type="button" class="btn btn-sm btn-outline-primary" id="importBrowseBtn">Browse File</button>
                        <input type="file" id="importFileInput" accept=".csv,.xlsx,.xls" style="display:none">
                    </div>
                    <div id="importFileName" class="mt-2 text-success small"></div>
                </div>

                <!-- Error list (shown after failed import) -->
                <div id="importErrors" class="d-none">
                    <div class="alert alert-warning mb-0">
                        <strong>Rows skipped:</strong>
                        <ul id="importErrorList" class="mb-0 mt-1 ps-3"></ul>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="importSubmitBtn" onclick="submitImport()">
                    <i class="bi bi-upload"></i> Import
                </button>
            </div>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script>
const additions = @json($additions);
const deductions = @json($deductions);
let currentEmployeeId = null;
let additionCounter = 0;
let deductionCounter = 0;

// Initialize Select2 for employee dropdown
$(document).ready(function() {
    initEmployeeSelect2('#employee-select');
});

// Employee selection change event
$('#employee-select').on('change', function() {
    const employeeId = $(this).val();
    loadEmployeeAdjustments(employeeId);
});

// Load employee adjustments via AJAX
function loadEmployeeAdjustments(employeeId) {
    if (!employeeId) {
        $('#adjustment-section').hide();
        $('#save-section').hide();
        currentEmployeeId = null;
        return;
    }

    currentEmployeeId = employeeId;
    $('#adjustment-section').show();
    $('#save-section').show();

    // Clear existing rows
    $('#additions-tbody').html('<tr><td colspan="3" class="text-center"><i class="bi bi-hourglass-split"></i> Loading...</td></tr>');
    $('#deductions-tbody').html('<tr><td colspan="3" class="text-center"><i class="bi bi-hourglass-split"></i> Loading...</td></tr>');

    $.ajax({
        url: "{{ route('payroll.payroll-adjustments.employee-adjustments', $payrollAdjustment->id) }}",
        type: 'GET',
        data: { employee_id: employeeId },
        success: function(response) {
            if (response.status) {
                renderAdditions(response.additions);
                renderDeductions(response.deductions);
            }
        },
        error: function(xhr) {
            Swal.fire('Error!', xhr.responseJSON?.message || 'Failed to load employee data', 'error');
            $('#additions-tbody').html('<tr><td colspan="3" class="text-center text-danger">Failed to load</td></tr>');
            $('#deductions-tbody').html('<tr><td colspan="3" class="text-center text-danger">Failed to load</td></tr>');
        }
    });
}

// Render additions
function renderAdditions(additionsData) {
    $('#additions-tbody').empty();

    if (additionsData.length === 0) {
        $('#additions-tbody').html('<tr><td colspan="3" class="text-center text-muted">No additions added</td></tr>');
        return;
    }

    additionsData.forEach(function(addition, index) {
        additionCounter = index + 1;
        const row = createAdditionRow(addition.addition_id, addition.amount);
        $('#additions-tbody').append(row);
    });
}

// Render deductions
function renderDeductions(deductionsData) {
    $('#deductions-tbody').empty();

    if (deductionsData.length === 0) {
        $('#deductions-tbody').html('<tr><td colspan="3" class="text-center text-muted">No deductions added</td></tr>');
        return;
    }

    deductionsData.forEach(function(deduction, index) {
        deductionCounter = index + 1;
        const row = createDeductionRow(deduction.deduction_id, deduction.amount);
        $('#deductions-tbody').append(row);
    });
}

// Add new addition row
function addAdditionRow() {
    if (!currentEmployeeId) {
        Swal.fire('Warning!', 'Please select an employee first', 'warning');
        return;
    }

    const row = createAdditionRow(null, '');
    $('#additions-tbody').find('tr').filter(function() {
        return $(this).find('td').length === 1 && $(this).find('td').hasClass('text-muted');
    }).remove();
    $('#additions-tbody').append(row);
}

// Add new deduction row
function addDeductionRow() {
    if (!currentEmployeeId) {
        Swal.fire('Warning!', 'Please select an employee first', 'warning');
        return;
    }

    const row = createDeductionRow(null, '');
    $('#deductions-tbody').find('tr').filter(function() {
        return $(this).find('td').length === 1 && $(this).find('td').hasClass('text-muted');
    }).remove();
    $('#deductions-tbody').append(row);
}

// Create addition row HTML
function createAdditionRow(selectedId, amount) {
    additionCounter++;
    const options = additions.map(a =>
        `<option value="${a.id}" ${a.id == selectedId ? 'selected' : ''}>${a.name}</option>`
    ).join('');

    return `
        <tr class="addition-row">
            <td>
                <select class="form-select form-select-sm addition-select" required>
                    <option value="">-- Select Addition --</option>
                    ${options}
                </select>
            </td>
            <td>
                <input type="number" step="0.01" class="form-control form-control-sm addition-amount"
                       placeholder="Amount" value="${amount}" required>
            </td>
            <td class="text-center">
                <button type="button" class="btn btn-danger btn-sm" onclick="removeRow(this)">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    `;
}

// Create deduction row HTML
function createDeductionRow(selectedId, amount) {
    deductionCounter++;
    const options = deductions.map(d =>
        `<option value="${d.id}" ${d.id == selectedId ? 'selected' : ''}>${d.name}</option>`
    ).join('');

    return `
        <tr class="deduction-row">
            <td>
                <select class="form-select form-select-sm deduction-select" required>
                    <option value="">-- Select Deduction --</option>
                    ${options}
                </select>
            </td>
            <td>
                <input type="number" step="0.01" class="form-control form-control-sm deduction-amount"
                       placeholder="Amount" value="${amount}" required>
            </td>
            <td class="text-center">
                <button type="button" class="btn btn-danger btn-sm" onclick="removeRow(this)">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    `;
}

// Remove row
function removeRow(btn) {
    const $row = $(btn).closest('tr');
    const $tbody = $row.closest('tbody');

    $row.remove();

    // If no rows left, show placeholder
    if ($tbody.find('tr').length === 0) {
        const colSpan = $tbody.attr('id') === 'additions-tbody' ? 3 : 3;
        $tbody.html(`<tr><td colspan="${colSpan}" class="text-center text-muted">No ${$tbody.attr('id') === 'additions-tbody' ? 'additions' : 'deductions'} added</td></tr>`);
    }
}

/* ============================================================
   Import modal logic
   ============================================================ */
let importSelectedFile = null;

// Toggle addition/deduction dropdowns
$('input[name="importType"]').on('change', function () {
    const val = $(this).val();
    if (val === 'addition') {
        $('#importAdditionGroup').removeClass('d-none');
        $('#importDeductionGroup').addClass('d-none');
    } else {
        $('#importDeductionGroup').removeClass('d-none');
        $('#importAdditionGroup').addClass('d-none');
    }
});

// Reset modal state when it opens
$('#importModal').on('show.bs.modal', function () {
    importSelectedFile = null;
    $('#importFileName').text('');
    $('#importFileInput').val('');
    $('#importErrors').addClass('d-none');
    $('#importErrorList').empty();
    $('#importDropZone').removeClass('border-success border-danger').addClass('border-secondary');
});

// Browse button
$('#importBrowseBtn').on('click', function () {
    $('#importFileInput').trigger('click');
});

// File input change
$('#importFileInput').on('change', function () {
    if (this.files.length > 0) {
        importSetFile(this.files[0]);
    }
});

// Drag & drop
$('#importDropZone').on('dragover', function (e) {
    e.preventDefault();
    $(this).addClass('bg-light');
});

$('#importDropZone').on('dragleave', function () {
    $(this).removeClass('bg-light');
});

$('#importDropZone').on('drop', function (e) {
    e.preventDefault();
    $(this).removeClass('bg-light');
    const file = e.originalEvent.dataTransfer.files[0];
    if (file) {
        importSetFile(file);
    }
});

function importSetFile(file) {
    const allowed = ['csv', 'xlsx', 'xls'];
    const ext = file.name.split('.').pop().toLowerCase();
    if (!allowed.includes(ext)) {
        Swal.fire('Invalid File', 'Please upload a CSV or Excel (.xlsx / .xls) file.', 'warning');
        return;
    }
    importSelectedFile = file;
    $('#importFileName').text('Selected: ' + file.name);
    $('#importDropZone').removeClass('border-danger').addClass('border-success');
    $('#importErrors').addClass('d-none');
    $('#importErrorList').empty();
}

function submitImport() {
    const type   = $('input[name="importType"]:checked').val();
    const itemId = type === 'addition' ? $('#importAdditionId').val() : $('#importDeductionId').val();

    if (!itemId) {
        Swal.fire('Warning', 'Please select a ' + type + '.', 'warning');
        return;
    }

    if (!importSelectedFile) {
        Swal.fire('Warning', 'Please select a file to upload.', 'warning');
        return;
    }

    const formData = new FormData();
    formData.append('_token', '{{ csrf_token() }}');
    formData.append('type', type);
    formData.append('item_id', itemId);
    formData.append('file', importSelectedFile);

    $('#importSubmitBtn').prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span> Importing...');
    $('#importErrors').addClass('d-none');
    $('#importErrorList').empty();

    $.ajax({
        url: '{{ route("payroll.payroll-adjustments.import-data", $payrollAdjustment->id) }}',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function (response) {
            $('#importSubmitBtn').prop('disabled', false).html('<i class="bi bi-upload"></i> Import');

            if (response.errors && response.errors.length > 0) {
                $('#importErrorList').empty();
                response.errors.forEach(function (err) {
                    $('#importErrorList').append('<li>' + err + '</li>');
                });
                $('#importErrors').removeClass('d-none');
            }

            Swal.fire('Done!', response.message, response.inserted > 0 ? 'success' : 'warning').then(function () {
                if (response.inserted > 0) {
                    $('#importModal').modal('hide');
                    // Reload current employee view if one is selected
                    if (currentEmployeeId) {
                        loadEmployeeAdjustments(currentEmployeeId);
                    }
                }
            });
        },
        error: function (xhr) {
            $('#importSubmitBtn').prop('disabled', false).html('<i class="bi bi-upload"></i> Import');
            const msg = xhr.responseJSON?.message || xhr.responseJSON?.errors?.file?.[0] || 'An error occurred.';
            Swal.fire('Error!', msg, 'error');
        }
    });
}

/* ============================================================
   Original adjustment logic
   ============================================================ */
// Save all adjustments
function saveAdjustments() {
    if (!currentEmployeeId) {
        Swal.fire('Warning!', 'Please select an employee first', 'warning');
        return;
    }

    let adjustments = [];

    // Collect additions
    $('#additions-tbody .addition-row').each(function() {
        const additionId = $(this).find('.addition-select').val();
        const amount = $(this).find('.addition-amount').val();

        if (additionId && amount) {
            adjustments.push({
                employee_id: currentEmployeeId,
                type: 'addition',
                item_id: additionId,
                amount: amount,
                remarks: null
            });
        }
    });

    // Collect deductions
    $('#deductions-tbody .deduction-row').each(function() {
        const deductionId = $(this).find('.deduction-select').val();
        const amount = $(this).find('.deduction-amount').val();

        if (deductionId && amount) {
            adjustments.push({
                employee_id: currentEmployeeId,
                type: 'deduction',
                item_id: deductionId,
                amount: amount,
                remarks: null
            });
        }
    });

    // Validate
    if (adjustments.length === 0) {
        Swal.fire('Warning!', 'Please add at least one addition or deduction', 'warning');
        return;
    }

    // Save via AJAX
    $.ajax({
        url: "{{ route('payroll.payroll-adjustments.save-adjustments', $payrollAdjustment->id) }}",
        type: 'POST',
        data: {
            _token: '{{ csrf_token() }}',
            adjustments: adjustments
        },
        success: function(response) {
            if (response.status) {
                Swal.fire('Success!', response.message, 'success').then(() => {
                    // Reload current employee's data
                    loadEmployeeAdjustments(currentEmployeeId);
                });
            }
        },
        error: function(xhr) {
            Swal.fire('Error!', xhr.responseJSON?.message || 'An error occurred', 'error');
        }
    });
}
</script>
@endsection
