<?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'])
            ->get();

        $shortlistedWorkers = $shortlists->map(function ($s) {
            $w = $s->worker;
            if (!$w) return null;
            return [
                'id' => $w->id,
                'name' => $w->name,
                'nationality' => $w->nationality,
                'category' => $w->category ? $w->category->name : 'General Helper',
                'skills' => $w->skills->pluck('name')->toArray(),
                'availability' => $w->availability,
                'experience' => $w->experience,
                'salary' => (int)$w->salary,
                'verified' => (bool)$w->verified,
            ];
        })->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.');
    }
}
