<?php

namespace App\Http\Controllers\Admin;

use App\Module;
use Exception;
use App\Article;
use App\ArticlePhoto;
use Illuminate\View\View;
use App\ArticleDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use App\Http\Requests\ArticleRequest;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class ArticleController extends Controller
{

    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath = '/admin/articles';
    /** View folder */
    private $viewDirectory = 'admin.articles.';

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('articles.head');
        $request= $request->toArray();
        return view($this->viewDirectory.'index',compact('title'));
    }

    /**
     * return data of the pages.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Article::latest()
            ->join('article_descriptions AS ad', 'articles.id', 'ad.article_id')
            ->join('languages', 'languages.id', 'ad.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['ad.title', 'articles.*']);

        if ($request->date_from) {
            $query->whereDate('articles.created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('articles.created_at', '<=', $request->date_to);
        }

        if ($request->name) {
            $query->where('ad.title', 'LIKE', '%'.$request->name.'%');
        }

        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }

        $articles= $query->paginate(100);

        return view($this->viewDirectory.'grid',compact('articles'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('articles.store');
        $head= metaFields('articles', 'add_new', getCurrentLocale()) ?? __('articles.new');
        return view( $this->viewDirectory.'form', compact('action', 'head') );
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param ArticleRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(ArticleRequest $request) :RedirectResponse
    {
        $data = $request->all();

        // update image to youtube api thumbnail if request have not image
        // update image to youtube api thumbnail if request have not image
        $data['video_type'] = $request->video_type ?? null;
        if ($request->video_type == 1){
            $parseVideo= parseExternalVideoLink($request->video_url);
            $data['image'] = $parseVideo['image'];
            $data['video'] = $parseVideo['url'];
        }

        $article = Article::create($data);

        // Insert Description
        $this->saveData($request, $article->id);
        // dd($article->id);
        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param Article $article
     * @return View
     */
    public function edit(Article $article) :View
    {
        $action= route('articles.update', $article->id);
        $head= metaFields('articles', 'edit', getCurrentLocale()) ?? __('articles.edit');

        $query = ArticleDescription::where('article_id', $article->id)
            ->join('languages', 'languages.id', 'article_descriptions.language_id')
            ->select(['article_descriptions.*', 'languages.local']);

        $articleDescription= $query->get();

        foreach ($articleDescription as $row) {
            $article[$row->local]= $row;
        }

        return view( $this->viewDirectory.'form', compact('article', 'action', 'head') );
    }

    /**
     * Update the specified resource in storage.
     *
     * @param ArticleRequest $request
     * @param Article $article
     * @return RedirectResponse|Redirector
     */
    public function update(ArticleRequest $request, Article $article) :RedirectResponse
    {

        $data = $request->all();

        // update image to youtube api thumbnail if request have not image
        $data['video_type'] = $request->video_type ?? null;
        if ($request->video_type == 1){
            $parseVideo= parseExternalVideoLink($request->video_url);
            $data['video'] = $parseVideo['url'];
            $data['image'] = $parseVideo['image'];
        }

        // Update image and category id if request has it
        $article->update($data);

        // Delete old description
        ArticleDescription::where('article_id', $article->id)->delete();

        // delete old photos
        ArticlePhoto::where('article_id', $article->id)->delete();

        // Insert new description
        $this->saveData( $request, $article->id );

        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Handle Save form data
     *
     * @param ArticleRequest $request
     * @param int $article_id
     * @return void
     */

    private function saveData(ArticleRequest $request, int $article_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'article_id'=> $article_id,
                'language_id'=> $lang->id,
                'title'=> $requestData['title_'.$lang->local],
                'slug'=> $requestData['slug_'.$lang->local],
                'meta_description'=> $requestData['meta_description_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
                'keywords'=> $requestData['keywords_'.$lang->local],
            ];
            ArticleDescription::create($data);
        }

        if ($request->has('images')){

            foreach ($request->images as $image) {
                $data=[
                    'image'=> $image,
                    'article_id'=> $article_id,
                ];

                ArticlePhoto::create($data);

            }
        }

    }


    /**
     * Remove the specified resource from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :JsonResponse
    {
        $article = Article::withTrashed()->find($id);
        if ($article) {
            if ($article->deleted_at) {
                $article->forceDelete();
            } else {
                $article->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

    /**
     * Remove several pages by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        if ($request->force) {
            Article::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Article::whereIn('id', $ids)->delete();
        }

        return response()->json(['message'=> __('dashboard.deletedDone')]);
    }

    /**
     * Restore the specified category from storage
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function restore(Request $request, int $id) :JsonResponse
    {
        $article = Article::withTrashed()->find($id);

        if ($article){
            $article->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);
    }

    /**
     * Restore several pages by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function restoreAll(Request $request) :JsonResponse
    {
        $article = Article::whereIn('id', $request->ids)->onlyTrashed();
        if ($article){
            $article->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}
