<?php

namespace App\Http\Controllers\API\V1;

use App\Http\Controllers\Controller;
use App\Http\Resources\AdvertisementResource;
use App\Models\Advertisement;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class AdvertisementController extends Controller
{
    public function index(Request $request): AnonymousResourceCollection
    {
        $user = $request->user();

        $query = Advertisement::query()->active();

        if ($user && $user->profile) {
            // Filter by user's gender
            if ($user->profile->gender === 'male') {
                $query->whereIn('targeted_audience', ['male', 'all']);
            } elseif ($user->profile->gender === 'female') {
                $query->whereIn('targeted_audience', ['female', 'all']);
            }

            // Filter by user's language preference from settings
            $languagePreference = $user->profile->settings['language'] ?? 'both';
            if ($languagePreference === 'ar') {
                $query->whereIn('targeted_language', ['ar', 'both']);
            } elseif ($languagePreference === 'en') {
                $query->whereIn('targeted_language', ['en', 'both']);
            }
        }

        $advertisements = $query
            ->orderBy('sort_order', 'asc')
            ->orderBy('created_at', 'desc')
            ->get();

        return AdvertisementResource::collection($advertisements);
    }

    public function show(Request $request, int $id): AdvertisementResource|JsonResponse
    {
        $advertisement = Advertisement::active()->findOrFail($id);

        return new AdvertisementResource($advertisement);
    }
}
