<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use App\Models\Department;
use App\Models\Employee;
use App\Models\LeaveType;
use App\Models\EvaluationCriteria;
use App\Models\EvaluationPeriod;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        // ── 1. Departments ────────────────────────────────────────────────────
        $depts = [
            ['name' => 'Human Resources',         'code' => 'HR',  'type' => 'division'],
            ['name' => 'Finance & Accounts',       'code' => 'FIN', 'type' => 'division'],
            ['name' => 'Information Technology',   'code' => 'IT',  'type' => 'department'],
            ['name' => 'Operations',               'code' => 'OPS', 'type' => 'division'],
            ['name' => 'Sales & Marketing',        'code' => 'SAL', 'type' => 'department'],
            ['name' => 'Customer Service',         'code' => 'CS',  'type' => 'unit'],
            ['name' => 'Legal & Compliance',       'code' => 'LEG', 'type' => 'unit'],
            ['name' => 'Research & Development',   'code' => 'RND', 'type' => 'department'],
            ['name' => 'Administration',           'code' => 'ADM', 'type' => 'division'],
            ['name' => 'Logistics',                'code' => 'LOG', 'type' => 'unit'],
        ];

        $deptMap = [];
        foreach ($depts as $d) {
            $deptMap[$d['code']] = Department::create(array_merge($d, ['is_active' => true]));
        }

        // ── 2. Users (no department_id — derived via employee record) ─────────
        // [name, email, role, dept_code, emp_number]
        $userDefs = [
            ['Alex Morgan',     'president@hrms.demo',  'president',   'ADM', 'EMP-0001'],
            ['Sarah Collins',   'hr.admin@hrms.demo',   'hr_admin',    'HR',  'EMP-0002'],
            ['Admin User',      'admin@hrms.demo',       'super_admin', 'IT',  'EMP-0003'],
            ['David Fletcher',  'dept.head@hrms.demo',  'dept_head',   'OPS', 'EMP-0004'],
            ['Maria Santos',    'dept.head2@hrms.demo', 'dept_head',   'FIN', 'EMP-0005'],
            ['James Pearce',    'j.pearce@hrms.demo',   'employee',    'IT',  'EMP-0006'],
            ['Lisa Turner',     'l.turner@hrms.demo',   'employee',    'FIN', 'EMP-0007'],
            ['Robert Hayes',    'r.hayes@hrms.demo',    'employee',    'SAL', 'EMP-0008'],
            ['Emily Clarke',    'e.clarke@hrms.demo',   'employee',    'CS',  'EMP-0009'],
            ['Michael Grant',   'm.grant@hrms.demo',    'employee',    'LOG', 'EMP-0010'],
        ];

        $employeeDetails = [
            //  first       last       position                  salary  gender    dob           doe           marital
            ['Alex',    'Morgan',    'Chief Executive Officer',  8000, 'Male',   '1968-05-12', '2002-01-01', 'Married'],
            ['Sarah',   'Collins',   'HR Manager',               3500, 'Female', '1978-09-23', '2010-06-15', 'Single'],
            ['Admin',   'User',      'System Administrator',     3000, 'Male',   '1980-01-15', '2015-08-20', 'Married'],
            ['David',   'Fletcher',  'Head of Operations',       4200, 'Male',   '1970-07-30', '2005-03-01', 'Married'],
            ['Maria',   'Santos',    'Finance Director',         4500, 'Female', '1975-11-11', '2007-11-30', 'Single'],
            ['James',   'Pearce',    'IT Officer',               2200, 'Male',   '1990-03-22', '2018-04-10', 'Married'],
            ['Lisa',    'Turner',    'Accounts Officer',         2000, 'Female', '1988-06-14', '2016-09-05', 'Single'],
            ['Robert',  'Hayes',     'Sales Executive',          2400, 'Male',   '1985-12-01', '2012-02-01', 'Married'],
            ['Emily',   'Clarke',    'Customer Service Rep.',    1800, 'Female', '1992-04-18', '2019-07-01', 'Single'],
            ['Michael', 'Grant',     'Logistics Coordinator',   1900, 'Male',   '1983-08-07', '2014-01-15', 'Married'],
        ];

        $deptCodeForUser = ['ADM','HR','IT','OPS','FIN','IT','FIN','SAL','CS','LOG'];

        $createdUsers = [];
        foreach ($userDefs as $i => [$name, $email, $role, $deptCode, $empNum]) {
            $user = User::create([
                'name'            => $name,
                'email'           => $email,
                'password'        => Hash::make('password'),
                'role'            => $role,
                'employee_number' => $empNum,
                'is_active'       => true,
            ]);
            $createdUsers[] = $user;
        }

        // ── 3. Employees ──────────────────────────────────────────────────────
        foreach ($createdUsers as $i => $user) {
            [$first, $last, $position, $salary, $gender, $dob, $doe, $marital] = $employeeDetails[$i];
            $dept = $deptMap[$deptCodeForUser[$i]];

            Employee::create([
                'user_id'            => $user->id,
                'first_name'         => $first,
                'last_name'          => $last,
                'position'           => $position,
                'employee_number'    => $userDefs[$i][4],
                'department_id'      => $dept->id,
                'date_of_birth'      => $dob,
                'date_of_employment' => $doe,
                'citizenship'        => null,
                'gender'             => $gender,
                'marital_status'     => $marital,
                'employment_type'    => 'full_time',
                'status'             => 'active',
                'salary_usd'         => $salary,
                'present_address'    => null,
            ]);
        }

        // ── 4. Set department heads ───────────────────────────────────────────
        $deptMap['HR']->update(['head_user_id'  => $createdUsers[1]->id]); // Sarah → HR
        $deptMap['OPS']->update(['head_user_id' => $createdUsers[3]->id]); // David → Ops
        $deptMap['FIN']->update(['head_user_id' => $createdUsers[4]->id]); // Maria → Finance

        // ── 5. Leave Types ────────────────────────────────────────────────────
        $leaveTypes = [
            ['name' => 'Annual Leave',        'code' => 'ANN', 'days_allowed_per_year' => 21, 'color' => '#0055b3', 'is_paid' => true],
            ['name' => 'Sick Leave',           'code' => 'SIC', 'days_allowed_per_year' => 15, 'color' => '#dc2626', 'is_paid' => true],
            ['name' => 'Maternity Leave',      'code' => 'MAT', 'days_allowed_per_year' => 90, 'color' => '#e91e8c', 'is_paid' => true],
            ['name' => 'Paternity Leave',      'code' => 'PAT', 'days_allowed_per_year' => 10, 'color' => '#7c3aed', 'is_paid' => true],
            ['name' => 'Bereavement Leave',    'code' => 'BER', 'days_allowed_per_year' =>  5, 'color' => '#6c757d', 'is_paid' => true],
            ['name' => 'Study Leave',          'code' => 'STU', 'days_allowed_per_year' => 30, 'color' => '#059669', 'is_paid' => false],
            ['name' => 'Unpaid Leave',         'code' => 'UNP', 'days_allowed_per_year' => 30, 'color' => '#94a3b8', 'is_paid' => false],
            ['name' => 'Emergency Leave',      'code' => 'EMG', 'days_allowed_per_year' =>  3, 'color' => '#f59e0b', 'is_paid' => true],
        ];
        foreach ($leaveTypes as $lt) {
            LeaveType::create(array_merge($lt, ['is_active' => true, 'requires_approval' => true]));
        }

        // ── 6. Evaluation Criteria ────────────────────────────────────────────
        $criteria = [
            ['name' => 'Job Knowledge',             'category' => 'Core Competencies',    'max_score' => 20, 'weight' => 1.2],
            ['name' => 'Quality of Work',           'category' => 'Core Competencies',    'max_score' => 20, 'weight' => 1.2],
            ['name' => 'Productivity & Output',     'category' => 'Core Competencies',    'max_score' => 20, 'weight' => 1.0],
            ['name' => 'Attendance & Punctuality',  'category' => 'Professional Conduct', 'max_score' => 10, 'weight' => 0.8],
            ['name' => 'Teamwork & Collaboration',  'category' => 'Professional Conduct', 'max_score' => 15, 'weight' => 1.0],
            ['name' => 'Initiative & Innovation',   'category' => 'Leadership',           'max_score' => 15, 'weight' => 1.0],
            ['name' => 'Communication Skills',      'category' => 'Professional Conduct', 'max_score' => 10, 'weight' => 0.8],
            ['name' => 'Adherence to Policies',     'category' => 'Professional Conduct', 'max_score' => 10, 'weight' => 0.8],
            ['name' => 'Leadership',                'category' => 'Leadership',           'max_score' => 15, 'weight' => 1.0],
            ['name' => 'Customer / Client Focus',   'category' => 'Service',              'max_score' => 15, 'weight' => 1.0],
        ];
        foreach ($criteria as $c) {
            EvaluationCriteria::create(array_merge($c, ['is_active' => true, 'description' => '']));
        }

        // ── 7. Evaluation Period ──────────────────────────────────────────────
        EvaluationPeriod::create([
            'name'       => 'Annual Appraisal ' . date('Y'),
            'start_date' => date('Y') . '-01-01',
            'end_date'   => date('Y') . '-12-31',
            'type'       => 'annual',
            'status'     => 'active',
        ]);

        $this->command->info('');
        $this->command->info('✅  HRMS demo data seeded successfully.');
        $this->command->info('');
        $this->command->table(
            ['Role', 'Email', 'Password'],
            [
                ['CEO / President', 'president@hrms.demo', 'password'],
                ['HR Manager',      'hr.admin@hrms.demo',  'password'],
                ['Super Admin',     'admin@hrms.demo',     'password'],
                ['Dept Head',       'dept.head@hrms.demo', 'password'],
                ['Employee',        'j.pearce@hrms.demo',  'password'],
            ]
        );
        $this->command->info('');
        $this->command->info('💡  Tip: set HRMS_COMPANY in your .env to your company name.');
    }
}
