<?php

namespace App\Http\Controllers\Admin;

use App\Module;
use Exception;
use App\Writer;
use App\User;
use App\Category;
use Illuminate\View\View;
use App\WriterDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use App\Http\Requests\WriterRequest;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class WriterController extends Controller
{

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

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('writers.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 = Writer::latest()
            ->join('writer_descriptions AS ad', 'writers.id', 'ad.writer_id')
            ->join('languages', 'languages.id', 'ad.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['ad.name', 'writers.*']);

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

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

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

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

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

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param WwriterRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(WriterRequest $request) :RedirectResponse
    {
        
        $writer = Writer::create($request->all());
        
       
        // Insert Description
        $this->saveData($request, $writer->id);

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


    /**
     * Show the form for editing the specified resource.
     *
     * @param Writer $writer
     * @return View
     */
    public function edit(Writer $writer) :View
    {
        $action= route('writers.update', $writer->id);
        $head = __('writers.edit');
        $query = WriterDescription::where('writer_id', $writer->id)
            ->join('languages', 'languages.id', 'writer_descriptions.language_id')
            ->select(['writer_descriptions.*', 'languages.local']);
        
      
        $writerDescription= $query->get();

        foreach ($writerDescription as $row) {
            $writer[$row->local]= $row;
        }

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

    /**
     * Update the specified resource in storage.
     *
     * @param WriterRequest $request
     * @param Writer $writer
     * @return RedirectResponse|Redirector
     */
    public function update(WriterRequest $request, Writer $writer):RedirectResponse
    {
        // Update image and category id if request has it
        $writer->update($request->all());

       

        // Delete old description
        WriterDescription::where('writer_id', $writer->id)->delete();

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

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

    /**
     * Handle Save form data
     *
     * @param WriterRequest $request
     * @param int $writer_id
     * @return void
     */

    private function saveData(WriterRequest $request, int $writer_id ):void
    {
        
        $requestData= $request->all();
        
        foreach (languages() as $lang) {
            $data=[
                'writer_id'=> $writer_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
                
                
            ];
            WriterDescription::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
    {
        $writer = Writer::withTrashed()->find($id);
        if ($writer) {
            if ($writer->deleted_at) {
                $writer->forceDelete();
            } else {
                $writer->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) {
            Writer::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Writer::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
    {
        $writer = Writer::withTrashed()->find($id);

        if ($writer){
            $writer->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
    {
        $writer = Writer::whereIn('id', $request->ids)->onlyTrashed();
        if ($writer){
            $writer->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}
