@extends('layouts.app')

@section('title', 'Initiate Dismissal Process')

@section('content')
<div class="container-fluid px-4 py-3">
    <div class="row">
        <div class="col-12">
            <!-- Page Header -->
            <div class="d-flex justify-content-between align-items-center mb-4">
                <div>
                    <h4 class="mb-0 fw-bold text-gray-800">
                        <i class="fas fa-user-slash me-2 text-danger"></i>Initiate Dismissal Process
                    </h4>
                    <p class="text-muted mt-1 mb-0">Create a formal dismissal request for employee separation</p>
                </div>
                <a href="{{ route('salary.dismissals.index') }}" class="btn btn-outline-secondary btn-sm rounded-pill px-3">
                    <i class="fas fa-arrow-left me-1"></i> Back to List
                </a>
            </div>

            <!-- Main Form Card -->
            <div class="card shadow-sm border-0 rounded-3">
                <div class="card-header bg-white border-bottom-0 pt-4 px-4">
                    <ul class="nav nav-tabs card-header-tabs" id="dismissalTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="basic-tab" data-bs-toggle="tab" data-bs-target="#basic" type="button" role="tab">
                                <i class="fas fa-info-circle me-2"></i>Basic Information
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="details-tab" data-bs-toggle="tab" data-bs-target="#details" type="button" role="tab">
                                <i class="fas fa-file-alt me-2"></i>Dismissal Details
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="financial-tab" data-bs-toggle="tab" data-bs-target="#financial" type="button" role="tab">
                                <i class="fas fa-coins me-2"></i>Financial Settlement
                            </button>
                        </li>
                    </ul>
                </div>

                <form id="dismissalForm" method="POST" class="needs-validation">
                    @csrf
                    <div class="card-body px-4 py-3">
                        <div class="tab-content">
                            <!-- Tab 1: Basic Information -->
                            <div class="tab-pane fade show active" id="basic" role="tabpanel">
                                <!-- Employee Selection Card -->
                                <div class="card bg-light border-0 rounded-3 mb-4">
                                    <div class="card-body">
                                        <div class="row align-items-end">
                                            <div class="col-md-8">
                                                <label class="form-label fw-semibold mb-2">
                                                    <i class="fas fa-user-circle text-primary me-1"></i>Select Employee
                                                    <span class="text-danger">*</span>
                                                </label>
                                                <select class="form-select form-select-lg" id="employee_id" name="employee_id" required>
                                                    <option value="">-- Search and select employee --</option>
                                                    @foreach($employees as $employee)
                                                        <option value="{{ $employee->id }}" 
                                                                data-join-date="{{ $employee->join_date ?? '' }}"
                                                                data-position="{{ $employee->position ?? '' }}"
                                                                data-department="{{ $employee->department ?? '' }}"
                                                                data-basic-salary="{{ $employee->basic_salary ?? 0 }}">
                                                            {{ $employee->full_name }} 
                                                            @if($employee->employee_id) (ID: {{ $employee->employee_id }}) @endif
                                                            - {{ $employee->position ?? 'No Position' }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                                <div class="invalid-feedback" id="employee_error"></div>
                                            </div>
                                            <div class="col-md-4 text-end">
                                                <div class="form-text">
                                                    <i class="fas fa-info-circle text-info"></i> Only active employees without active dismissals are shown
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Employee Details Dashboard -->
                                <div id="employeeDetails" style="display: none;">
                                    <div class="row g-3 mb-4">
                                        <div class="col-md-3">
                                            <div class="card border-0 shadow-sm h-100">
                                                <div class="card-body text-center">
                                                    <div class="rounded-circle bg-primary bg-opacity-10 p-3 d-inline-block mb-2">
                                                        <i class="fas fa-building fa-2x text-primary"></i>
                                                    </div>
                                                    <h6 class="text-muted mb-1">Department</h6>
                                                    <h5 class="mb-0" id="emp_department">-</h5>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="card border-0 shadow-sm h-100">
                                                <div class="card-body text-center">
                                                    <div class="rounded-circle bg-success bg-opacity-10 p-3 d-inline-block mb-2">
                                                        <i class="fas fa-briefcase fa-2x text-success"></i>
                                                    </div>
                                                    <h6 class="text-muted mb-1">Position</h6>
                                                    <h5 class="mb-0" id="emp_position">-</h5>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="card border-0 shadow-sm h-100">
                                                <div class="card-body text-center">
                                                    <div class="rounded-circle bg-info bg-opacity-10 p-3 d-inline-block mb-2">
                                                        <i class="fas fa-calendar-alt fa-2x text-info"></i>
                                                    </div>
                                                    <h6 class="text-muted mb-1">Join Date</h6>
                                                    <h5 class="mb-0" id="emp_join_date">-</h5>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="card border-0 shadow-sm h-100">
                                                <div class="card-body text-center">
                                                    <div class="rounded-circle bg-warning bg-opacity-10 p-3 d-inline-block mb-2">
                                                        <i class="fas fa-money-bill-wave fa-2x text-warning"></i>
                                                    </div>
                                                    <h6 class="text-muted mb-1">Basic Salary</h6>
                                                    <h5 class="mb-0" id="emp_basic_salary">-</h5>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Pending Deductions Alert -->
                                    <div id="pendingDeductionsSection" class="mb-4" style="display: none;">
                                        <div class="alert alert-warning border-0 shadow-sm">
                                            <div class="d-flex align-items-center">
                                                <div class="me-3">
                                                    <i class="fas fa-exclamation-triangle fa-2x"></i>
                                                </div>
                                                <div class="flex-grow-1">
                                                    <h6 class="mb-1">Pending Deductions Found</h6>
                                                    <p class="mb-0 small">The following deductions will be automatically applied during the dismissal process:</p>
                                                </div>
                                            </div>
                                            <div class="table-responsive mt-3">
                                                <table class="table table-sm table-borderless mb-0">
                                                    <thead class="table-light">
                                                        <tr>
                                                            <th>Date</th>
                                                            <th>Amount</th>
                                                            <th>Reason</th>
                                                            <th>Status</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody id="pendingDeductionsList">
                                                        <tr>
                                                            <td colspan="4" class="text-center text-muted">No pending deductions</td>
                                                        </tr>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Active Dismissal Warning -->
                                    <div id="existingDismissalWarning" class="alert alert-danger border-0 shadow-sm" style="display: none;">
                                        <div class="d-flex align-items-center">
                                            <i class="fas fa-ban fa-2x me-3"></i>
                                            <div>
                                                <h6 class="mb-1">Active Dismissal Process Exists</h6>
                                                <p class="mb-0 small">This employee already has an active dismissal process. Please check existing records before proceeding.</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Tab 2: Dismissal Details -->
                            <div class="tab-pane fade" id="details" role="tabpanel">
                                <div class="row g-4">
                                    <div class="col-md-6">
                                        <div class="card border-0 shadow-sm h-100">
                                            <div class="card-body">
                                                <h6 class="fw-bold mb-3">
                                                    <i class="fas fa-gavel text-danger me-2"></i>Dismissal Classification
                                                </h6>
                                                <div class="mb-3">
                                                    <label class="form-label fw-semibold">Dismissal Type <span class="text-danger">*</span></label>
                                                    <select class="form-select" id="dismissal_type" name="dismissal_type" required>
                                                        <option value="">-- Select Type --</option>
                                                        <option value="gross_misconduct">Gross Misconduct</option>
                                                        <option value="performance">Performance Issues</option>
                                                        <option value="attendance">Attendance Related</option>
                                                        <option value="redundancy">Redundancy</option>
                                                        <option value="other">Other</option>
                                                    </select>
                                                    <div class="invalid-feedback" id="dismissal_type_error"></div>
                                                </div>

                                                <div class="mb-3">
                                                    <label class="form-label fw-semibold">Effective Date <span class="text-danger">*</span></label>
                                                    <input type="date" class="form-control" id="effective_date" name="effective_date" required>
                                                    <small class="text-muted">Date when dismissal takes effect</small>
                                                    <div class="invalid-feedback" id="effective_date_error"></div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="card border-0 shadow-sm h-100">
                                            <div class="card-body">
                                                <h6 class="fw-bold mb-3">
                                                    <i class="fas fa-clock text-warning me-2"></i>Notice Period
                                                </h6>
                                                <div class="mb-3">
                                                    <label class="form-label fw-semibold">Last Working Date</label>
                                                    <input type="date" class="form-control" id="last_working_date" name="last_working_date">
                                                    <small class="text-muted">Optional - If different from effective date</small>
                                                </div>

                                                <!-- Garden Leave Section -->
                                                <div class="mb-3">
                                                    <label class="form-label fw-semibold">Garden Leave Required</label>
                                                    <div class="form-check form-switch">
                                                        <input class="form-check-input" type="checkbox" id="garden_leave" name="garden_leave" value="1">
                                                        <label class="form-check-label" for="garden_leave">
                                                            Place employee on garden leave (pay in lieu of notice)
                                                        </label>
                                                    </div>
                                                    <div id="gardenLeaveInfo" style="display: none;" class="mt-2 p-2 bg-info bg-opacity-10 rounded">
                                                        <small class="text-info">
                                                            <i class="fas fa-info-circle me-1"></i>
                                                            Garden leave means employee stays home during notice period but receives full pay. 
                                                            Used for senior staff or those joining competitors.
                                                        </small>
                                                    </div>
                                                </div>

                                                <!-- Settlement Calculation Preview -->
                                                <div id="settlementPreview" style="display: none;" class="mt-3">
                                                    <div class="card border-primary">
                                                        <div class="card-header bg-primary bg-opacity-10">
                                                            <h6 class="mb-0">Settlement Calculation Preview</h6>
                                                        </div>
                                                        <div class="card-body">
                                                            <div class="row">
                                                                <div class="col-md-6">
                                                                    <table class="table table-sm">
                                                                        <tr>
                                                                            <td>Basic Monthly Salary:</td>
                                                                            <td class="text-end" id="preview_basic_salary">KES 0</td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td>Unpaid Days ({{ date('d') }} days):</td>
                                                                            <td class="text-end" id="preview_unpaid">KES 0</td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td>Unused Leave Days:</td>
                                                                            <td class="text-end" id="preview_leave">KES 0</td>
                                                                        </tr>
                                                                    </table>
                                                                </div>
                                                                <div class="col-md-6">
                                                                    <table class="table table-sm">
                                                                        <tr>
                                                                            <td>Notice Period Pay:</td>
                                                                            <td class="text-end" id="preview_notice">KES 0</td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td>Severance Pay:</td>
                                                                            <td class="text-end" id="preview_severance">KES 0</td>
                                                                        </tr>
                                                                        <tr class="table-primary">
                                                                            <td><strong>Total Settlement:</strong></td>
                                                                            <td class="text-end"><strong id="preview_total">KES 0</strong></td>
                                                                        </tr>
                                                                    </table>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="col-12">
                                        <div class="card border-0 shadow-sm">
                                            <div class="card-body">
                                                <h6 class="fw-bold mb-3">
                                                    <i class="fas fa-file-text text-info me-2"></i>Reason for Dismissal
                                                </h6>
                                                <textarea class="form-control" id="reason" name="reason" rows="5" required 
                                                          placeholder="Provide a detailed, factual account of the reasons leading to this dismissal..."></textarea>
                                                <div class="invalid-feedback" id="reason_error"></div>
                                                <div class="form-text mt-2">
                                                    <i class="fas fa-info-circle text-info"></i> Minimum 20 characters. Include dates, incidents, and any previous warnings.
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="col-12">
                                        <div class="card border-0 shadow-sm">
                                            <div class="card-body">
                                                <h6 class="fw-bold mb-3">
                                                    <i class="fas fa-comment-dots text-secondary me-2"></i>Additional Comments
                                                </h6>
                                                <textarea class="form-control" id="comments" name="comments" rows="3" 
                                                          placeholder="Any additional information or notes..."></textarea>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Tab 3: Financial Settlement -->
                            <div class="tab-pane fade" id="financial" role="tabpanel">
                                <div class="row g-4">
                                    <div class="col-md-6">
                                        <div class="card border-0 shadow-sm">
                                            <div class="card-body">
                                                <h6 class="fw-bold mb-3">
                                                    <i class="fas fa-calculator text-primary me-2"></i>Settlement Configuration
                                                </h6>
                                                <div class="form-check form-switch mb-3">
                                                    <input class="form-check-input" type="checkbox" id="requires_settlement" name="requires_settlement" value="1">
                                                    <label class="form-check-label fw-semibold" for="requires_settlement">
                                                        Requires Final Settlement Calculation
                                                    </label>
                                                </div>

                                                <div id="settlementFields" style="display: none;">
                                                    <div class="mb-3">
                                                        <label class="form-label">Proposed Settlement Amount</label>
                                                        <div class="input-group">
                                                            <span class="input-group-text">KES</span>
                                                            <input type="number" class="form-control" id="settlement_amount" name="settlement_amount" step="0.01">
                                                        </div>
                                                        <small class="text-muted">If known, otherwise will be calculated</small>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="col-md-6">
                                        <div class="card border-0 shadow-sm">
                                            <div class="card-body">
                                                <h6 class="fw-bold mb-3">
                                                    <i class="fas fa-hand-holding-usd text-success me-2"></i>Deduction Information
                                                </h6>
                                                <div class="mb-3">
                                                    <label class="form-label">Additional Deduction Amount</label>
                                                    <div class="input-group">
                                                        <span class="input-group-text">KES</span>
                                                        <input type="number" class="form-control" id="deduction_amount" name="deduction_amount" step="0.01">
                                                    </div>
                                                </div>
                                                <div id="deductionReasonGroup" style="display: none;">
                                                    <label class="form-label">Deduction Reason</label>
                                                    <textarea class="form-control" id="deduction_reason" name="deduction_reason" rows="2" 
                                                              placeholder="Reason for additional deduction..."></textarea>
                                                    <div class="invalid-feedback" id="deduction_reason_error"></div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="col-12">
                                        <div class="alert alert-info border-0 shadow-sm">
                                            <div class="d-flex">
                                                <i class="fas fa-info-circle fa-2x me-3"></i>
                                                <div>
                                                    <h6 class="mb-1">Important Note</h6>
                                                    <p class="mb-0 small">This dismissal request will be reviewed by HR and management. 
                                                    All pending deductions will be automatically calculated in the final settlement.</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Form Actions -->
                    <div class="card-footer bg-white border-top-0 py-3">
                        <div class="d-flex justify-content-end gap-2">
                            <button type="button" class="btn btn-secondary rounded-pill px-4" onclick="window.history.back()">
                                <i class="fas fa-times me-1"></i> Cancel
                            </button>
                            <button type="submit" class="btn btn-danger rounded-pill px-4" id="submitBtn">
                                <i class="fas fa-paper-plane me-1"></i> Submit Dismissal Request
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Loading Overlay -->
<div id="loadingOverlay" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); z-index: 9999; align-items: center; justify-content: center;">
    <div class="text-center bg-white p-4 rounded-3">
        <div class="spinner-border text-danger mb-3" role="status" style="width: 3rem; height: 3rem;"></div>
        <h6>Processing...</h6>
        <p class="mb-0 small">Please wait while we process your request</p>
    </div>
</div>
@endsection

@push('styles')
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2-bootstrap4-theme@1.0.0/dist/select2-bootstrap4.min.css" rel="stylesheet">
<style>
    .form-select, .form-control {
        border-radius: 0.5rem;
        border: 1px solid #e2e8f0;
        transition: all 0.2s;
    }
    .form-select:focus, .form-control:focus {
        border-color: #dc2626;
        box-shadow: 0 0 0 0.2rem rgba(220, 38, 38, 0.1);
    }
    .card {
        border-radius: 1rem;
        transition: transform 0.2s, box-shadow 0.2s;
    }
    .card:hover {
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.08) !important;
    }
    .nav-tabs .nav-link {
        color: #6c757d;
        border: none;
        padding: 0.75rem 1.5rem;
        transition: all 0.2s;
    }
    .nav-tabs .nav-link:hover {
        color: #dc2626;
        background: transparent;
        border-bottom: 2px solid #dc2626;
    }
    .nav-tabs .nav-link.active {
        color: #dc2626;
        background: transparent;
        border-bottom: 2px solid #dc2626;
        font-weight: 600;
    }
    .select2-container--bootstrap4 .select2-selection {
        border-radius: 0.5rem !important;
        min-height: calc(2.5rem + 2px) !important;
        border-color: #e2e8f0 !important;
    }
    .select2-container--bootstrap4 .select2-selection--single .select2-selection__rendered {
        line-height: calc(2.5rem) !important;
    }
    .select2-container--bootstrap4 .select2-dropdown {
        border-radius: 0.5rem !important;
    }
    .toast {
        border-radius: 0.5rem;
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
    }
    .btn {
        transition: all 0.2s;
    }
    .btn:hover {
        transform: translateY(-1px);
    }
    .bg-opacity-10 {
        --bs-bg-opacity: 0.1;
    }
</style>
@endpush

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function() {
    $('#employee_id').select2({
        theme: 'bootstrap4',
        placeholder: '🔍 Search for employee...',
        allowClear: true,
        width: '100%'
    });
    
    // Show/hide settlement fields
    $('#requires_settlement').change(function() {
        $('#settlementFields').toggle(this.checked);
    });
    
    // Show/hide deduction reason
    $('#deduction_amount').on('input', function() {
        const amount = parseFloat($(this).val());
        $('#deductionReasonGroup').toggle(amount > 0);
        if (amount > 0) {
            $('#deduction_reason').prop('required', true);
        } else {
            $('#deduction_reason').prop('required', false);
        }
    });
    
    // Employee selection handler
    $('#employee_id').change(function() {
        const employeeId = $(this).val();
        if (employeeId) {
            loadEmployeeDetails(employeeId);
        } else {
            $('#employeeDetails').slideUp();
        }
    });
    
    function loadEmployeeDetails(employeeId) {
        showLoader();
        $.ajax({
            url: `/salary/employees/${employeeId}/details`,
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    const emp = response.employee;
                    
                    // Update employee info cards
                    $('#emp_department').text(emp.department || 'Not Assigned');
                    $('#emp_position').text(emp.position || 'Not Specified');
                    $('#emp_join_date').text(emp.join_date ? formatDate(emp.join_date) : 'N/A');
                    $('#emp_basic_salary').text(formatCurrency(emp.basic_salary || 0));
                    
                    // Show details with animation
                    $('#employeeDetails').slideDown();
                    
                    // Handle pending deductions
                    if (emp.pending_deductions && emp.pending_deductions.length > 0) {
                        let html = '';
                        emp.pending_deductions.forEach(d => {
                            html += `<tr>
                                <td>${formatDate(d.created_at)}</td>
                                <td class="text-danger">${formatCurrency(d.amount)}</td>
                                <td>${escapeHtml(d.reason)}</td>
                                <td><span class="badge bg-warning text-dark">Pending</span></td>
                            </tr>`;
                        });
                        $('#pendingDeductionsList').html(html);
                        $('#pendingDeductionsSection').slideDown();
                    } else {
                        $('#pendingDeductionsSection').slideUp();
                    }
                    
                    // Check for existing dismissal
                    if (emp.has_active_dismissal) {
                        $('#existingDismissalWarning').slideDown();
                        $('#submitBtn').prop('disabled', true);
                        showToast('warning', 'This employee already has an active dismissal process');
                    } else {
                        $('#existingDismissalWarning').slideUp();
                        $('#submitBtn').prop('disabled', false);
                    }
                }
            },
            error: function() {
                showToast('error', 'Failed to load employee details');
                $('#employeeDetails').slideUp();
            },
            complete: function() {
                hideLoader();
            }
        });
    }

    // Auto-calculate settlement based on employee data
function calculateSettlement() {
    const basicSalary = parseFloat($('#emp_basic_salary').text().replace(/[^0-9.-]+/g, '')) || 0;
    const dailyRate = basicSalary / 30;
    
    // Calculate unpaid days (days worked in current month)
    const today = new Date();
    const unpaidDays = today.getDate() - 1;
    const unpaidAmount = unpaidDays * dailyRate;
    
    // Calculate leave days (assuming 21 days per year)
    const joinDate = new Date($('#emp_join_date').text());
    const yearsEmployed = (today - joinDate) / (1000 * 60 * 60 * 24 * 365);
    const leaveDays = Math.floor(yearsEmployed * 21);
    const leaveAmount = leaveDays * dailyRate;
    
    // Notice period (30 days)
    const noticeAmount = basicSalary;
    
    // Severance (15 days per year)
    const severanceAmount = yearsEmployed * 15 * dailyRate;
    
    const total = unpaidAmount + leaveAmount + noticeAmount + severanceAmount;
    
    $('#preview_unpaid').text(formatCurrency(unpaidAmount));
    $('#preview_leave').text(formatCurrency(leaveAmount));
    $('#preview_notice').text(formatCurrency(noticeAmount));
    $('#preview_severance').text(formatCurrency(severanceAmount));
    $('#preview_total').text(formatCurrency(total));
    $('#proposed_settlement_amount').val(total);
}
    
    // Form submission handler
    $('#dismissalForm').submit(function(e) {
        e.preventDefault();
        
        // Clear previous errors
        $('.is-invalid').removeClass('is-invalid');
        $('.invalid-feedback').text('');
        
        // Validate form
        if (!validateForm()) return;
        
        const formData = new FormData(this);
        
        showLoader();
        $('#submitBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i> Submitting...');
        
        $.ajax({
            url: '{{ route("salary.dismissals.store") }}',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    showToast('success', response.message);
                    setTimeout(() => {
                        window.location.href = response.redirect_url || '{{ route("salary.dismissals.index") }}';
                    }, 1500);
                } else {
                    showToast('error', response.message);
                    $('#submitBtn').prop('disabled', false).html('<i class="fas fa-paper-plane me-1"></i> Submit Dismissal Request');
                    hideLoader();
                }
            },
            error: function(xhr) {
                hideLoader();
                $('#submitBtn').prop('disabled', false).html('<i class="fas fa-paper-plane me-1"></i> Submit Dismissal Request');
                
                if (xhr.status === 422 && xhr.responseJSON.errors) {
                    const errors = xhr.responseJSON.errors;
                    for (let field in errors) {
                        $(`#${field}`).addClass('is-invalid');
                        $(`#${field}_error`).text(errors[field][0]);
                    }
                    showToast('error', 'Please correct the validation errors');
                    // Switch to tab with errors
                    if (errors.reason || errors.dismissal_type || errors.effective_date) {
                        $('#details-tab').tab('show');
                    }
                    if (errors.deduction_reason || errors.deduction_amount) {
                        $('#financial-tab').tab('show');
                    }
                } else {
                    const message = xhr.responseJSON?.message || 'An error occurred. Please try again.';
                    showToast('error', message);
                }
            }
        });
    });
    
    // Form validation
    function validateForm() {
        let isValid = true;
        
        // Employee validation
        if (!$('#employee_id').val()) {
            $('#employee_id').addClass('is-invalid');
            $('#employee_error').text('Please select an employee');
            isValid = false;
        }
        
        // Dismissal type
        if (!$('#dismissal_type').val()) {
            $('#dismissal_type').addClass('is-invalid');
            $('#dismissal_type_error').text('Please select a dismissal type');
            isValid = false;
        }
        
        // Effective date
        const effectiveDate = $('#effective_date').val();
        if (!effectiveDate) {
            $('#effective_date').addClass('is-invalid');
            $('#effective_date_error').text('Please select an effective date');
            isValid = false;
        } else if (effectiveDate < new Date().toISOString().split('T')[0]) {
            $('#effective_date').addClass('is-invalid');
            $('#effective_date_error').text('Effective date cannot be in the past');
            isValid = false;
        }
        
        // Reason validation
        const reason = $('#reason').val();
        if (!reason) {
            $('#reason').addClass('is-invalid');
            $('#reason_error').text('Please provide a reason for dismissal');
            isValid = false;
        } else if (reason.length < 20) {
            $('#reason').addClass('is-invalid');
            $('#reason_error').text('Reason must be at least 20 characters (currently ' + reason.length + ')');
            isValid = false;
        }
        
        // Deduction validation
        const deductionAmount = $('#deduction_amount').val();
        if (deductionAmount && parseFloat(deductionAmount) > 0) {
            const deductionReason = $('#deduction_reason').val();
            if (!deductionReason) {
                $('#deduction_reason').addClass('is-invalid');
                $('#deduction_reason_error').text('Please provide a reason for the deduction');
                isValid = false;
            }
        }
        
        return isValid;
    }
    
    // Helper functions
    function formatCurrency(amount) {
        return new Intl.NumberFormat('en-KE', {
            style: 'currency',
            currency: 'KES',
            minimumFractionDigits: 2
        }).format(amount);
    }
    
    function formatDate(dateString) {
        return new Date(dateString).toLocaleDateString('en-KE', {
            year: 'numeric',
            month: 'short',
            day: 'numeric'
        });
    }
    
    function escapeHtml(text) {
        if (!text) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    function showLoader() {
        $('#loadingOverlay').css('display', 'flex');
    }
    
    function hideLoader() {
        $('#loadingOverlay').fadeOut();
    }
    
    function showToast(type, message) {
        const bgColor = type === 'success' ? '#28a745' : (type === 'error' ? '#dc3545' : '#ffc107');
        const icon = type === 'success' ? 'fa-check-circle' : (type === 'error' ? 'fa-exclamation-circle' : 'fa-info-circle');
        
        const toastHtml = `
            <div class="toast align-items-center text-white border-0 position-fixed" style="top: 20px; right: 20px; z-index: 10000; background: ${bgColor}; border-radius: 0.5rem;" role="alert" data-bs-autohide="true" data-bs-delay="5000">
                <div class="d-flex">
                    <div class="toast-body">
                        <i class="fas ${icon} me-2"></i> ${message}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                </div>
            </div>
        `;
        
        $('body').append(toastHtml);
        const toast = $('.toast').last();
        const bsToast = new bootstrap.Toast(toast, { autohide: true, delay: 5000 });
        bsToast.show();
        
        toast.on('hidden.bs.toast', function() { $(this).remove(); });
    }
});
</script>
@endpush