<?php

namespace App\Http\Controllers\Admin;

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

class FeaturedAdsController extends Controller
{
    public function push(Request $request): JsonResponse
    {
        $request->validate([
            'id' => 'required|integer|exists:featured_ads,id',
            'segment' => 'array',
            'segment.roles' => 'array',
            'segment.cities' => 'array',
            'segment.notif_levels' => 'array',
        ]);

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

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

            // Update featured ad status to scheduled
            \DB::table('featured_ads')
                ->where('id', $id)
                ->update([
                    'status' => 'scheduled',
                    'scheduled_at' => now(),
                    'updated_at' => now()
                ]);

            return response()->json([
                'success' => true,
                'pushed' => 1,
                'message' => 'آگهی ویژه برای ارسال زمان‌بندی شد'
            ]);

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

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

