@extends('layouts.app')
@section('title','Employees')
@section('breadcrumb')
<li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
<li class="breadcrumb-item active">Employees</li>
@endsection

@push('styles')
@include('partials.report-datepicker-assets')
<style>
    .employee-form-modal {
        width: min(1140px, calc(100vw - 1.5rem));
        max-width: none;
        height: calc(100vh - 1.5rem);
        margin: 0.75rem auto;
    }
    .employee-form-modal .modal-content {
        height: 100%;
        display: flex;
        flex-direction: column;
        overflow: hidden;
    }
    .employee-form-modal .employee-form-shell {
        display: flex;
        flex-direction: column;
        flex: 1 1 auto;
        min-height: 0;
        overflow: hidden;
    }
    .employee-form-modal .modal-body {
        flex: 1 1 auto;
        min-height: 0;
        overflow-y: auto;
        overscroll-behavior: contain;
    }
    .employee-form-modal .modal-header,
    .employee-form-modal .modal-footer {
        flex-shrink: 0;
    }
    .employee-form-modal .employee-form-tabs {
        position: sticky;
        top: 0;
        z-index: 2;
        background: var(--bs-body-bg, #fff);
        padding-top: 0.25rem;
        margin-bottom: 1rem !important;
    }
</style>
@endpush

@section('content')
<div class="page-header">
    <div>
        <h1 class="page-title">Employees</h1>
        <p class="page-subtitle">{{ $stats['total'] }} total &nbsp;·&nbsp; <span class="text-success">{{ $stats['active'] }} active</span></p>
    </div>
    @if(auth()->user()->hasPermission('masters','create'))
    <a href="{{ route('masters.employees.index', ['open' => 'create']) }}" class="btn btn-primary">
        <i class="bi bi-plus-lg me-1"></i>New Employee
    </a>
    @endif
</div>

@if(session('success'))
<div class="alert alert-success alert-dismissible d-flex gap-2 mb-3">
    <i class="bi bi-check-circle flex-shrink-0"></i><div>{{ session('success') }}</div>
    <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert"></button>
</div>
@endif

<div class="card mb-3"><div class="card-body py-2 px-3">
<form method="GET" id="employeeListFilters">
<div class="row g-2 align-items-center mb-2">
<div class="col-12 col-md-5"><input type="text" name="search" class="form-control form-control-sm" placeholder="Search name, code, email…" value="{{ request('search') }}"></div>
<div class="col-6 col-md-2"><select name="status" class="form-select form-select-sm filter-auto"><option value="">All Status</option><option value="active" {{ request('status')==='active'?'selected':'' }}>Active</option><option value="inactive" {{ request('status')==='inactive'?'selected':'' }}>Inactive</option></select></div>
<div class="col-3 col-md-1"><button type="submit" class="btn btn-primary btn-sm w-100"><i class="bi bi-search"></i></button></div>
<div class="col-3 col-md-1"><a href="{{ route('masters.employees.index') }}" class="btn btn-outline-secondary btn-sm w-100" title="Clear filters"><i class="bi bi-x-lg"></i></a></div>
</div>
<div class="row g-2 align-items-center">
<div class="col-6 col-md-4 col-lg"><select name="department" class="form-select form-select-sm filter-auto" aria-label="Department"><option value="">All Departments</option>@foreach($departmentOptions as $name => $label)<option value="{{ $name }}" {{ request('department')===$name?'selected':'' }}>{{ $label }}</option>@endforeach</select></div>
<div class="col-6 col-md-4 col-lg"><select name="designation" class="form-select form-select-sm filter-auto" aria-label="Designation"><option value="">All Designations</option>@foreach($designationOptions as $name => $label)<option value="{{ $name }}" {{ request('designation')===$name?'selected':'' }}>{{ $label }}</option>@endforeach</select></div>
<div class="col-6 col-md-4 col-lg"><select name="project" class="form-select form-select-sm filter-auto" aria-label="Project"><option value="">All Projects</option>@foreach($projectOptions as $name => $label)<option value="{{ $name }}" {{ request('project')===$name?'selected':'' }}>{{ $label }}</option>@endforeach</select></div>
<div class="col-6 col-md-4 col-lg"><select name="branch" class="form-select form-select-sm filter-auto" aria-label="Branch"><option value="">All Branches</option>@foreach($branchOptions as $name => $label)<option value="{{ $name }}" {{ request('branch')===$name?'selected':'' }}>{{ $label }}</option>@endforeach</select></div>
<div class="col-6 col-md-4 col-lg"><select name="blood_group" class="form-select form-select-sm filter-auto" aria-label="Blood group"><option value="">All Blood Groups</option>@foreach($bloodGroupOptions as $name => $label)<option value="{{ $name }}" {{ request('blood_group')===$name?'selected':'' }}>{{ $label }}</option>@endforeach</select></div>
</div>
</form></div></div>

<div class="card"><div class="card-body p-0"><div class="table-responsive">
<table class="table table-hover mb-0" style="min-width:980px">
<thead class="table-light">
<tr>
    <th class="ps-4">Employee ID</th>
    <th>Display Name</th>
    <th class="d-none d-md-table-cell">Email</th>
    <th class="d-none d-lg-table-cell">Phone</th>
    <th class="d-none d-md-table-cell">Designation</th>
    <th class="d-none d-lg-table-cell">Department</th>
    <th class="d-none d-xl-table-cell">Project</th>
    <th class="d-none d-xl-table-cell">Branch</th>
    <th class="d-none d-lg-table-cell">Blood Group</th>
    <th>Status</th>
    <th class="text-end pe-4">Actions</th>
</tr>
</thead>
<tbody>
@forelse($employees as $emp)
<tr>
<td class="ps-4 text-muted" style="font-size:13px">{{ $emp->code ?? '—' }}</td>
<td><div class="fw-semibold" style="font-size:13.5px">{{ $emp->display_name ?: $emp->name }}</div></td>
<td class="d-none d-md-table-cell" style="font-size:13px">{{ $emp->email ?? '—' }}</td>
<td class="d-none d-lg-table-cell" style="font-size:13px">{{ $emp->phone ?? $emp->mobile ?? '—' }}</td>
<td class="d-none d-md-table-cell" style="font-size:13px">{{ $emp->designation ?? '—' }}</td>
<td class="d-none d-lg-table-cell" style="font-size:13px">{{ $emp->department ?? '—' }}</td>
<td class="d-none d-xl-table-cell" style="font-size:13px">{{ $emp->project ?? '—' }}</td>
<td class="d-none d-xl-table-cell" style="font-size:13px">{{ $emp->branch ?? '—' }}</td>
<td class="d-none d-lg-table-cell" style="font-size:13px">{{ $emp->blood_group ?? '—' }}</td>
<td><span class="badge" style="font-size:11px;background:{{ $emp->is_active?'#d1e7dd':'#e9ecef' }};color:{{ $emp->is_active?'#0a3622':'#495057' }}">{{ $emp->is_active?'Active':'Inactive' }}</span></td>
<td class="text-end pe-3"><div class="d-flex justify-content-end gap-1">
@if(auth()->user()->hasPermission('masters','edit'))
<a href="{{ route('masters.employees.edit',$emp) }}" class="btn btn-outline-secondary btn-sm" title="Edit"><i class="bi bi-pencil"></i></a>
<form method="POST" action="{{ route('masters.employees.toggle',$emp) }}">@csrf @method('PATCH')<button type="submit" class="btn btn-sm {{ $emp->is_active?'btn-outline-warning':'btn-outline-success' }}" title="{{ $emp->is_active?'Deactivate':'Activate' }}"><i class="bi bi-{{ $emp->is_active?'eye-slash':'eye' }}"></i></button></form>
@endif
@if(auth()->user()->hasPermission('masters','delete'))
<form method="POST" action="{{ route('masters.employees.destroy',$emp) }}" onsubmit="return confirm('Delete {{ addslashes($emp->display_name ?: $emp->name) }}?')">@csrf @method('DELETE')<button type="submit" class="btn btn-outline-danger btn-sm"><i class="bi bi-trash"></i></button></form>
@endif
</div></td>
</tr>
@empty
<tr><td colspan="11" class="text-center py-5 text-muted"><i class="bi bi-people display-5 d-block mb-2"></i>No employees found.@if(auth()->user()->hasPermission('masters','create'))<div class="mt-2"><a href="{{ route('masters.employees.index', ['open' => 'create']) }}" class="btn btn-primary btn-sm">Add First Employee</a></div>@endif</td></tr>
@endforelse
</tbody></table></div>
@if($employees->hasPages())<div class="px-4 py-3 border-top">{{ $employees->links() }}</div>@endif
</div></div>

@include('masters.employees._form-modal', ['employee' => $formEmployee ?? null])
@endsection

@push('scripts')
@include('partials.report-datepicker-init')
<script>
(function () {
    function money(n) {
        return (Math.round((n + Number.EPSILON) * 100) / 100).toFixed(2);
    }

    function sumInputs(selector) {
        let total = 0;
        document.querySelectorAll(selector).forEach(function (el) {
            total += parseFloat(el.value || '0') || 0;
        });
        return total;
    }

    function recalcPayrollTotals() {
        const totalEarningsEl = document.getElementById('totalEarnings');
        if (!totalEarningsEl) return;

        const earnings = sumInputs('.emp-earning-amount');
        const deductions = sumInputs('.emp-deduction-amount');
        const net = earnings - deductions;

        document.getElementById('totalEarnings').value = money(earnings);
        document.getElementById('totalDeductions').value = money(deductions);
        document.getElementById('netSalary').value = money(net);

        let irregularAnnual = 0;
        document.querySelectorAll('#tab-payroll tbody tr').forEach(function (row) {
            const amountEl = row.querySelector('.emp-irregular-amount');
            const qtyEl = row.querySelector('.emp-irregular-qty');
            const annualEl = row.querySelector('.emp-irregular-annual');
            if (!amountEl || !qtyEl || !annualEl) return;
            const annual = (parseFloat(amountEl.value || '0') || 0) * (parseFloat(qtyEl.value || '0') || 0);
            annualEl.value = money(annual);
            irregularAnnual += annual;
        });

        document.getElementById('irregularAnnualTotal').value = money(irregularAnnual);
        document.getElementById('annualNonPayrollTotal').value = money(irregularAnnual);
        document.getElementById('annualEarnings').value = money(earnings * 12);
        document.getElementById('totalAnnualIncome').value = money((earnings * 12) + irregularAnnual);
    }

    function syncComponentName(select) {
        const hidden = select.closest('td')?.querySelector('.emp-component-name');
        if (!hidden) return;
        const option = select.options[select.selectedIndex];
        hidden.value = option?.dataset?.name || '';
    }

    document.getElementById('employeeForm')?.addEventListener('input', recalcPayrollTotals);
    document.getElementById('employeeForm')?.addEventListener('change', function (event) {
        if (event.target.classList.contains('emp-component-select')) {
            syncComponentName(event.target);
        }
        recalcPayrollTotals();
    });

    document.querySelectorAll('.emp-component-select').forEach(syncComponentName);

    function updatePayrollHeading() {
        const code = document.querySelector('[name="code"]')?.value || 'Employee_ID';
        const name = document.querySelector('[name="display_name"]')?.value || 'Employee_Name';
        const heading = document.getElementById('payrollComponentHeading');
        if (heading) {
            heading.textContent = 'Salary Component Details of ' + code + ' + ' + name + ' (Per Month)';
        }
    }

    document.getElementById('employeeForm')?.addEventListener('input', function (event) {
        if (event.target.matches('[name="code"], [name="display_name"]')) {
            updatePayrollHeading();
        }
    });

    const modalEl = document.getElementById('employeeFormModal');
    if (modalEl) {
        modalEl.addEventListener('shown.bs.modal', function () {
            modalEl.querySelector('.modal-body')?.scrollTo(0, 0);
            if (window.axisInitReportDatepickers) {
                window.axisInitReportDatepickers();
            }
            recalcPayrollTotals();
            updatePayrollHeading();
        });
        document.getElementById('employeeFormTabs')?.addEventListener('shown.bs.tab', function () {
            modalEl.querySelector('.modal-body')?.scrollTo(0, 0);
        });
    }

    recalcPayrollTotals();
    updatePayrollHeading();

    function showEmployeeModal() {
        if (!modalEl) return;
        if (typeof bootstrap === 'undefined') {
            setTimeout(showEmployeeModal, 50);
            return;
        }
        bootstrap.Modal.getOrCreateInstance(modalEl).show();
    }

    @if($errors->any() || filled($formEmployee ?? null) || request('open') === 'create')
    showEmployeeModal();
    @endif

    document.querySelectorAll('#employeeListFilters .filter-auto').forEach(function (el) {
        el.addEventListener('change', function () {
            document.getElementById('employeeListFilters')?.submit();
        });
    });
})();
</script>
@endpush
