<?php

namespace TPS\API\Http\Controllers;

use Illuminate\Http\Request;
use TPS\API\Http\Resources\Core\Slider;
use TPS\Shop\Repositories\SliderRepository;
use TPS\API\Http\Resources\Catalog\Product as ProductResource;
use Webkul\RestApi\Http\Controllers\V1\Shop\ShopController;
use Carbon\Carbon;
class Sliders extends ShopController
{
    protected $requestException = ['page', 'limit', 'pagination', 'sort', 'order', 'token','currency'];

    public function resource(){
        return Slider::class;
    }

    public function repository(){
        return SliderRepository::class;
    }


    public function allResources(Request $request)
    {
        $query = $this->getRepositoryInstance()->scopeQuery(function ($query) use ($request) {

            foreach ($request->except($this->requestException) as $input => $value) {
                $query = $query->whereIn($input, array_map('trim', explode(',', $value)));
            }

            if ($sort = $request->input('sort')) {
                $query = $query->orderBy($sort, $request->input('order') ?? 'desc');
            } else {
                $query = $query->orderBy('id', 'desc');
            }

            return $query->where(function ($q){
                $q->whereNull('expired_at')
                    ->orWhereDate('expired_at','>=',Carbon::today());
            });
        });

        if (is_null($request->input('pagination')) || $request->input('pagination')) {
            $results = $query->paginate($request->input('limit') ?? 10);
        } else {
            $results = $query->get();
        }

        return $this->getResourceCollection($results);
    }

    public function weeklyOffers()
    {
        $products =  $this->getRepositoryInstance()->getWeeklyOffers();
        $productsArray = ProductResource::collection($products);
        return response()->json(['data' => $productsArray]);
    }
}