<?php

namespace App\Http\Controllers;

use App\Models\District;
use App\Models\User;
use App\Models\PointPlan;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Log;

class ManagerController extends Controller
{
    public function getPointsAndOperators($id): JsonResponse
    {
        $user = User::find($id);
        $pointPlans = PointPlan::whereNull('operator_id')
        ->whereHas('point.district', function ($q) use ($user) {
            $q->where('manager_id', $user->id);
        })
        ->with(['point', 'point.district'])
        ->get();
        $operators = User::whereHas('role', function ($query) {
            $query->where('name', 'Оператор');
        })->where('is_active', true)->get()->map(function ($user) {
            $role = $user->role;
            return [
                'id' => $user->id,
                'first_name' => $user->first_name,
                'middle_name' => $user->middle_name,
                'last_name' => $user->last_name,
                'position' => $user->position,
                'role' => $role,
            ];
        });
        return response()->json(['point_plans' => $pointPlans, 'operators' => $operators]);
    }

    public function proposeOperatorToPointPlan(Request $request): JsonResponse
    {
        $authUser = Auth::user();
        $user = User::find($request->operator_id);
        $validated = $request->validate([
            'point_plan_id' => ['required', 'exists:point_plans,id'],
            'operator_id' => ['required', 'exists:users,id'],
        ]);

        $operatorId = $validated['operator_id'];
        $plan = PointPlan::findOrFail($validated['point_plan_id']);

        $count = PointPlan::where('operator_id', $operatorId)
        ->whereDate('day', $plan->day)
        ->count();
        if ($count >= 2) {
            return response()->json([
                'error' => 'Оператор уже назначен на 2 ПУИДД в этот день',
            ], 400);
        }
        // Назначаем оператора
        $plan->update(['operator_id' => $operatorId]);
        $user->userNotifications()->create([
            'title' => "Назначение оператора на ПУИДД",
            'content'=> 'Вы назначены оператором на план работ ' . $plan->id . ' по ПУИДД '  . $plan->point_id . '.',
        ]);

        Log::create([
            'model_id' => $plan->id,
            'model_type' => PointPlan::class,
            'change' =>  'Оператор',
            'action' => 'на план работ ' . $plan->id . ' по ПУИДД ' . $plan->point_id . ' назначен оператор',
            'old_value' => '',
            'new_value' => $user->fullName(),
            'created_by' => $authUser->id,
        ]);
        return response()->json([
            'message' => 'Оператор успешно назначен на ПУИДД',
            'plan_id' => $plan->id,
            'operator_id' => $operatorId,
        ]);
    }
    public function getNearestPointPlans($id): JsonResponse
    {
        $currentPlan = PointPlan::with('point')->findOrFail($id);

        $lat = $currentPlan->point->latitude;
        $lon = $currentPlan->point->longitude;

        $nearestPlans = PointPlan::whereHas('point', function ($query) use ($currentPlan) {
                $query->where('id', '!=', $currentPlan->point->id);
            })
            ->whereDate('day', $currentPlan->day)
            ->whereNull('operator_id')
            ->with('point')
            ->get()
            ->sortBy(function ($plan) use ($lat, $lon) {
                $distance = 6371 * acos(
                    cos(deg2rad($lat)) *
                    cos(deg2rad($plan->point->latitude)) *
                    cos(deg2rad($plan->point->longitude) - deg2rad($lon)) +
                    sin(deg2rad($lat)) *
                    sin(deg2rad($plan->point->latitude))
                );
                return $distance;
            })
            ->take(5)
            ->values();

        return response()->json(['nearest_plans' => $nearestPlans]);
    }

}
