@extends('layouts.app')
@section('title','My Dashboard')
@section('page-title','My Dashboard')

@push('styles')
<style>
.dash-card { border:none;border-radius:16px;box-shadow:0 4px 20px rgba(0,0,0,.18);overflow:hidden; }
.dash-card-dark { background:linear-gradient(145deg,#0a1628,#0f2140);color:#fff; }
.dash-card-mid  { background:linear-gradient(145deg,#0d1b2e,#122040);color:#fff; }
.dch {
    background:rgba(255,255,255,.06);border-bottom:1px solid rgba(255,255,255,.08);
    padding:.9rem 1.25rem;font-weight:700;font-size:.88rem;color:rgba(255,255,255,.92);
    display:flex;align-items:center;justify-content:space-between;
}
.dcb { padding:1.1rem 1.25rem; }
/* Leave balance bars */
.bal-label { font-size:.79rem;font-weight:700;color:rgba(255,255,255,.85); }
.bal-sub   { font-size:.68rem;color:rgba(255,255,255,.4); }
.bal-bar   { background:rgba(255,255,255,.1);border-radius:5px;height:7px;overflow:hidden; }
/* Dark table */
.dark-table thead th {
    background:rgba(255,255,255,.05)!important;border-bottom:1px solid rgba(255,255,255,.1)!important;
    color:rgba(255,255,255,.5)!important;font-size:.68rem;text-transform:uppercase;letter-spacing:.07em;
}
.dark-table tbody td {
    border-bottom:1px solid rgba(255,255,255,.06)!important;
    color:rgba(255,255,255,.82)!important;background:transparent!important;
}
.dark-table tbody tr:last-child td { border-bottom:none!important; }
/* Eval ring helper */
.eval-ring {
    width:84px;height:84px;border-radius:50%;
    display:flex;align-items:center;justify-content:center;
    margin:0 auto .6rem;
}
/* Training list */
.training-row {
    display:flex;align-items:flex-start;justify-content:space-between;
    gap:.75rem;padding:.65rem 1.25rem;border-bottom:1px solid rgba(255,255,255,.06);
}
.training-row:last-child { border-bottom:none; }
@keyframes spin { to { transform: rotate(360deg); } }
</style>
@endpush

@section('content')

@if(isset($setup_required) && $setup_required)
<div class="alert alert-warning d-flex gap-2">
    <i class="bi bi-exclamation-triangle-fill mt-1"></i>
    <div>Your employee profile has not been set up yet. Please contact HR.
    <a href="{{ route('profile') }}" class="alert-link ms-1">Go to Profile →</a></div>
</div>
@else

<div class="page-header">
    <div class="d-flex align-items-center gap-3 flex-wrap">
        <div class="avatar avatar-xl" style="background:linear-gradient(135deg,#003366,#0055b3);color:#fff;">
            {{ strtoupper(substr($employee->first_name,0,1).substr($employee->last_name,0,1)) }}
        </div>
        <div>
            <h1 class="mb-0">Welcome, {{ $employee->first_name }}!</h1>
            <div style="font-size:.88rem;color:var(--text-2);margin-top:.2rem;">
                <span class="fw-semibold">{{ $employee->position }}</span>
                @if($employee->department) · {{ $employee->department->name }}@endif
                · <span style="color:var(--ul-primary);font-weight:700;">{{ $employee->employee_number }}</span>
            </div>
        </div>
    </div>
</div>

{{-- Stat cards --}}
<div class="row g-3 mb-4">
    <div class="col-6 col-md-3">
        <div class="stat-card sc-primary"><div class="stat-icon"><i class="bi bi-clock"></i></div>
            <div class="stat-value">{{ $employee->years_of_service ?? 0 }}</div><div class="stat-label">Years of Service</div></div>
    </div>
    <div class="col-6 col-md-3">
        <div class="stat-card sc-success"><div class="stat-icon"><i class="bi bi-person-check"></i></div>
            <div class="stat-value">{{ $attendance_summary['present'] ?? 0 }}</div><div class="stat-label">Present (Mo.)</div></div>
    </div>
    <div class="col-6 col-md-3">
        <div class="stat-card sc-warning"><div class="stat-icon"><i class="bi bi-calendar-check"></i></div>
            <div class="stat-value">{{ $pending_leaves }}</div><div class="stat-label">Pending Leaves</div></div>
    </div>
    <div class="col-6 col-md-3">
        <div class="stat-card {{ $discipline_active > 0 ? 'sc-danger' : 'sc-teal' }}">
            <div class="stat-icon"><i class="bi bi-shield-check"></i></div>
            <div class="stat-value">{{ $discipline_active }}</div><div class="stat-label">Active Cases</div></div>
    </div>
</div>

<div class="row g-3">
    {{-- Attendance + clock --}}
    <div class="col-12 col-md-6 col-lg-4">
        <div class="dash-card dash-card-dark h-100">
            <div class="dch"><span><i class="bi bi-clock-history me-2" style="color:#60a5fa;"></i>Attendance — {{ now()->format('M Y') }}</span></div>
            <div class="dcb">

                {{-- ── Clock In / Out form ── --}}
                @php $gpsRestrict = config('hrms.gps_restrict'); @endphp

                <form method="POST" action="{{ route('attendance.clock') }}" class="mb-3" id="clockForm">
                    @csrf
                    {{-- Hidden fields populated by JS before submit --}}
                    <input type="hidden" name="gps_lat" id="gpsLat">
                    <input type="hidden" name="gps_lng" id="gpsLng">

                    @if($gpsRestrict)
                    {{-- Location status indicator --}}
                    <div id="gpsStatus" class="d-flex align-items-center gap-2 mb-2 px-1"
                         style="font-size:.75rem;color:rgba(255,255,255,.5);">
                        <div id="gpsSpinner"
                             style="width:8px;height:8px;border-radius:50%;border:2px solid rgba(255,255,255,.3);border-top-color:#60a5fa;animation:spin .8s linear infinite;flex-shrink:0;"></div>
                        <span id="gpsStatusText">Checking your location…</span>
                    </div>
                    @endif

                    <button type="submit" id="clockBtn" class="btn btn-primary w-100 py-2"
                        @if($gpsRestrict) disabled @endif>
                        <i class="bi bi-fingerprint me-2"></i>
                        <span id="clockBtnLabel">Clock In / Out</span>
                    </button>
                </form>
                <div style="text-align:center;font-size:.78rem;color:rgba(255,255,255,.4);margin-bottom:1rem;">
                    {{ now()->format('h:i A · D, M j') }}
                </div>
                <canvas id="attChart" height="160"></canvas>
                <div class="row g-2 mt-2 text-center">
                    <div class="col-6">
                        <div style="background:rgba(74,222,128,.12);border-radius:10px;padding:.55rem;">
                            <div class="fw-bold" style="color:#4ade80;">{{ $attendance_summary['present'] ?? 0 }}</div>
                            <div style="font-size:.65rem;color:rgba(255,255,255,.4);">Present</div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div style="background:rgba(248,113,113,.12);border-radius:10px;padding:.55rem;">
                            <div class="fw-bold" style="color:#f87171;">{{ $attendance_summary['absent'] ?? 0 }}</div>
                            <div style="font-size:.65rem;color:rgba(255,255,255,.4);">Absent</div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div style="background:rgba(251,191,36,.12);border-radius:10px;padding:.55rem;">
                            <div class="fw-bold" style="color:#fbbf24;">{{ $attendance_summary['late'] ?? 0 }}</div>
                            <div style="font-size:.65rem;color:rgba(255,255,255,.4);">Late</div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div style="background:rgba(96,165,250,.12);border-radius:10px;padding:.55rem;">
                            <div class="fw-bold" style="color:#60a5fa;">{{ $attendance_summary['on_leave'] ?? 0 }}</div>
                            <div style="font-size:.65rem;color:rgba(255,255,255,.4);">On Leave</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{-- Leave balances --}}
    <div class="col-12 col-md-6 col-lg-4">
        <div class="dash-card dash-card-mid h-100">
            <div class="dch">
                <span><i class="bi bi-calendar-heart me-2" style="color:#f87171;"></i>Leave Balances</span>
                <a href="{{ route('leaves.create') }}" style="font-size:.75rem;color:rgba(255,255,255,.5);text-decoration:none;border:1px solid rgba(255,255,255,.18);border-radius:7px;padding:.25rem .7rem;">Request</a>
            </div>
            <div class="dcb">
                @forelse($leave_balances as $balance)
                <div class="mb-3">
                    <div class="d-flex justify-content-between mb-1">
                        <span class="bal-label d-flex align-items-center gap-2">
                            <span style="width:10px;height:10px;background:{{ $balance->leaveType->color ?? '#6c757d' }};border-radius:3px;display:inline-block;flex-shrink:0;"></span>
                            {{ $balance->leaveType->name }}
                        </span>
                        <span class="bal-sub">{{ $balance->taken_days }}/{{ $balance->entitled_days }} days</span>
                    </div>
                    <div class="bal-bar">
                        @php $pct = $balance->entitled_days > 0 ? ($balance->taken_days/$balance->entitled_days)*100 : 0; @endphp
                        <div style="height:100%;width:{{ min($pct,100) }}%;background:{{ $balance->leaveType->color ?? '#6c757d' }};border-radius:5px;transition:width .5s;"></div>
                    </div>
                    <div class="bal-sub mt-1">{{ max(0,$balance->remaining) }} days remaining</div>
                </div>
                @empty
                <div style="text-align:center;color:rgba(255,255,255,.4);font-size:.82rem;padding:1rem 0;">Leave balances not configured</div>
                @endforelse
            </div>
        </div>
    </div>

    {{-- Latest evaluation --}}
    <div class="col-12 col-md-6 col-lg-4">
        <div class="dash-card dash-card-dark h-100">
            <div class="dch"><span><i class="bi bi-bar-chart-steps me-2" style="color:#a78bfa;"></i>Latest Evaluation</span></div>
            <div class="dcb">
                @if($latest_evaluation)
                @php
                    $score = $latest_evaluation->weighted_score ? round($latest_evaluation->weighted_score) : 0;
                    $rMap  = ['excellent'=>'#4ade80','very_good'=>'#60a5fa','satisfactory'=>'#22d3ee','needs_improvement'=>'#fbbf24','unsatisfactory'=>'#f87171'];
                    $rCol  = $rMap[$latest_evaluation->rating ?? ''] ?? '#94a3b8';
                @endphp
                <div class="text-center mb-3">
                    <div class="eval-ring" style="background:conic-gradient({{ $rCol }} {{ $score*3.6 }}deg,rgba(255,255,255,.08) 0);box-shadow:0 0 0 4px rgba(255,255,255,.05);">
                        <div style="width:66px;height:66px;border-radius:50%;background:linear-gradient(145deg,#0a1628,#0f2140);display:flex;align-items:center;justify-content:center;">
                            <span style="font-weight:900;font-size:1.15rem;color:{{ $rCol }};">{{ $score }}%</span>
                        </div>
                    </div>
                    <div class="fw-bold mb-1" style="color:rgba(255,255,255,.9);">{{ $latest_evaluation->rating_label }}</div>
                    <span class="badge" style="background:{{ $rCol }};color:#000;font-size:.72rem;">{{ $latest_evaluation->period->name ?? '' }}</span>
                </div>
                @if($latest_evaluation->status === 'submitted')
                <form method="POST" action="{{ route('performance.acknowledge', $latest_evaluation) }}">
                    @csrf
                    <button type="submit" class="btn btn-success w-100 btn-sm">
                        <i class="bi bi-check2-circle me-1"></i>Acknowledge Evaluation
                    </button>
                </form>
                @else
                <a href="{{ route('performance.show', $latest_evaluation) }}" class="btn btn-sm w-100"
                   style="background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.18);color:rgba(255,255,255,.8);">
                    <i class="bi bi-eye me-1"></i>View Full Evaluation
                </a>
                @endif
                @else
                <div class="text-center py-3" style="color:rgba(255,255,255,.4);">
                    <i class="bi bi-bar-chart d-block mb-1" style="font-size:2rem;"></i>
                    No evaluations yet
                </div>
                @endif

                {{-- Upcoming trainings --}}
                <div class="dch" style="margin:1.1rem -1.25rem 0;border-top:1px solid rgba(255,255,255,.08);border-bottom:none;">
                    <span><i class="bi bi-mortarboard me-2" style="color:#22d3ee;"></i>Upcoming Trainings</span>
                </div>
                @forelse($upcoming_trainings as $t)
                <div class="training-row">
                    <div>
                        <div style="font-weight:700;font-size:.83rem;color:rgba(255,255,255,.88);">{{ $t->title }}</div>
                        <div style="font-size:.72rem;color:rgba(255,255,255,.4);">{{ $t->start_date->format('M d') }} · {{ ucfirst($t->type) }}</div>
                    </div>
                    <a href="{{ route('training.show',$t) }}" style="font-size:.72rem;color:rgba(255,255,255,.5);text-decoration:none;white-space:nowrap;border:1px solid rgba(255,255,255,.15);border-radius:6px;padding:.2rem .55rem;">View</a>
                </div>
                @empty
                <div style="text-align:center;padding:.9rem 0;font-size:.8rem;color:rgba(255,255,255,.35);">No upcoming trainings</div>
                @endforelse
            </div>
        </div>
    </div>

    {{-- Recent leaves --}}
    <div class="col-12">
        <div class="dash-card dash-card-mid">
            <div class="dch">
                <span><i class="bi bi-calendar-event me-2" style="color:#60a5fa;"></i>My Recent Leave Requests</span>
                <a href="{{ route('leaves.index') }}" style="font-size:.75rem;color:rgba(255,255,255,.5);text-decoration:none;border:1px solid rgba(255,255,255,.18);border-radius:7px;padding:.25rem .7rem;">View All</a>
            </div>
            <div class="table-responsive">
                <table class="table mb-0 dark-table">
                    <thead><tr><th>Leave #</th><th>Type</th><th class="d-none d-md-table-cell">From</th><th class="d-none d-md-table-cell">To</th><th>Days</th><th>Status</th><th></th></tr></thead>
                    <tbody>
                    @forelse($recent_leaves as $leave)
                    <tr>
                        <td class="fw-semibold" style="color:#60a5fa;">{{ $leave->leave_number }}</td>
                        <td><span class="badge" style="background:{{ $leave->leaveType->color ?? '#6c757d' }};color:#fff;">{{ $leave->leaveType->name }}</span></td>
                        <td class="d-none d-md-table-cell">{{ $leave->date_from->format('M d, Y') }}</td>
                        <td class="d-none d-md-table-cell">{{ $leave->date_to->format('M d, Y') }}</td>
                        <td>{{ $leave->total_days }}</td>
                        <td><span class="badge bg-{{ $leave->status_badge }}">{{ $leave->status_label }}</span></td>
                        <td><a href="{{ route('leaves.show',$leave) }}" class="btn btn-sm btn-icon" style="background:rgba(255,255,255,.1);border:none;color:rgba(255,255,255,.7);"><i class="bi bi-eye"></i></a></td>
                    </tr>
                    @empty
                    <tr><td colspan="7" style="text-align:center;color:rgba(255,255,255,.35);padding:1.25rem;">No leave requests found</td></tr>
                    @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
@endif
@endsection

@push('scripts')
<script>
@if(!isset($setup_required))
const att = @json($attendance_summary);
new Chart(document.getElementById('attChart'), {
    type:'doughnut',
    data:{
        labels:['Present','Absent','Late','On Leave'],
        datasets:[{ data:[att.present,att.absent,att.late,att.on_leave],
            backgroundColor:['#4ade80','#f87171','#fbbf24','#60a5fa'], borderWidth:0 }]
    },
    options:{responsive:true,cutout:'65%',plugins:{legend:{position:'bottom',labels:{color:'rgba(255,255,255,.55)',font:{size:10},boxWidth:10,padding:10}}}}
});
@endif

// ── GPS Clock Restriction ───────────────────────────────────────────────────
@if(config('hrms.gps_restrict'))
(function () {
    const ALLOWED_LAT    = {{ (float) config('hrms.gps_lat') }};
    const ALLOWED_LNG    = {{ (float) config('hrms.gps_lng') }};
    const RADIUS_METERS  = {{ (int) config('hrms.gps_radius_meters', 150) }};

    const btn         = document.getElementById('clockBtn');
    const label       = document.getElementById('clockBtnLabel');
    const statusEl    = document.getElementById('gpsStatus');
    const statusText  = document.getElementById('gpsStatusText');
    const spinner     = document.getElementById('gpsSpinner');
    const latInput    = document.getElementById('gpsLat');
    const lngInput    = document.getElementById('gpsLng');

    // Haversine distance in metres
    function haversine(lat1, lng1, lat2, lng2) {
        const R    = 6371000;
        const dLat = (lat2 - lat1) * Math.PI / 180;
        const dLng = (lng2 - lng1) * Math.PI / 180;
        const a    = Math.sin(dLat/2)**2
                   + Math.cos(lat1 * Math.PI/180) * Math.cos(lat2 * Math.PI/180)
                   * Math.sin(dLng/2)**2;
        return R * 2 * Math.asin(Math.sqrt(a));
    }

    function setAllowed(distance) {
        latInput.value = window._gpsLat;
        lngInput.value = window._gpsLng;
        btn.disabled   = false;
        btn.style.background = '';
        label.textContent    = 'Clock In / Out';
        spinner.style.borderTopColor = '#4ade80';
        spinner.style.animation      = 'none';
        spinner.style.background     = '#4ade80';
        statusText.textContent = '\u2713 On-site (' + Math.round(distance) + ' m from office)';
        statusText.style.color = '#4ade80';
    }

    function setDenied(reason) {
        btn.disabled         = true;
        btn.style.background = 'rgba(239,68,68,.25)';
        label.textContent    = 'Not available — ' + reason;
        spinner.style.animation   = 'none';
        spinner.style.background  = '#f87171';
        spinner.style.borderColor = 'transparent';
        statusText.textContent    = '\u2717 ' + reason;
        statusText.style.color    = '#f87171';
    }

    function checkPosition(pos) {
        const lat  = pos.coords.latitude;
        const lng  = pos.coords.longitude;
        const acc  = pos.coords.accuracy; // accuracy radius in metres
        window._gpsLat = lat;
        window._gpsLng = lng;

        const dist = haversine(ALLOWED_LAT, ALLOWED_LNG, lat, lng);

        // If GPS accuracy is worse than allowed radius, warn but allow the
        // server to make the final call with the best available coordinates.
        if (dist <= RADIUS_METERS) {
            setAllowed(dist);
        } else {
            setDenied('outside office zone (' + Math.round(dist) + ' m away)');
        }
    }

    function onError(err) {
        const messages = {
            1: 'location access denied — please allow in browser settings',
            2: 'location unavailable — check your connection or device GPS',
            3: 'location request timed out — please refresh and try again',
        };
        setDenied(messages[err.code] || 'location error');
    }

    if (!navigator.geolocation) {
        setDenied('geolocation not supported by this browser');
        return;
    }

    // Poll every 30 s so the button re-enables if the employee moves into range
    function poll() {
        navigator.geolocation.getCurrentPosition(checkPosition, onError, {
            enableHighAccuracy: true,
            timeout:            10000,
            maximumAge:         20000,
        });
    }

    poll();
    setInterval(poll, 30000);
})();
@else
// GPS restriction is disabled — attach coordinates anyway (passive, no gate)
(function () {
    if (!navigator.geolocation) return;
    navigator.geolocation.getCurrentPosition(function(pos) {
        const l = document.getElementById('gpsLat');
        const g = document.getElementById('gpsLng');
        if (l) l.value = pos.coords.latitude;
        if (g) g.value = pos.coords.longitude;
    }, function(){}, { enableHighAccuracy: true, timeout: 8000, maximumAge: 30000 });
})();
@endif
</script>
@endpush
