<?php

namespace App\Http\Controllers;

use App\Tag;
use App\Article;
use DataTables;
use Response;
use Auth;
use Storage;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Services\Uploader; #custom class

class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data['articles'] = Article::latest()->get();
        $data['page'] = 'Article';
        return view('backend.article.index')->with($data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data['page'] = 'Article';
        return view('backend.article.form')->with($data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        # Make validation rules
        $rules = collect([
            'tags' => 'required',
            'image' => 'required',
        ]);

        # Validation rules for language input
        foreach (config('translatable.locales') as $locale => $language) {
            $rules->put('title.'.$locale.'', 'required');
            $rules->put('content.'.$locale.'', 'required');
        }

        $alt = $request->alt;

        # Validate
        $this->validate($request, $rules->toArray());

        if ($request->image) {
            
            # Save new image
            $imageName = Uploader::SaveImage($request->image, 'banner_', 'img/article/', $alt[app()->getLocale()]);

        }

        $db = new Article();
        $db->user_id = Auth::user()->id;
        $db->banner = $imageName;

        foreach (config('translatable.locales') as $key => $value) {
            $db->{'title:'.$key} = $request->title[$key];
            $db->{'content:'.$key} = $request->content[$key];
            $db->{'alt:'.$key} = $request->alt[$key];
        }

        $tags = explode(',', $request->tags);
        $ids = collect([]);
        foreach ($tags as $tag) {
            //Add new tags
            $tag = Tag::updateOrCreate(
                ['name' => $tag ],[]
            );    
            $ids->push($tag->id);
        }
        $db->save();

        $db->tags()->sync($ids);


        return redirect()->route('articles.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\article  $article
     * @return \Illuminate\Http\Response
     */
    public function show(Article $article)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\article  $article
     * @return \Illuminate\Http\Response
     */
    public function edit(Article $article)
    {
        $data['route'] = route('articles.update', $article->id);
        $data['method'] = method_field('PUT');
        $data['article'] = $article;
        $data['page'] = 'Article';
        return view('backend.article.form')->with($data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\article  $article
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Article $article)
    {
        # Make validation rules
        $rules = collect([
            'tags' => 'required',
        ]);

        # Validation rules for language input
        foreach (config('translatable.locales') as $locale => $language) {
            $rules->put('title.'.$locale.'', 'required');
            $rules->put('content.'.$locale.'', 'required');
        }

        # Validate
        $this->validate($request, $rules->toArray());

        # Get the old image name incase no image uploaded
        $imageName = $article->banner;

        if ($request->image) {
            
            # Save new image
            $imageName = Uploader::SaveImage($request->image, 'banner_', 'img/article/', $request->alt[app()->getLocale()]);

            # Delete old image if new one uploaded
            if($article->banner!=''){
              Storage::delete('/img/article/'.$article->banner);          
            }
        }

        $article->user_id = Auth::user()->id;
        $article->banner = $imageName;

        foreach (config('translatable.locales') as $key => $value) {
            $article->{'title:'.$key} = $request->title[$key];
            $article->{'alt:'.$key} = $request->alt[$key];
            $article->{'content:'.$key} = $request->content[$key];
        }

        $tags = explode(',', $request->tags);
        $ids = collect([]);
        foreach ($tags as $tag) {
            //Add new tags
            $tag = Tag::updateOrCreate(
                ['name' => $tag ],[]
            );    
            $ids->push($tag->id);
        }

        $article->tags()->sync($ids);

        $article->save();

        return redirect()->route('articles.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\article  $article
     * @return \Illuminate\Http\Response
     */
    public function destroy(Article $article)
    {
        $article->deleteTranslations();
        if($article->banner!=''){
            Storage::delete('/img/article/'.$article->banner);          
        }   
        $article->delete();
        return redirect()->back();
    }

    /**========== Added functions =========**/

    /**========== Publish =========**/
    public function publish(Article $article)
    {
        $article->published = true;
        $article->save();

        return redirect()->back();
    }

    /**========== Hide =========**/
    public function hide(Article $article)
    {
        $article->published = false;
        $article->featured = false;
        $article->save();

        return redirect()->back();
    }
    /**========= Change featured =========**/
    public function featured(Article $article)
    {
        $featured = Article::where('featured', true)->first();
        if($featured){
            $featured->featured = false;
            $featured->save();            
        }

        $article->featured = true;
        $article->published = true;
        $article->save();

        return redirect()->back();
    } 
}
