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

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

        // 1. Get job posts created by this employer
        $jobIds = JobPost::where('employer_id', $employerId)->pluck('id');

        // Fetch applications for those jobs
        $applications = JobApplication::whereIn('job_id', $jobIds)
            ->with(['worker.category', 'jobPost'])
            ->get();

        $selectedWorkers = $applications->map(function ($app) {
            $w = $app->worker;
            if (!$w) return null;

            // Map DB status to UI friendly status
            $status = 'Reviewing';
            if ($app->status === 'hired') $status = 'Hired';
            elseif ($app->status === 'rejected') $status = 'Rejected';
            elseif ($app->status === 'shortlisted' || $app->status === 'offer_sent') $status = 'Offer Sent';
            elseif ($app->status === 'applied') $status = 'Reviewing';
            else $status = ucfirst($app->status);

            return [
                'id' => $app->id, // standard application id
                'worker_id' => $w->id,
                'name' => $w->name,
                'nationality' => $w->nationality,
                'category' => $w->category ? $w->category->name : 'General Helper',
                'salary' => (int)$w->salary,
                'status' => $status,
                'applied_at' => $app->created_at->format('M d, Y'),
            ];
        })->filter()->values()->toArray();

        // 2. Fetch direct hiring offers sent by this employer
        $directOffers = JobOffer::where('employer_id', $employerId)
            ->with('worker.category')
            ->get();

        $directWorkers = $directOffers->map(function ($offer) {
            $w = $offer->worker;
            if (!$w) return null;

            // Map DB offer status to UI friendly status
            $status = 'Offer Sent';
            if ($offer->status === 'accepted') $status = 'Hired';
            elseif ($offer->status === 'rejected') $status = 'Rejected';
            elseif ($offer->status === 'pending') $status = 'Offer Sent';

            return [
                'id' => 'offer_' . $offer->id, // Unique string key prefix to prevent clashes
                'worker_id' => $w->id,
                'name' => $w->name,
                'nationality' => $w->nationality,
                'category' => $w->category ? $w->category->name : 'General Helper',
                'salary' => (int)$offer->salary,
                'status' => $status,
                'applied_at' => $offer->created_at->format('M d, Y'),
            ];
        })->filter()->values()->toArray();

        // Merge standard job applications with direct hiring offers for unified tracking
        $mergedCandidates = array_merge($selectedWorkers, $directWorkers);

        return Inertia::render('Employer/SelectedCandidates', [
            'selectedWorkers' => $mergedCandidates,
        ]);
    }

    public function updateStatus(Request $request, $id)
    {
        $request->validate([
            'status' => 'required|string|in:Reviewing,Offer Sent,Hired,Rejected',
        ]);

        // If this is a direct hiring offer response
        if (is_string($id) && str_starts_with($id, 'offer_')) {
            $offerId = substr($id, 6);
            $offer = JobOffer::findOrFail($offerId);
            
            $dbStatus = 'pending';
            if ($request->status === 'Hired') {
                $dbStatus = 'accepted';
                $offer->worker->update(['status' => 'Hired']);
            } elseif ($request->status === 'Rejected') {
                $dbStatus = 'rejected';
                $offer->worker->update(['status' => 'active']);
            } elseif ($request->status === 'Offer Sent') {
                $dbStatus = 'pending';
            }

            $offer->update(['status' => $dbStatus]);

            return back()->with('success', 'Direct candidate hiring offer status updated successfully to ' . $request->status);
        }

        // Standard job application status update
        $app = JobApplication::findOrFail($id);

        $dbStatus = 'applied';
        if ($request->status === 'Hired') {
            $dbStatus = 'hired';
            if ($app->worker) {
                $app->worker->update(['status' => 'Hired']);
            }
        } elseif ($request->status === 'Rejected') {
            $dbStatus = 'rejected';
            if ($app->worker) {
                $app->worker->update(['status' => 'active']);
            }
        } elseif ($request->status === 'Offer Sent') {
            $dbStatus = 'shortlisted';
        } elseif ($request->status === 'Reviewing') {
            $dbStatus = 'applied';
        }

        $app->update([
            'status' => $dbStatus,
        ]);

        return back()->with('success', 'Candidate application status updated successfully to ' . $request->status);
    }
}
