@extends('layouts.app')
@section('title','Performance Evaluation')
@section('page-title','Performance Evaluation')

@section('content')
<div class="page-header">
    <div class="d-flex align-items-center justify-content-between flex-wrap gap-2">
        <div>
            <h1>New Evaluation</h1>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('performance.index') }}">Evaluations</a></li>
                    <li class="breadcrumb-item active">New</li>
                </ol>
            </nav>
        </div>
        <a href="{{ route('performance.index') }}" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-1"></i>Back</a>
    </div>
</div>

<form method="POST" action="{{ route('performance.store') }}">
@csrf
<div class="row g-3">
    <div class="col-12 col-lg-8">
        <!-- Employee & Period -->
        <div class="card mb-3">
            <div class="card-header"><i class="bi bi-person-check me-2 text-primary"></i>Evaluation Details</div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-12 col-sm-6">
                        <label class="form-label">Employee <span class="text-danger">*</span></label>
                        <select name="employee_id" class="form-select" required>
                            <option value="">— Select Employee —</option>
                            @foreach($employees as $emp)
                            <option value="{{ $emp->id }}" {{ old('employee_id') == $emp->id ? 'selected':'' }}>{{ $emp->full_name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-12 col-sm-6">
                        <label class="form-label">Evaluation Period <span class="text-danger">*</span></label>
                        <select name="period_id" class="form-select" required>
                            <option value="">— Select Period —</option>
                            @foreach($periods as $p)
                            <option value="{{ $p->id }}" {{ old('period_id') == $p->id ? 'selected':'' }}>{{ $p->name }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
            </div>
        </div>

        <!-- Scoring -->
        <div class="card mb-3">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span><i class="bi bi-sliders me-2 text-primary"></i>Performance Criteria</span>
                <span class="badge bg-primary" id="totalScoreBadge">Total: 0</span>
            </div>
            <div class="card-body">
                @foreach($criteria->groupBy('category') as $category => $items)
                <div class="mb-4">
                    <div class="text-uppercase fw-bold mb-3" style="font-size:.7rem;letter-spacing:.1em;color:#64748b;border-bottom:2px solid #f0f4f8;padding-bottom:.5rem;">
                        {{ $category }}
                    </div>
                    @foreach($items as $c)
                    <div class="mb-4">
                        <div class="d-flex justify-content-between align-items-center mb-1">
                            <label class="form-label mb-0 fw-semibold" style="font-size:.88rem;">{{ $c->name }}</label>
                            <span class="badge bg-light text-dark" id="score-display-{{ $c->id }}">0 / {{ $c->max_score }}</span>
                        </div>
                        <input type="range" class="form-range score-slider" name="scores[{{ $c->id }}]"
                            min="0" max="{{ $c->max_score }}" value="{{ old("scores.{$c->id}", 0) }}"
                            data-max="{{ $c->max_score }}" data-id="{{ $c->id }}"
                            oninput="updateScore(this)">
                        <input type="text" name="score_comments[{{ $c->id }}]" class="form-control form-control-sm mt-1"
                            placeholder="Optional comment for this criterion…" value="{{ old("score_comments.{$c->id}") }}">
                    </div>
                    @endforeach
                </div>
                @endforeach
            </div>
        </div>

        <!-- Comments -->
        <div class="card">
            <div class="card-header"><i class="bi bi-chat-text me-2 text-primary"></i>Evaluator Comments</div>
            <div class="card-body">
                <div class="mb-3">
                    <label class="form-label">Overall Comments</label>
                    <textarea name="evaluator_comments" class="form-control" rows="4" placeholder="Provide a comprehensive summary of the employee's performance…">{{ old('evaluator_comments') }}</textarea>
                </div>
                <div class="mb-3">
                    <label class="form-label">Development Goals</label>
                    <textarea name="development_goals" class="form-control" rows="3" placeholder="Set goals for the next evaluation period…">{{ old('development_goals') }}</textarea>
                </div>
                <div class="mb-0">
                    <label class="form-label">Training Needs Identified</label>
                    <textarea name="training_needs" class="form-control" rows="3" placeholder="List any training programs recommended…">{{ old('training_needs') }}</textarea>
                </div>
            </div>
        </div>
    </div>

    <!-- Rating Preview Sidebar -->
    <div class="col-12 col-lg-4">
        <div class="card mb-3 sticky-top" style="top:80px;">
            <div class="card-header"><i class="bi bi-speedometer me-2 text-primary"></i>Score Preview</div>
            <div class="card-body text-center">
                <div class="mb-3">
                    <canvas id="scoreGauge" width="180" height="180" style="max-width:160px;"></canvas>
                </div>
                <div class="display-6 fw-black mb-1" id="previewScore">0%</div>
                <div class="badge fs-6 mb-3" id="previewRating" style="background:#6c757d;">—</div>
                <hr>
                <div class="text-start">
                    <div class="d-flex justify-content-between py-2 border-bottom" style="font-size:.82rem;"><span>Excellent</span><span class="fw-semibold">≥ 90%</span></div>
                    <div class="d-flex justify-content-between py-2 border-bottom" style="font-size:.82rem;"><span>Very Good</span><span class="fw-semibold">75 – 89%</span></div>
                    <div class="d-flex justify-content-between py-2 border-bottom" style="font-size:.82rem;"><span>Satisfactory</span><span class="fw-semibold">60 – 74%</span></div>
                    <div class="d-flex justify-content-between py-2 border-bottom" style="font-size:.82rem;"><span>Needs Improvement</span><span class="fw-semibold">45 – 59%</span></div>
                    <div class="d-flex justify-content-between py-2" style="font-size:.82rem;"><span>Unsatisfactory</span><span class="fw-semibold">< 45%</span></div>
                </div>
                <button type="submit" class="btn btn-primary w-100 mt-3">
                    <i class="bi bi-send me-2"></i>Submit Evaluation
                </button>
            </div>
        </div>
    </div>
</div>
</form>
@endsection

@push('scripts')
<script>
const criteria = @json($criteria->map(fn($c) => ['id'=>$c->id,'max'=>$c->max_score,'weight'=>(float)$c->weight]));
const ratingColors = {'Excellent':'#198754','Very Good':'#0d6efd','Satisfactory':'#0dcaf0','Needs Improvement':'#ffc107','Unsatisfactory':'#dc3545'};

function updateScore(el) {
    const id = el.dataset.id, max = el.dataset.max, val = parseInt(el.value);
    document.getElementById('score-display-'+id).textContent = val + ' / ' + max;
    recalcTotal();
}

function recalcTotal() {
    let totalWeighted = 0, totalWeight = 0;
    criteria.forEach(c => {
        const el = document.querySelector(`input[name="scores[${c.id}]"]`);
        const score = el ? parseInt(el.value) : 0;
        totalWeighted += (score / c.max) * 100 * c.weight;
        totalWeight += c.weight;
    });
    const pct = totalWeight > 0 ? totalWeighted / totalWeight : 0;
    document.getElementById('previewScore').textContent = Math.round(pct) + '%';

    let rating = 'Unsatisfactory';
    if (pct >= 90) rating = 'Excellent';
    else if (pct >= 75) rating = 'Very Good';
    else if (pct >= 60) rating = 'Satisfactory';
    else if (pct >= 45) rating = 'Needs Improvement';

    const rBadge = document.getElementById('previewRating');
    rBadge.textContent = rating;
    rBadge.style.background = ratingColors[rating] || '#6c757d';

    document.getElementById('totalScoreBadge').textContent = 'Score: ' + Math.round(pct) + '%';
}

// Initialize
document.querySelectorAll('.score-slider').forEach(s => s.addEventListener('input', () => updateScore(s)));
recalcTotal();
</script>
@endpush
