<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OpportunitiesController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $q = DB::table('opportunities')->orderByDesc('id');
        if ($request->filled('city_id')) {
            $q->where('city_id', (int)$request->get('city_id'));
        }
        $page = max(1, (int)$request->query('page', 1));
        $perPage = max(1, min(100, (int)$request->query('per_page', 50)));
        $total = (clone $q)->count();
        $items = $q->forPage($page, $perPage)->get();
        return response()->json([
            'items' => $items,
            'pagination' => [
                'page' => $page,
                'per_page' => $perPage,
                'total' => $total,
            ],
        ]);
    }

    public function push(Request $request): JsonResponse
    {
        $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'integer|exists:opportunities,id',
            'segment' => 'array',
            'segment.roles' => 'array',
            'segment.cities' => 'array',
            'segment.notif_levels' => 'array',
        ]);

        $ids = $request->input('ids', []);
        $segment = $request->input('segment', []);

        try {
            // Dispatch push job
            \App\Jobs\PushOpportunitiesJob::dispatch($ids, $segment);

            // Update opportunities status to scheduled
            \DB::table('opportunities')
                ->whereIn('id', $ids)
                ->update([
                    'status' => 'scheduled',
                    'scheduled_at' => now(),
                    'updated_at' => now()
                ]);

            return response()->json([
                'success' => true,
                'pushed' => count($ids),
                'skipped' => 0,
                'message' => 'فرصت‌ها برای ارسال زمان‌بندی شدند'
            ]);

        } catch (\Throwable $e) {
            \Log::error('Admin push opportunities failed', [
                'ids' => $ids,
                'segment' => $segment,
                'error' => $e->getMessage()
            ]);

            return response()->json([
                'success' => false,
                'pushed' => 0,
                'skipped' => count($ids),
                'message' => 'خطا در ارسال: ' . $e->getMessage()
            ], 500);
        }
    }
}
