<?php

namespace Database\Seeders;

use App\Models\Appraisal;
use App\Models\AppraisalPeriod;
use App\Models\Department;
use App\Models\KeyResultArea;
use App\Models\KpiLibrary;
use App\Models\User;
use App\Services\AppraisalService;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        // ── Departments ────────────────────────────
        $depts = [
            ['name' => 'Office of the Director General', 'code' => 'ODG'],
            ['name' => 'Administration & Human Resources', 'code' => 'AHR'],
            ['name' => 'Finance & Accounts', 'code' => 'FAD'],
            ['name' => 'Information & Communication Technology', 'code' => 'ICT'],
            ['name' => 'Policy, Planning & Research', 'code' => 'PPR'],
            ['name' => 'Automotive Development', 'code' => 'ADV'],
            ['name' => 'Standards & Regulations', 'code' => 'SAR'],
            ['name' => 'Procurement & Supply', 'code' => 'PSC'],
            ['name' => 'Legal Services', 'code' => 'LSD'],
            ['name' => 'Public Relations & Protocol', 'code' => 'PRP'],
        ];

        foreach ($depts as $d) {
            Department::create($d);
        }

        // ── Admin User ─────────────────────────────
        $admin = User::create([
            'surname' => 'System',
            'firstname' => 'Administrator',
            'email' => 'admin@naddc.gov.ng',
            'password' => 'password',
            'role' => 'admin',
            'designation' => 'System Administrator',
            'department_id' => 4, // ICT
            'is_active' => true,
        ]);

        // ── Director ────────────────────────────────
        $dg = User::create([
            'surname' => 'Ajayi',
            'firstname' => 'Olusola',
            'othername' => 'Adewale',
            'email' => 'ceo@naddc.gov.ng',
            'password' => 'password',
            'role' => 'director',
            'designation' => 'Director General / CEO',
            'ippis_no' => 'IPPIS001',
            'department_id' => 1,
            'is_active' => true,
        ]);

        // ── HOD ─────────────────────────────────────
        $hod = User::create([
            'surname' => 'Musa',
            'firstname' => 'Ibrahim',
            'othername' => 'Garba',
            'email' => 'hod.ict@naddc.gov.ng',
            'password' => 'password',
            'role' => 'department_head',
            'designation' => 'Director ICT',
            'ippis_no' => 'IPPIS002',
            'department_id' => 4,
            'supervisor_id' => $dg->id,
            'is_active' => true,
        ]);

        // ── Supervisor ──────────────────────────────
        $supervisor = User::create([
            'surname' => 'Okonkwo',
            'firstname' => 'Chukwuma',
            'othername' => 'Emeka',
            'email' => 'supervisor@naddc.gov.ng',
            'password' => 'password',
            'role' => 'supervisor',
            'designation' => 'Principal Dev Planning Officer (PDPO II)',
            'ippis_no' => 'IPPIS003',
            'department_id' => 4,
            'supervisor_id' => $hod->id,
            'is_active' => true,
        ]);

        // ── Staff Members ───────────────────────────
        $staff1 = User::create([
            'surname' => 'Adebayo',
            'firstname' => 'Funke',
            'othername' => 'Mary',
            'email' => 'funke.adebayo@naddc.gov.ng',
            'password' => 'password',
            'role' => 'staff',
            'designation' => 'Senior Software Developer',
            'ippis_no' => 'IPPIS004',
            'phone' => '+234 803 123 4567',
            'department_id' => 4,
            'supervisor_id' => $supervisor->id,
            'is_active' => true,
        ]);

        $staff2 = User::create([
            'surname' => 'Mohammed',
            'firstname' => 'Aisha',
            'othername' => 'Zainab',
            'email' => 'aisha.mohammed@naddc.gov.ng',
            'password' => 'password',
            'role' => 'staff',
            'designation' => 'Network Engineer',
            'ippis_no' => 'IPPIS005',
            'phone' => '+234 802 987 6543',
            'department_id' => 4,
            'supervisor_id' => $supervisor->id,
            'is_active' => true,
        ]);

        // Update department heads
        Department::where('id', 4)->update(['head_id' => $hod->id, 'director_id' => $dg->id]);
        Department::where('id', 1)->update(['director_id' => $dg->id]);

        // ── KRAs ────────────────────────────────────
        $kra1 = KeyResultArea::create(['name' => 'Service Delivery', 'description' => 'Quality and timeliness of service delivery']);
        $kra2 = KeyResultArea::create(['name' => 'Innovation & Technology', 'description' => 'Adoption and implementation of new technologies']);
        $kra3 = KeyResultArea::create(['name' => 'Capacity Building', 'description' => 'Staff development and training initiatives']);
        $kra4 = KeyResultArea::create(['name' => 'Stakeholder Engagement', 'description' => 'Collaboration with internal and external stakeholders']);
        $kra5 = KeyResultArea::create(['name' => 'Compliance & Governance', 'description' => 'Adherence to policies, regulations and standards']);

        // ── KPIs ────────────────────────────────────
        KpiLibrary::create(['name' => 'Task Completion Rate', 'unit_of_measurement' => '%', 'key_result_area_id' => $kra1->id]);
        KpiLibrary::create(['name' => 'Response Time', 'unit_of_measurement' => 'Hours', 'key_result_area_id' => $kra1->id]);
        KpiLibrary::create(['name' => 'System Uptime', 'unit_of_measurement' => '%', 'key_result_area_id' => $kra2->id]);
        KpiLibrary::create(['name' => 'Training Sessions Delivered', 'unit_of_measurement' => 'Count', 'key_result_area_id' => $kra3->id]);
        KpiLibrary::create(['name' => 'Report Submission Rate', 'unit_of_measurement' => '%', 'key_result_area_id' => $kra5->id]);

        // ── Appraisal Period ────────────────────────
        $period = AppraisalPeriod::create([
            'name' => 'January – December 2025',
            'start_date' => '2025-01-01',
            'end_date' => '2025-12-31',
            'status' => 'active',
            'description' => 'Federal Civil Service Standard Annual PMS Cycle for NADDC.',
            'created_by' => $admin->id,
        ]);

        $appraisalService = app(AppraisalService::class);

        // ── Seed Completed Appraisal for Funke Adebayo ───────────────
        $appraisal1 = Appraisal::create([
            'appraisal_period_id' => $period->id,
            'employee_id' => $staff1->id,
            'supervisor_id' => $supervisor->id,
            'counter_signing_officer_id' => $hod->id,
            'status' => 'completed',
            'employee_comment' => 'I exceeded targets set for digitizing PMS portal and maintained 99.8% portal availability.',
            'supervisor_comment' => 'Excellent delivery, highly proactive in problem solving and collaborative with colleagues.',
            'counter_signing_comment' => 'Commended for outstanding innovation and timely completion of key projects.',
            'strengths' => 'Strong architectural design skills, high work turnaround speed, good teamwork.',
            'areas_for_improvement' => 'Participate more in inter-departmental technical presentations.',
            'training_needs' => 'Advanced Cloud Architecture Certification (AWS/Azure).',
            'submitted_at' => '2025-12-05 10:00:00',
            'reviewed_at' => '2025-12-10 14:30:00',
            'completed_at' => '2025-12-15 16:00:00',
        ]);

        // Section 4 Goals for Appraisal 1
        $appraisal1->goals()->create([
            'key_result_area_id' => $kra2->id,
            'kra_weight' => 40,
            'objective' => 'Design and deploy automated Performance Management portal for all departments',
            'objective_weight' => 40,
            'kpi' => 'Portal Deployment & Adoption Rate',
            'target_set' => '100% Departmental Rollout',
            'unit_of_measurement' => '%',
            'achievement' => 'Deployed full PMS platform with 100% coverage across 10 departments.',
            'self_rating' => 'O',
            'supervisor_rating' => 'O',
            'raw_score' => 100,
            'weighted_raw_score' => 40.00,
            'sort_order' => 1,
        ]);

        $appraisal1->goals()->create([
            'key_result_area_id' => $kra1->id,
            'kra_weight' => 30,
            'objective' => 'Maintain SLA for portal issue resolution within 24 hours',
            'objective_weight' => 30,
            'kpi' => 'Average Issue Resolution Turnaround',
            'target_set' => '< 24 Hours',
            'unit_of_measurement' => 'Hours',
            'achievement' => 'Maintained average resolution time of 12 hours.',
            'self_rating' => 'E',
            'supervisor_rating' => 'E',
            'raw_score' => 90,
            'weighted_raw_score' => 27.00,
            'sort_order' => 2,
        ]);

        $appraisal1->goals()->create([
            'key_result_area_id' => $kra3->id,
            'kra_weight' => 30,
            'objective' => 'Conduct PMS user training and orientation sessions for staff',
            'objective_weight' => 30,
            'kpi' => 'Trained Departmental Officers',
            'target_set' => '150 Officers',
            'unit_of_measurement' => 'Officers',
            'achievement' => 'Organized 6 hands-on workshops training 165 staff.',
            'self_rating' => 'O',
            'supervisor_rating' => 'VG',
            'raw_score' => 80,
            'weighted_raw_score' => 24.00,
            'sort_order' => 3,
        ]);

        // Initialize Section 5 & 6 and set ratings
        $appraisalService->initializeDefaultCompetenciesAndOperations($appraisal1);

        foreach ($appraisal1->competencies as $comp) {
            $comp->update([
                'employee_rating' => $comp->max_score,
                'supervisor_rating' => $comp->max_score,
                'score' => $comp->max_score,
            ]);
        }

        foreach ($appraisal1->operations as $op) {
            $op->update([
                'employee_rating' => $op->max_score,
                'supervisor_rating' => $op->max_score,
                'score' => $op->max_score,
            ]);
        }

        $appraisalService->calculateAppraisalScores($appraisal1);
    }
}
