<?php

namespace App\Modules\AvailableRequests\Services;

use App\Models\Trip;
use App\Models\ShopperRequest;
use App\Support\Services\BaseService;
use App\Http\Resources\AvailableShopperRequestResource;

class AvailableRequestService extends BaseService
{
    public function getAvailableRequestsForTraveler()
    {
        $user = request()->user();

        // جلب رحلات الترافيلر
        $trips = Trip::where('user_id', $user->id)
            ->where('is_active', true)
            ->where('departure_at', '>', now())
            ->get();

        if ($trips->isEmpty()) {
            return $this->success([
                'requests' => [],
                'message' => 'لا يوجد لديك رحلات نشطة حالياً'
            ]);
        }

        // جمع المدن
        $fromCities = collect();
        $toCities   = collect();

        foreach ($trips as $trip) {
            $fromCities->push(
                trim($trip->outbound_ar ?? ''), 
                trim($trip->outbound_en ?? ''), 
                trim($trip->outbound_zh ?? '')
            );
            $toCities->push(
                trim($trip->inbound_ar ?? ''), 
                trim($trip->inbound_en ?? ''), 
                trim($trip->inbound_zh ?? '')
            );
        }

        $fromCities = $fromCities->filter()->unique()->values();
        $toCities   = $toCities->filter()->unique()->values();

        $requests = ShopperRequest::query()
            ->with([
                'items',
                'user:id,name,phone_number,avatar_url'
            ])
            ->where('status', 'published')
            ->whereNotNull('published_at')
            ->where(function ($q) use ($fromCities) {
                $q->whereIn('buy_from_ar', $fromCities)
                  ->orWhereIn('buy_from_en', $fromCities)
                  ->orWhereIn('buy_from_zh', $fromCities);
            })
            ->where(function ($q) use ($toCities) {
                $q->whereIn('deliver_to_ar', $toCities)
                  ->orWhereIn('deliver_to_en', $toCities)
                  ->orWhereIn('deliver_to_zh', $toCities);
            })
            ->latest('published_at')
            ->paginate(12);

        return $this->success([
            'debug' => [
                'traveler_from_cities' => $fromCities->toArray(),
                'traveler_to_cities'   => $toCities->toArray(),
                'total_found'          => $requests->total(),
            ],
            'requests' => AvailableShopperRequestResource::collection($requests),
            'pagination' => [
                'current_page' => $requests->currentPage(),
                'last_page'    => $requests->lastPage(),
                'per_page'     => $requests->perPage(),
                'total'        => $requests->total(),
            ]
        ], 'Available requests retrieved successfully');
    }

    public function getAvailableRequests()
    {
        return ShopperRequest::query()
            ->with(['user', 'items'])
            ->published()
            ->latest()
            ->get();
    }

    public function showAvailableRequest($id)
    {
        return ShopperRequest::query()
            ->with([
                'user:id,name,phone_number,avatar_url',
                'items'
            ])
            ->where('status', 'published')
            ->whereNotNull('published_at')
            ->findOrFail($id);
    }

    public function getRequestItems($id)
    {
        $request = ShopperRequest::query()
            ->with(['items'])
            ->where('status', 'published')
            ->whereNotNull('published_at')
            ->findOrFail($id);

        return $this->success([
            'request_id' => $request->id,
            'items' => $request->items->map(function ($item) {
                return [
                    'id' => $item->id,
                    'name' => $item->name_en, // أو اعمل localization لو عايز
                    'details' => $item->details_en,
                    'price' => $item->price,
                    'currency' => $item->currency,
                    'quantity' => $item->quantity,
                    'total_price' => $item->total_price,
                    'gallery' => $item->gallery ?? [],
                ];
            }),
        ], 'Request items retrieved successfully');
    }
}