<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\ApiCode;
use App\Models\NewFeed;
use Illuminate\Support\Str;
use App\Http\Controllers\AppBaseController;

use Validator;

class NewsFeedController extends AppBaseController
{
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => [
            'all', 'main',
            'gallery',
        ]]);
    }
    public function gallery(Request $request)
    {
        $limit = 6;

        if ($request->query('limit') != null)
            $limit = $request->query('limit');
        $news = NewFeed::select('id', 'title', 'type')
            ->where(function ($query) use ($request) {
                if ($request->query('type') != null)
                    $query->where('type', $request->query('type'));
            })
            ->orderBy('created_at', 'DESC')->limit($limit)->get();

        return $this->sendResponse($news, "gallery fetched successfully", ApiCode::SUCCESS, 0);
    }
    public function main(Request $request)
    {
        $limit = 6;
        if ($request->query('limit') != null)
            $limit = $request->query('limit');
        $result = array();
        $news0 = NewFeed::where('type', 0)->orderBy('created_at', 'DESC')->limit($limit)->get();
        if (count($news0) > 0) {
            foreach ($news0 as $d) {
                $d->seenCount += 1;
                $d->save();
            }
            array_push($result, $news0);
        }
        $news1 =  NewFeed::where('type', 1)->orderBy('created_at', 'DESC')->limit($limit)->get();
        if (count($news1) > 0) {
            foreach ($news1 as $d) {
                $d->seenCount += 1;
                $d->save();
            }
            array_push($result, $news1);
        }
        $news2 =  NewFeed::where('type', 2)->orderBy('created_at', 'DESC')->limit($limit)->get();
        if (count($news2) > 0) {
            foreach ($news2 as $d) {
                $d->seenCount += 1;
                $d->save();
            }
            array_push($result, $news2);
        }
        $news3 =  NewFeed::where('type', 3)->orderBy('created_at', 'DESC')->limit($limit)->get();

        if (count($news3) > 0) {
            foreach ($news3 as $d) {
                $d->seenCount += 1;
                $d->save();
            }
            array_push($result, $news3);
        }


        return $this->sendResponse($result, "news fetched successfully", ApiCode::SUCCESS, 0);
    }
    public function all(Request $request)
    {
        $limit = 10;
        if ($request->query('limit') != null)
            $limit = $request->query('limit');

        $news = NewFeed::where(function ($query) use ($request) {
            if ($request->query('type'))
                $query->where('type', $request->query('type'));
        })->where(function ($query) use ($request) {
            if ($request->query('search'))
                $query->where('title', 'like', '%' . $request->query('search') . '%')
                    ->orWhere('content', 'like', '%' . $request->query('search') . '%')
                    ->orWhere('tags', 'like', '%' . $request->query('search') . '%');
        })->orderBy('created_at', 'DESC')->paginate($limit)->toArray();
        foreach ($news['data'] as $d) {
            NewFeed::where('id', $d['id'])->update(['seenCount' => $d['seenCount'] + 1]);
        }
        return $this->sendResponse($news, "news fetched successfully", ApiCode::SUCCESS, 0);
    }

    public function add(Request $request)
    {
        $rules =
            [

                'title' => 'required',
                'content' => 'required',
                'type' => 'required',
                'tags' => 'required',
            ];
        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            return $this->sendResponse(
                $validator->errors(),
                "validation errors",
                ApiCode::BAD_REQUEST,
                1
            );
        }


        $input = $request->all();

        $input['user_id'] = auth()->user()->id;

        $news = NewFeed::create($input);

        if ($request->has('image')) {
            $uuid = Str::uuid();
            $news->addMediaFromRequest('image')->usingName($uuid)->usingFileName($uuid . '.' . $request->image->extension())->toMediaCollection('images');
            $news->save();
            //Log::error($request->file);
        }
        return $this->sendResponse(
            [NewFeed::where('id', $news->id)->first()],
            "news created successfully",
            ApiCode::CREATED,
            0
        );
    }

    public function edit($id, Request $request)
    {
        $rules =
            [

                'title' => 'required',
                'content' => 'required',
                'tags' => 'required',
            ];
        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            return $this->sendResponse(
                $validator->errors(),
                "validation errors",
                ApiCode::BAD_REQUEST,
                1
            );
        }

        $input = $request->all();
        $news = NewFeed::where('id', $id)->firstOrFail();
        $news->title = $input['title'];
        $news->content = $input['content'];
        $news->tags = $input['tags'];
        $news->save();

        if ($request->has('image')) {
            $news->media->each->delete();
            $news->save();
            $uuid = Str::uuid();
            $news->addMediaFromRequest('image')->usingName($uuid)->usingFileName($uuid . '.' . $request->image->extension())->toMediaCollection('images');
            $news->save();
            //Log::error($request->file);
        }
        return $this->sendResponse(
            [NewFeed::where('id', $news->id)->first()],
            "news created successfully",
            ApiCode::CREATED,
            0
        );
    }

    public function delete($id, Request $request)
    {
        $diwan = NewFeed::where('id', $id)->firstOrFail();


        $diwan->delete();
        return $this->sendResponse(
            null,
            "diwan deleted successfully",
            ApiCode::SUCCESS,
            0
        );
    }
}
