<?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\Shortlist;

class ShortlistController 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;

        $shortlists = Shortlist::where('employer_id', $employerId)
            ->with(['worker.category', 'worker.skills', 'worker.documents'])
            ->get();

        $shortlistedWorkers = $shortlists->map(function ($s) {
            $w = $s->worker;
            if (!$w)
                return null;

            $isPending = str_contains(strtolower($w->passport_status), 'pending');
            if ($w->status === 'hidden' || $isPending || $w->status === 'Hired') {
                return null;
            }

            // 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];

            // Emirates ID verification status (dynamic passport status)
            $emiratesIdStatus = $w->emirates_id_status;

            // 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
            $visaStatus = $w->visa_status;

            // 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
            ];
            $photo = $photos[$w->id % 4];

            $dbReviews = \App\Models\Review::where('worker_id', $w->id)->get();
            $reviewsCount = $dbReviews->count();
            $rating = $reviewsCount > 0 ? round($dbReviews->avg('rating'), 1) : 0.0;

            return [
                'id' => $w->id,
                'name' => $w->name,
                'nationality' => $w->nationality,
                'photo' => $photo,
                'emirates_id_status' => $emiratesIdStatus,
                'passport_status' => $w->passport_status,
                'category' => $w->category ? $w->category->name : 'Domestic Worker',
                'skills' => $mappedSkills,
                '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,
            ];
        })->filter()->values()->toArray();

        return Inertia::render('Employer/Shortlist', [
            'shortlistedWorkers' => $shortlistedWorkers,
        ]);
    }

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

        $request->validate([
            'worker_id' => 'required|exists:workers,id',
        ]);

        $workerId = $request->worker_id;

        $existing = Shortlist::where('employer_id', $employerId)
            ->where('worker_id', $workerId)
            ->first();

        if ($existing) {
            $existing->delete();
            $status = 'removed';
        } else {
            Shortlist::create([
                'employer_id' => $employerId,
                'worker_id' => $workerId,
            ]);
            $status = 'added';
        }

        if ($request->wantsJson()) {
            return response()->json([
                'status' => 'success',
                'action' => $status,
                'shortlistedIds' => Shortlist::where('employer_id', $employerId)->pluck('worker_id')->toArray()
            ]);
        }

        return back();
    }

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

        Shortlist::where('employer_id', $employerId)
            ->where('worker_id', $id)
            ->delete();

        return back()->with('success', 'Worker removed from shortlist.');
    }
}
