<?php

namespace App\Http\Controllers\Admin;

/** Ajax Request */

use Exception;
use App\Log;
use App\News;
use Illuminate\View\View;
use App\NewDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use Illuminate\Http\RedirectResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\NewRequest; // for Validation
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class NewController extends Controller
{

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

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

    /**
     * return data of the news.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = News::latest()
        ->join('new_descriptions AS cd', 'news.id', 'cd.new_id')
        ->join('languages', 'languages.id', 'cd.language_id')
        ->where('local', LaravelLocalization::getCurrentLocale())
        ->select(['cd.name', 'news.*']);

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

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

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

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

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

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

    /**
     * Store a newly created category in storage.
     * @param NewRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(NewRequest $request) :RedirectResponse
    {
       

        $new = News::create($request->all());
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'الاخبار العاجلة','action'=>'اضافة']);
       
        // Insert Description
        $this->saveData( $request, $new->id );

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

    /**
     * Show the form for editing the specified category.
     *
     * @param  New  $new
     * @return View
     */
    public function edit(News $news) :View
    {
        $new = $news;
        $action= route('news.update', $new->id);
        $head = __('news.edit');
        $query = NewDescription::where('new_id', $new->id)
        ->join('languages', 'languages.id', 'new_descriptions.language_id')
        ->select(['new_descriptions.*', 'languages.local']);

        $NewDescription= $query->get();

        foreach ($NewDescription as $row) {
            $new[$row->local]= $row;
        }

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

    /**
     * Update the specified category in storage.
     * @param NewRequest $request
     * @param New $new
     * @return RedirectResponse|Redirector
     */
    public function update(NewRequest $request, News $news) :RedirectResponse
    {
        $new = $news;
        // Update the "updated_at" column only
        $new->update($request->all());
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'الاخبار العاجلة','action'=>'تعديل']);
       

        // Delete old description
        NewDescription::where('new_id', $new->id)->delete();

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

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

    /**
     * Handle Save form data
     *
     * @param NewRequest $request
     * @param int $new_id
     * @return void
     */

     private function saveData(NewRequest $request, int $new_id ) :void
     {

        $requestData= $request->all();

        foreach (languages() as $lang) {
            $data=[
                'new_id'=> $new_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
                
            ];

            NewDescription::create($data);
        }

     }

    /**
     * Remove the specified category from storage.
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :JsonResponse
    {
        $new= News::withTrashed()->find($id);
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'الاخبار العاجلة','action'=>'حذف']);
        if ($new) {
            if ($new->deleted_at) {
                $new->forceDelete();
            } else {
                $new->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

    /**
     * Remove several news by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'الاخبار العاجلة','action'=>'حذف']);

        if ($request->force) {
            News::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            News::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
    {
        $new= News::withTrashed()->find($id);
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'الاخبار العاجلة','action'=>'استرجاع']);
        if ($new) {
            $new->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);

    }

    /**
     * Restore several news by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function restoreAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'الاخبار العاجلة','action'=>'استرجاع']);
        News::whereIn('id', $ids)->onlyTrashed()->restore();
        return response()->json(['message'=> __('dashboard.saveDone')]);
    }
}
