<?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\JobPost;
use App\Models\JobApplication;
use App\Models\WorkerCategory;

class JobController 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();
        if (!$user) {
            return redirect()->route('employer.login');
        }

        $dbJobs = JobPost::where('employer_id', $user->id)
            ->with(['category', 'applications'])
            ->latest()
            ->get();

        $jobs = $dbJobs->map(function ($job) {
            return [
                'id' => $job->id,
                'title' => $job->title,
                'category' => $job->category->name ?? 'General',
                'location' => $job->location,
                'salary' => (int) $job->salary,
                'workers_needed' => $job->workers_needed,
                'applied_count' => $job->applications->count(),
                'posted_at' => $job->created_at->format('M d, Y'),
                'status' => ucfirst($job->status), // Active, Closed, Draft
            ];
        })->toArray();

        return Inertia::render('Employer/Jobs/Index', [
            'initialJobs' => $jobs,
        ]);
    }

    public function create()
    {
        $categories = WorkerCategory::pluck('name')->toArray();
        if (empty($categories)) {
            $categories = ['Electrician', 'Mason', 'Plumber', 'Cleaner', 'Site Supervisor', 'Driver', 'General Helper'];
        }

        return Inertia::render('Employer/Jobs/Create', [
            'categories' => $categories,
        ]);
    }

    public function store(Request $request)
    {
        $user = $this->resolveCurrentUser();
        if (!$user) {
            return back()->withErrors(['general' => 'User session not found.']);
        }

        $request->validate([
            'title' => 'required|string|max:255',
            'category' => 'required|string',
            'workers_needed' => 'required|integer|min:1',
            'location' => 'required|string|max:255',
            'salary' => 'required|numeric|min:0',
            'job_type' => 'required|string|in:Full Time,Part Time,Contract',
            'start_date' => 'required|date',
            'description' => 'required|string|max:1000',
            'requirements' => 'nullable|string',
        ]);

        $category = WorkerCategory::where('name', $request->category)->first();
        if (!$category) {
            $category = WorkerCategory::create(['name' => $request->category]);
        }

        JobPost::create([
            'employer_id' => $user->id,
            'title' => $request->title,
            'category_id' => $category->id,
            'workers_needed' => $request->workers_needed,
            'job_type' => $request->job_type,
            'location' => $request->location,
            'salary' => $request->salary,
            'start_date' => $request->start_date,
            'description' => $request->description,
            'requirements' => $request->requirements,
            'status' => 'active',
        ]);

        return redirect()->route('employer.jobs')->with('success', 'Job posted successfully.');
    }

    public function applicants($id)
    {
        $user = $this->resolveCurrentUser();
        if (!$user) {
            return redirect()->route('employer.login');
        }

        $job = JobPost::where('employer_id', $user->id)->where('id', $id)->firstOrFail();

        $dbApplications = JobApplication::where('job_id', $id)
            ->with(['worker.category', 'worker.skills'])
            ->get();

        $applicants = $dbApplications->map(function ($app) {
            $worker = $app->worker;
            return [
                'id' => $worker->id,
                'name' => $worker->name,
                'nationality' => $worker->nationality,
                'category' => $worker->category->name ?? 'General',
                'salary' => (int) $worker->expected_salary,
                'experience' => ($worker->experience_years ?? 3) . ' Years',
                'status' => ucfirst($app->status), // Applied, Shortlisted, Hired, Rejected
                'match_score' => $worker->match_score ?? 90,
            ];
        })->toArray();

        return Inertia::render('Employer/Jobs/Applicants', [
            'job' => [
                'id' => $job->id,
                'title' => $job->title,
                'category' => $job->category->name ?? 'General',
                'salary' => (int) $job->salary,
            ],
            'applicants' => $applicants,
        ]);
    }
}
