<?php

namespace App\Http\Controllers\Employer;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Inertia\Inertia;
use App\Models\User;
use App\Models\Worker;
use App\Models\WorkerCategory;
use App\Models\Shortlist;
use App\Models\JobOffer;

class WorkerController extends Controller
{
    private function resolveCurrentUser()
    {
        $sess = session('user');
        $sessId = is_array($sess) ? ($sess['id'] ?? null) : ($sess->id ?? null);
        
        if (!$sessId) {
            $user = User::where('role', 'employer')->first();
            if ($user) {
                session(['user' => (object)[
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'role' => 'employer',
                    'subscription_status' => $user->subscription_status ?? 'active',
                ]]);
                return $user;
            }
        } else {
            return User::find($sessId);
        }
        
        return null;
    }

    public function index(Request $request)
    {
        $user = $this->resolveCurrentUser();
        $employerId = $user ? $user->id : 2;

        $dbWorkers = Worker::with(['category', 'skills'])->get();

        $workers = $dbWorkers->map(function ($w) {
            // Map languages with country names
            $langs = ($w->id % 2 === 0) ? ['English', 'Arabic'] : ( ($w->id % 3 === 0) ? ['English', 'Tagalog'] : ['English', 'Hindi', 'Arabic'] );
            
            // Preferred job types: full-time / part-time / live-in / live-out
            $jobTypes = ['full-time', 'part-time', 'live-in', 'live-out'];
            $preferredJobType = $jobTypes[$w->id % 4];

            // Availability status: Active / Hidden / Hired
            $availStatuses = ['Active', 'Hidden', 'Hired'];
            $availabilityStatus = $availStatuses[$w->id % 3];

            // Emirates ID verification status
            $emiratesIdStatus = $w->verified ? 'Emirates ID Verified' : 'EID Vetting Pending';

            // Exact Skills mapping: cooking, driving, childcare, cleaning, elderly care, gardening
            $skillsList = ['cooking', 'driving', 'childcare', 'cleaning', 'elderly care', 'gardening'];
            $mappedSkills = [
                $skillsList[$w->id % 6],
                $skillsList[($w->id + 2) % 6]
            ];

            // Visa status
            $visaStatusesList = ['Residence Visa', 'Tourist Visa', 'Employment Visa', 'Cancelled Visa', 'Own Visa'];
            $visaStatus = $visaStatusesList[$w->id % 5];

            // Optional profile photos
            $photos = [
                'https://images.unsplash.com/photo-1573496359142-b8d87734a5a2?auto=format&fit=crop&q=80&w=200',
                'https://images.unsplash.com/photo-1534528741775-53994a69daeb?auto=format&fit=crop&q=80&w=200',
                'https://images.unsplash.com/photo-1544005313-94ddf0286df2?auto=format&fit=crop&q=80&w=200',
                null // Test optional photo placeholder
            ];
            $photo = $photos[$w->id % 4];

            $rating = 4.0 + (($w->id * 3) % 10) / 10.0;
            $reviewsCount = ($w->id * 4) % 20 + 2;

            return [
                'id' => $w->id,
                'name' => $w->name,
                'nationality' => $w->nationality,
                'photo' => $photo,
                'emirates_id_status' => $emiratesIdStatus,
                'category' => $w->category ? $w->category->name : 'Domestic Worker',
                'skills' => $mappedSkills,
                'availability_status' => $availabilityStatus,
                'visa_status' => $visaStatus,
                'experience' => $w->experience,
                'salary' => (int)$w->salary,
                'religion' => $w->religion,
                'languages' => $langs, 
                'age' => $w->age,
                'verified' => (bool)$w->verified,
                'preferred_job_type' => $preferredJobType,
                'bio' => $w->bio,
                'rating' => $rating,
                'reviews_count' => $reviewsCount,
            ];
        })->toArray();

        $shortlistedIds = Shortlist::where('employer_id', $employerId)->pluck('worker_id')->toArray();

        $dbCategories = WorkerCategory::pluck('name')->toArray();
        $dbNationalities = Worker::distinct()->pluck('nationality')->toArray();

        $filtersMetadata = [
            'categories' => array_merge(['All Categories'], $dbCategories),
            'nationalities' => array_merge(['All Nationalities'], $dbNationalities),
            'availabilities' => ['All Availabilities', 'Active', 'Hidden', 'Hired'],
            'experienceLevels' => ['All Experience', '1-2 Years', '3-5 Years', '5+ Years'],
            'religions' => ['All Religions', 'Christian', 'Muslim', 'Hindu', 'Buddhist'],
            'languages' => ['All Languages', 'English', 'Arabic', 'Hindi', 'Tagalog'],
            'workTypes' => ['All Types', 'full-time', 'part-time', 'live-in', 'live-out'],
            'skills' => ['All Skills', 'cooking', 'driving', 'childcare', 'cleaning', 'elderly care', 'gardening'],
            'visaStatuses' => ['All Visa Statuses', 'Residence Visa', 'Tourist Visa', 'Employment Visa', 'Cancelled Visa', 'Own Visa'],
        ];

        return Inertia::render('Employer/Workers/Index', [
            'initialWorkers' => $workers,
            'initialShortlistedIds' => $shortlistedIds,
            'filtersMetadata' => $filtersMetadata,
        ]);
    }

    public function show($id)
    {
        $w = Worker::with(['category', 'skills', 'documents'])->findOrFail($id);
        
        $langs = ($w->id % 2 === 0) ? ['English', 'Arabic'] : ( ($w->id % 3 === 0) ? ['English', 'Tagalog'] : ['English', 'Hindi', 'Arabic'] );
        
        $jobTypes = ['full-time', 'part-time', 'live-in', 'live-out'];
        $preferredJobType = $jobTypes[$w->id % 4];

        $availStatuses = ['Active', 'Hidden', 'Hired'];
        $availabilityStatus = $availStatuses[$w->id % 3];

        $emiratesIdStatus = $w->verified ? 'Emirates ID Verified' : 'EID Vetting Pending';

        $skillsList = ['cooking', 'driving', 'childcare', 'cleaning', 'elderly care', 'gardening'];
        $mappedSkills = [
            $skillsList[$w->id % 6],
            $skillsList[($w->id + 2) % 6]
        ];

        $photos = [
            'https://images.unsplash.com/photo-1573496359142-b8d87734a5a2?auto=format&fit=crop&q=80&w=200',
            'https://images.unsplash.com/photo-1534528741775-53994a69daeb?auto=format&fit=crop&q=80&w=200',
            'https://images.unsplash.com/photo-1544005313-94ddf0286df2?auto=format&fit=crop&q=80&w=200',
            null
        ];
        $photo = $photos[$w->id % 4];

        $rating = 4.0 + (($w->id * 3) % 10) / 10.0;
        $reviewsCount = ($w->id * 4) % 20 + 2;

        $reviews = [
            [
                'id' => 1,
                'employer_name' => 'Fatima Al Mansoori',
                'rating' => 5,
                'date' => 'May 10, 2026',
                'comment' => 'Extremely reliable and respectful. Professional work and great communication.',
            ],
            [
                'id' => 2,
                'employer_name' => 'Michael Harrison',
                'rating' => 4,
                'date' => 'Mar 24, 2026',
                'comment' => 'Very punctual, did exactly what was expected. Highly recommend.',
            ]
        ];

        $simDb = Worker::with('category')
            ->where('id', '!=', $w->id)
            ->limit(3)
            ->get();
        $similarWorkers = $simDb->map(function($sw) {
            $availStatuses = ['Active', 'Hidden', 'Hired'];
            $availabilityStatus = $availStatuses[$sw->id % 3];

            return [
                'id' => $sw->id,
                'name' => $sw->name,
                'nationality' => $sw->nationality,
                'category' => $sw->category ? $sw->category->name : 'Helper',
                'salary' => (int)$sw->salary,
                'rating' => 4.7,
                'verified' => (bool)$sw->verified,
                'availability_status' => $availabilityStatus,
            ];
        })->toArray();

        $visaStatusesList = ['Residence Visa', 'Tourist Visa', 'Employment Visa', 'Cancelled Visa', 'Own Visa'];
        $visaStatus = $visaStatusesList[$w->id % 5];

        $worker = [
            'id' => $w->id,
            'name' => $w->name,
            'nationality' => $w->nationality,
            'photo' => $photo,
            'emirates_id_status' => $emiratesIdStatus,
            'category' => $w->category ? $w->category->name : 'Domestic Worker',
            'skills' => $mappedSkills,
            'availability_status' => $availabilityStatus,
            'visa_status' => $visaStatus,
            'experience' => $w->experience,
            'experience_years' => 5, 
            'salary' => (int)$w->salary,
            'religion' => $w->religion,
            'languages' => $langs,
            'age' => $w->age,
            'verified' => (bool)$w->verified,
            'preferred_job_type' => $preferredJobType,
            'bio' => $w->bio,
            'rating' => $rating,
            'reviews_count' => $reviewsCount,
            'reviews' => $reviews,
            'similar_workers' => $similarWorkers,
        ];

        return Inertia::render('Employer/Workers/Show', [
            'worker' => $worker,
        ]);
    }

    public function sendOffer(Request $request, $id)
    {
        $request->validate([
            'work_date' => 'required|date',
            'location' => 'required|string|max:255',
            'salary' => 'required|numeric|min:0',
            'notes' => 'nullable|string|max:1000',
        ]);

        $user = $this->resolveCurrentUser();
        $employerId = $user ? $user->id : 2;

        $worker = Worker::findOrFail($id);

        JobOffer::create([
            'employer_id' => $employerId,
            'worker_id' => $worker->id,
            'work_date' => $request->work_date,
            'location' => $request->location,
            'salary' => $request->salary,
            'notes' => $request->notes,
            'status' => 'pending',
        ]);

        return redirect()->route('employer.hiring.success', ['id' => $id])
            ->with('success', 'Hiring offer has been successfully dispatched to the worker!');
    }
}
