<?php

namespace AhmadFatoni\ApiGenerator\Controllers\API;

use Cms\Classes\Controller;
use DB;
use Config;
use AhmadFatoni\ApiGenerator\Helpers\Helpers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use RainLab\Blog\Models\Post;
use TPS\Birzha\Classes\BlogPostResource;
use TPS\Birzha\Models\SliderApp;

class BlogPostsApiController extends Controller
{
    protected $Post;

    protected $helpers;

    public function __construct(Post $Post, Helpers $helpers)
    {
        parent::__construct();
        $this->Post = $Post;
        $this->helpers = $helpers;
    }

    //posts list
    public function index(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data, [
            'locale' => 'required|in:ru,en,tm',
            'per_page' => 'numeric',
            'sort_order' => 'in:asc,desc'
        ]);
        if($validator->fails()) {
            return $this->helpers->apiArrayResponseBuilder(400, 'fail', $validator->errors() );
        }

        return response()->json(
            BlogPostResource::collection($this->Post::with(['featured_images', 'translations:locale,model_id,attribute_data',])
                ->orderBy('published_at', $data['sort_order'] ?? 'desc')
                ->paginate($data['per_page'] ?? 7))->response()->getData(), 200);
    }
    
    public function getSliders(Request $request)
    {
        $path = Config::get('cms.storage.media.path');
        
        $data = $request->all();
        $validator = Validator::make($data, [
            //'locale' => 'required|in:ru,en,tm',
            'type' => 'required'
        ]);
        if($validator->fails()) {
            return $this->helpers->apiArrayResponseBuilder(400, 'fail', $validator->errors() );
        }
        $dataSlider = SliderApp::where('type', $data['type'])->orderBy('order', 'desc')->select('id', 'img', 'type', 'order')->get();
        
        //$dataSlider["img"] = $path.$dataSlider["img"];
        
         if($dataSlider){
            $dataSlider->each(function ($item, $key) {
                $item->img = 'http://78.111.88.8:9086'.Config::get('cms.storage.media.path').$item->img;
            });
        }
        
        return response()->json($dataSlider, 200);
    }

    //posts item
    public function show($id, Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data, [
            'locale' => 'required|in:ru,en,tm',
        ]);
        if($validator->fails()) {
            return $this->helpers->apiArrayResponseBuilder(400, 'fail', $validator->errors() );
        }

        if(!$post = $this->Post::find($id)) {
            return $this->helpers->apiArrayResponseBuilder(404, 'not found', ['error' => "Resource id = {$id} could not be found"]);
        } else {
            return new BlogPostResource($post);
        }
    }
}
