<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Inertia\Inertia;

class WorkerController extends Controller
{
    /**
     * Display a listing of all workers.
     */
    public function index()
    {
        $workers = \App\Models\Worker::with(['category', 'skills'])
            ->latest()
            ->get()
            ->map(function ($worker) {
                // Map languages from database comma-separated string
                $langs = $worker->language ? array_map('trim', explode(',', $worker->language)) : ['English'];
                
                // Map skills dynamically from database
                $mappedSkills = $worker->skills->pluck('name')->toArray();
                if (empty($mappedSkills)) {
                    $mappedSkills = ['cooking', 'cleaning'];
                }

                // Preferred job types: full-time / part-time / live-in / live-out
                $jobTypes = ['full-time', 'part-time', 'live-in', 'live-out'];
                $preferredJobType = $jobTypes[$worker->id % 4];

                return [
                    'id' => $worker->id,
                    'name' => $worker->name,
                    'email' => $worker->email,
                    'phone' => $worker->phone,
                    'gender' => $worker->gender ?? 'Female',
                    'language' => $worker->language ?? 'English',
                    'languages' => $langs,
                    'nationality' => $worker->nationality,
                    'country' => $worker->country,
                    'city' => $worker->city,
                    'area' => $worker->area,
                    'live_in_out' => $worker->live_in_out ?? 'Live-in',
                    'category' => $worker->category ? $worker->category->name : 'N/A',
                    'experience' => $worker->experience,
                    'salary' => (int)$worker->salary,
                    'skills' => $mappedSkills,
                    'preferred_job_type' => $preferredJobType,
                    'status' => $worker->status,
                    'availability' => $worker->availability,
                    'verified' => (bool)$worker->verified,
                    'bio' => $worker->bio,
                    'joined_at' => $worker->created_at ? $worker->created_at->format('Y-m-d') : 'N/A',
                ];
            });

        return Inertia::render('Admin/Workers/Index', [
            'workers' => $workers,
        ]);
    }

    /**
     * Toggle worker active/inactive status.
     */
    public function toggleStatus(Request $request, $id)
    {
        $validated = $request->validate([
            'status' => 'required|in:active,inactive,suspended,banned',
        ]);

        $worker = \App\Models\Worker::findOrFail($id);
        $worker->status = $validated['status'];
        $worker->save();

        return back()->with('success', "Worker status has been updated to {$validated['status']}.");
    }

    /**
     * Override worker availability.
     */
    public function availabilityOverride(Request $request, $id)
    {
        $validated = $request->validate([
            'availability' => 'required|string',
        ]);

        $worker = \App\Models\Worker::findOrFail($id);
        $worker->availability = $validated['availability'];
        $worker->save();

        return back()->with('success', "Worker availability has been overridden to '{$validated['availability']}' successfully.");
    }

    /**
     * Flag worker as fraudulent or suspicious.
     */
    public function flagFraud(Request $request, $id)
    {
        $validated = $request->validate([
            'is_fraud' => 'required|boolean',
            'reason' => 'nullable|string'
        ]);

        $worker = \App\Models\Worker::findOrFail($id);
        $worker->status = $validated['is_fraud'] ? 'suspended' : 'active';
        $worker->save();

        $statusStr = $validated['is_fraud'] ? 'FLAGGED FOR FRAUD' : 'UNFLAGGED';

        return back()->with('success', "Worker #{$id} has been {$statusStr}. Notes: {$validated['reason']}");
    }

    /**
     * Moderation profile updates.
     */
    public function updateProfile(Request $request, $id)
    {
        $validated = $request->validate([
            'name' => 'required|string',
            'phone' => 'required|string',
            'gender' => 'nullable|string',
            'language' => 'nullable|string',
            'country' => 'nullable|string',
            'city' => 'nullable|string',
            'area' => 'nullable|string',
            'live_in_out' => 'nullable|string',
            'category' => 'required|string',
            'experience' => 'required|string',
            'salary' => 'nullable|numeric',
            'bio' => 'nullable|string'
        ]);

        $worker = \App\Models\Worker::findOrFail($id);
        
        $category = \App\Models\WorkerCategory::where('name', $validated['category'])->first();
        if ($category) {
            $worker->category_id = $category->id;
        }

        $worker->name = $validated['name'];
        $worker->phone = $validated['phone'];
        $worker->gender = $validated['gender'] ?? $worker->gender;
        $worker->language = $validated['language'] ?? $worker->language;
        $worker->country = $validated['country'] ?? $worker->country;
        $worker->city = $validated['city'] ?? $worker->city;
        $worker->area = $validated['area'] ?? $worker->area;
        $worker->live_in_out = $validated['live_in_out'] ?? $worker->live_in_out;
        $worker->experience = $validated['experience'];
        $worker->salary = $validated['salary'] ?? $worker->salary;
        $worker->bio = $validated['bio'] ?? $worker->bio;
        $worker->save();

        return back()->with('success', "Worker #{$id} profile details moderated and updated successfully.");
    }

    /**
     * Verify an employer's company details.
     */
    public function verifyEmployer(Request $request, $id)
    {
        $sponsor = \App\Models\Sponsor::findOrFail($id);
        $sponsor->is_verified = true;
        $sponsor->save();

        return back()->with('success', "Employer #{$id} verification status set to APPROVED.");
    }

    /**
     * Suspend employer.
     */
    public function suspendEmployer(Request $request, $id)
    {
        $validated = $request->validate([
            'reason' => 'nullable|string'
        ]);

        $sponsor = \App\Models\Sponsor::findOrFail($id);
        $sponsor->status = 'suspended';
        $sponsor->save();

        return back()->with('success', "Employer #{$id} has been suspended. Reason: " . ($validated['reason'] ?? 'Unspecified violation'));
    }
}
