<?php

namespace Database\Seeders;

use App\Models\Announcement;
use App\Models\AttendanceRecord;
use App\Models\Department;
use App\Models\Designation;
use App\Models\EmployeeDocument;
use App\Models\HrTicket;
use App\Models\JobPosting;
use App\Models\LeaveRequest;
use App\Models\LeaveType;
use App\Models\Payroll;
use App\Models\PerformanceReview;
use App\Models\Training;
use App\Models\TrainingEnrollment;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        $operations = Department::updateOrCreate(['code' => 'OPS'], ['name' => 'Operations', 'description' => 'Canadian field operations and service delivery', 'status' => 'active']);
        $hr = Department::updateOrCreate(['code' => 'HR'], ['name' => 'Human Resources', 'description' => 'People operations, payroll onboarding and employment standards support', 'status' => 'active']);
        $finance = Department::updateOrCreate(['code' => 'FIN'], ['name' => 'Finance', 'description' => 'Payroll, accounting, CRA remittance tracking and reporting', 'status' => 'active']);

        $manager = Designation::updateOrCreate(['name' => 'Manager'], ['level' => 'M1', 'description' => 'Department manager', 'status' => 'active']);
        $officer = Designation::updateOrCreate(['name' => 'Officer'], ['level' => 'O1', 'description' => 'Operational staff', 'status' => 'active']);
        $coordinator = Designation::updateOrCreate(['name' => 'Coordinator'], ['level' => 'C1', 'description' => 'Team coordination role', 'status' => 'active']);

        $admin = User::updateOrCreate(
            ['email' => 'hradmin@movex-ca.test'],
            [
                'staff_id' => 'CA-HR-ADMIN-001',
                'name' => 'Movex Canada HR Admin',
                'password' => Hash::make('password123'),
                'role' => 'admin',
                'phone' => '+12045550101',
                'department_id' => $hr->id,
                'designation_id' => $manager->id,
                'job_title' => 'HR Manager',
                'employment_date' => now()->subYears(2)->toDateString(),
                'employment_status' => 'active',
                'basic_salary' => 8500,
                'payroll_frequency' => 'monthly',
                'province' => 'MB',
                'postal_code' => 'R3C 4T3',
                'tax_province' => 'MB',
                'sin_last4' => '1001',
                'work_authorization_status' => 'Canadian citizen',
                'address' => '360 Main Street, Winnipeg, MB',
                'emergency_contact' => 'Emergency Desk +1 204 555 0199',
                'bank_name' => 'Royal Bank of Canada',
                'bank_institution_number' => '003',
                'bank_transit_number' => '00001',
                'bank_account' => '0001112223',
            ]
        );

        $users = collect([
            User::updateOrCreate(['email' => 'emma@movex-ca.test'], [
                'staff_id' => 'CA-HR-USER-001', 'name' => 'Emma Thompson', 'password' => Hash::make('password123'), 'role' => 'user', 'phone' => '+12045550102', 'department_id' => $operations->id, 'designation_id' => $coordinator->id, 'job_title' => 'Regional Coordinator', 'employment_date' => now()->subMonths(10)->toDateString(), 'employment_status' => 'active', 'basic_salary' => 5200, 'payroll_frequency' => 'biweekly', 'province' => 'MB', 'postal_code' => 'R3B 1B9', 'tax_province' => 'MB', 'sin_last4' => '2002', 'work_authorization_status' => 'Canadian citizen', 'address' => 'Portage Avenue, Winnipeg, MB', 'emergency_contact' => 'Liam Thompson +1 204 555 0202', 'bank_name' => 'TD Canada Trust', 'bank_institution_number' => '004', 'bank_transit_number' => '10202', 'bank_account' => '0002223334',
            ]),
            User::updateOrCreate(['email' => 'sarah@movex-ca.test'], [
                'staff_id' => 'CA-HR-USER-002', 'name' => 'Sarah Chen', 'password' => Hash::make('password123'), 'role' => 'user', 'phone' => '+14165550103', 'department_id' => $finance->id, 'designation_id' => $officer->id, 'job_title' => 'Payroll Officer', 'employment_date' => now()->subMonths(7)->toDateString(), 'employment_status' => 'active', 'basic_salary' => 4700, 'payroll_frequency' => 'biweekly', 'province' => 'ON', 'postal_code' => 'M5H 2N2', 'tax_province' => 'ON', 'sin_last4' => '3003', 'work_authorization_status' => 'Permanent resident', 'address' => 'King Street West, Toronto, ON', 'emergency_contact' => 'David Chen +1 416 555 0303', 'bank_name' => 'Scotiabank', 'bank_institution_number' => '002', 'bank_transit_number' => '10303', 'bank_account' => '0003334445',
            ]),
            User::updateOrCreate(['email' => 'daniel@movex-ca.test'], [
                'staff_id' => 'CA-HR-USER-003', 'name' => 'Daniel Fraser', 'password' => Hash::make('password123'), 'role' => 'user', 'phone' => '+14035550104', 'department_id' => $operations->id, 'designation_id' => $officer->id, 'job_title' => 'City Coordinator', 'employment_date' => now()->subMonths(5)->toDateString(), 'employment_status' => 'probation', 'basic_salary' => 4300, 'payroll_frequency' => 'biweekly', 'province' => 'AB', 'postal_code' => 'T2P 1J9', 'tax_province' => 'AB', 'sin_last4' => '4004', 'work_authorization_status' => 'Work permit', 'address' => '7 Avenue SW, Calgary, AB', 'emergency_contact' => 'Maya Fraser +1 403 555 0404', 'bank_name' => 'CIBC', 'bank_institution_number' => '010', 'bank_transit_number' => '10404', 'bank_account' => '0004445556',
            ]),
        ]);

        foreach (['Vacation Leave' => 10, 'Sick / Personal Leave' => 5, 'Maternity / Parental Leave' => 0, 'Bereavement Leave' => 3, 'Statutory Holiday' => 0] as $name => $days) {
            LeaveType::updateOrCreate(['name' => $name], ['annual_days' => $days, 'requires_document' => in_array($name, ['Sick / Personal Leave', 'Maternity / Parental Leave']), 'status' => 'active']);
        }

        $vacation = LeaveType::where('name', 'Vacation Leave')->first();
        LeaveRequest::updateOrCreate(
            ['user_id' => $users[0]->id, 'leave_type_id' => $vacation->id, 'start_date' => now()->addDays(8)->toDateString()],
            ['end_date' => now()->addDays(12)->toDateString(), 'total_days' => 5, 'reason' => 'Family commitment', 'status' => 'pending']
        );

        foreach ($users as $user) {
            AttendanceRecord::updateOrCreate(
                ['user_id' => $user->id, 'work_date' => today()->toDateString()],
                ['clock_in_at' => now()->setTime(8, 30), 'clock_out_at' => null, 'status' => 'present', 'approved_by' => $admin->id]
            );
            Payroll::updateOrCreate(
                ['user_id' => $user->id, 'pay_period_start' => now()->startOfMonth()->toDateString(), 'pay_period_end' => now()->endOfMonth()->toDateString()],
                ['basic_salary' => $user->basic_salary, 'allowances' => 300, 'deductions' => 250, 'tax' => 900, 'net_pay' => $user->basic_salary + 300 - 1150, 'status' => 'approved', 'notes' => 'Demo Canadian payroll: tax field represents combined income tax, CPP/EI and other statutory deductions.']
            );
            EmployeeDocument::updateOrCreate(
                ['user_id' => $user->id, 'title' => 'Employment Agreement'],
                ['document_type' => 'Employment Agreement', 'status' => 'valid', 'notes' => 'Seeded Canadian employment record']
            );
        }

        PerformanceReview::updateOrCreate(
            ['user_id' => $users[0]->id, 'review_period' => 'Q1 2026'],
            ['score' => 4, 'summary' => 'Strong coordination and timely reporting across Canadian operations.', 'strengths' => 'Communication and ownership', 'improvement_plan' => 'Improve documentation discipline', 'status' => 'completed', 'reviewed_by' => $admin->id, 'reviewed_at' => now()]
        );

        Announcement::updateOrCreate(
            ['title' => 'Welcome to Movex Canada HR CRM'],
            ['body' => 'All staff should update their profile, province, postal code, bank deposit details, TD1/SIN onboarding details and emergency contact information before payroll cut-off.', 'audience' => 'all', 'status' => 'published', 'published_at' => now(), 'created_by' => $admin->id]
        );

        HrTicket::updateOrCreate(
            ['user_id' => $users[1]->id, 'subject' => 'Payslip clarification'],
            ['category' => 'payroll', 'priority' => 'normal', 'status' => 'open', 'message' => 'Please confirm my tax, CPP/EI and allowance breakdown for this month.']
        );

        $training = Training::updateOrCreate(
            ['title' => 'Canadian Workplace Safety and HR Policy Orientation'],
            ['description' => 'Internal onboarding for staff conduct, reporting lines, workplace safety and employment standards awareness.', 'start_date' => now()->addDays(14)->toDateString(), 'end_date' => now()->addDays(14)->toDateString(), 'location' => 'Winnipeg Office', 'status' => 'active', 'created_by' => $admin->id]
        );
        TrainingEnrollment::updateOrCreate(['training_id' => $training->id, 'user_id' => $users[0]->id], ['status' => 'registered']);

        JobPosting::updateOrCreate(
            ['title' => 'HR Officer', 'location' => 'Winnipeg, Manitoba'],
            ['department_id' => $hr->id, 'employment_type' => 'full_time', 'description' => 'Support recruitment, staff records, payroll onboarding, HR operations and employee documentation.', 'requirements' => 'Canadian diploma/degree or equivalent HR experience. CPHR exposure is an asset.', 'status' => 'open', 'closing_date' => now()->addMonth()->toDateString(), 'created_by' => $admin->id]
        );
    }
}
