<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Coach;
use App\Models\Member;
use App\Services\AdminNotificationService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class NotificationController extends Controller
{
    public function __construct(
        protected AdminNotificationService $adminNotificationService
    ) {}

    public function index()
    {
        return view('admin.notifications.index');
    }

    public function sendGeneral(Request $request)
    {
        $data = $request->validate([
            'title' => ['required', 'string', 'max:255'],
            'message' => ['required', 'string', 'max:1000'],
            'member_ids' => ['nullable', 'array'],
            'member_ids.*' => ['integer', 'exists:members,id'],
            'coach_ids' => ['nullable', 'array'],
            'coach_ids.*' => ['integer', 'exists:coaches,id'],
        ]);

        $memberIds = $data['member_ids'] ?? [];
        $coachIds  = $data['coach_ids'] ?? [];

        if (empty($memberIds) && empty($coachIds)) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => __('Please select at least one recipient (members/coaches).'),
                ], 422);
            }

            return redirect()
                ->back()
                ->withInput()
                ->with('error', __('Please select at least one recipient (members/coaches).'));
        }

        $this->adminNotificationService->queueGeneralNotification(
            $data['title'],
            $data['message'],
            $memberIds,
            $coachIds
        );

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => __('Notification queued successfully.'),
            ]);
        }

        return redirect()
            ->route('admin.notifications.index')
            ->with('success', __('Notification queued successfully.'));
    }

    public function sendSpecific(Request $request)
    {
        $data = $request->validate([
            'member_id' => ['required', 'integer', 'exists:members,id'],
            'title' => ['required', 'string', 'max:255'],
            'message' => ['required', 'string', 'max:1000'],
        ]);

        $this->adminNotificationService->queueSpecificCustomerNotification(
            (int) $data['member_id'],
            $data['title'],
            $data['message']
        );

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => __('Notification queued successfully.'),
            ]);
        }

        return redirect()
            ->route('admin.notifications.index')
            ->with('success', __('Notification queued successfully.'));
    }

    public function sendSpecificCoach(Request $request)
    {
        $data = $request->validate([
            'coach_id' => ['required', 'integer', 'exists:coaches,id'],
            'title' => ['required', 'string', 'max:255'],
            'message' => ['required', 'string', 'max:1000'],
        ]);

        $this->adminNotificationService->queueSpecificCoachNotification(
            (int) $data['coach_id'],
            $data['title'],
            $data['message']
        );

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => __('Notification queued successfully.'),
            ]);
        }

        return redirect()
            ->route('admin.notifications.index')
            ->with('success', __('Notification queued successfully.'));
    }

    // Select2 options (JSON)
    public function membersOptions(Request $request): JsonResponse
    {
        $q = (string) $request->input('q', '');

        $members = Member::active()
            ->when($q !== '', function ($query) use ($q) {
                $query->where(function ($qq) use ($q) {
                    $qq->where('name', 'like', "%{$q}%")
                        ->orWhere('phone', 'like', "%{$q}%")
                        ->orWhere('email', 'like', "%{$q}%");
                });
            })
            ->orderBy('id')
            ->limit(25)
            ->get(['id', 'name']);

        return response()->json($members->map(fn (Member $m) => [
            'id' => $m->id,
            'text' => $m->name,
        ])->values());
    }

    public function coachesOptions(Request $request): JsonResponse
    {
        $q = (string) $request->input('q', '');

        $coaches = Coach::active()
            ->when($q !== '', function ($query) use ($q) {
                $query->where(function ($qq) use ($q) {
                    $qq->where('name', 'like', "%{$q}%")
                        ->orWhere('phone', 'like', "%{$q}%")
                        ->orWhere('email', 'like', "%{$q}%");
                });
            })
            ->orderBy('id')
            ->limit(25)
            ->get(['id', 'name']);

        return response()->json($coaches->map(fn (Coach $c) => [
            'id' => $c->id,
            'text' => $c->name,
        ])->values());
    }
}
