<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\JobOffer;
use App\Models\Worker;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class WorkerProfileController extends Controller
{
    /**
     * Get authorized worker's profile details.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getProfile(Request $request)
    {
        /** @var Worker $worker */
        $worker = $request->attributes->get('worker');
        
        $worker->load(['category', 'skills', 'documents']);

        return response()->json([
            'success' => true,
            'data' => [
                'worker' => $worker
            ]
        ], 200);
    }

    /**
     * Update authorized worker's profile details.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateProfile(Request $request)
    {
        /** @var Worker $worker */
        $worker = $request->attributes->get('worker');

        $validator = Validator::make($request->all(), [
            'name' => 'nullable|string|max:255',
            'age' => 'nullable|integer|min:18|max:70',
            'nationality' => 'nullable|string|max:100',
            'salary' => 'nullable|numeric|min:0',
            'availability' => 'nullable|string|max:100',
            'experience' => 'nullable|string|max:100',
            'religion' => 'nullable|string|max:100',
            'bio' => 'nullable|string|max:1000',
            'category_id' => 'nullable|exists:worker_categories,id',
            'skills' => 'nullable|array',
            'skills.*' => 'exists:skills,id',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation error.',
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            DB::transaction(function () use ($request, $worker) {
                // Update worker attributes
                $updateData = $request->only([
                    'name', 'age', 'nationality', 'salary', 'availability',
                    'experience', 'religion', 'bio', 'category_id'
                ]);

                // Filter out null inputs if we want to support partial updates
                $updateData = array_filter($updateData, function ($value) {
                    return !is_null($value);
                });

                $worker->update($updateData);

                // Sync skills if provided
                if ($request->has('skills')) {
                    $worker->skills()->sync($request->skills ?: []);
                }
            });

            $worker->load(['category', 'skills', 'documents']);

            return response()->json([
                'success' => true,
                'message' => 'Profile updated successfully.',
                'data' => [
                    'worker' => $worker
                ]
            ], 200);

        } catch (\Exception $e) {
            logger()->error('Mobile Worker Profile Update Failure: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while updating your profile.',
                'error' => app()->environment('local') ? $e->getMessage() : 'Internal Server Error'
            ], 500);
        }
    }

    /**
     * Get all job offers received by the worker.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getOffers(Request $request)
    {
        /** @var Worker $worker */
        $worker = $request->attributes->get('worker');

        $offers = JobOffer::where('worker_id', $worker->id)
            ->with(['employer.employerProfile']) // Load employer and their profile details
            ->latest()
            ->get();

        return response()->json([
            'success' => true,
            'data' => [
                'offers' => $offers
            ]
        ], 200);
    }

    /**
     * Respond to a specific job offer (Accept or Reject).
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function respondToOffer(Request $request, $id)
    {
        /** @var Worker $worker */
        $worker = $request->attributes->get('worker');

        $validator = Validator::make($request->all(), [
            'status' => 'required|string|in:accepted,rejected',
        ], [
            'status.in' => 'Status must be either accepted or rejected.'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation error.',
                'errors' => $validator->errors()
            ], 422);
        }

        try {
            $offer = JobOffer::where('id', $id)
                ->where('worker_id', $worker->id)
                ->first();

            if (!$offer) {
                return response()->json([
                    'success' => false,
                    'message' => 'Job offer not found.'
                ], 404);
            }

            if ($offer->status !== 'pending') {
                return response()->json([
                    'success' => false,
                    'message' => 'This job offer has already been responded to.'
                ], 400);
            }

            $responseStatus = $request->status;

            DB::transaction(function () use ($offer, $worker, $responseStatus) {
                // Update offer status
                $offer->update(['status' => $responseStatus]);

                // If accepted, change worker status to 'Hired'
                if ($responseStatus === 'accepted') {
                    $worker->update(['status' => 'Hired']);
                }
            });

            return response()->json([
                'success' => true,
                'message' => "Job offer successfully " . $responseStatus . ".",
                'data' => [
                    'offer' => $offer,
                    'worker_status' => $worker->fresh()->status
                ]
            ], 200);

        } catch (\Exception $e) {
            logger()->error('Mobile Respond to Offer Failure: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'An error occurred while responding to the job offer.',
                'error' => app()->environment('local') ? $e->getMessage() : 'Internal Server Error'
            ], 500);
        }
    }
}
