<?php

namespace App\Http\Controllers\Admin;

/** Ajax Request */

use Exception;
use App\Models;
use App\Log;
use Illuminate\View\View;
use App\ModelDescription;
use App\ModelPhoto;
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\ModelRequest; // for Validation
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class ModelController extends Controller
{

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

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

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

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

        if ($request->date_to) {
            $query->whereDate('models.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();
        }
        $models= $query->paginate(100);

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

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

    /**
     * Store a newly created Model in storage.
     * @param ModelRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(ModelRequest $request) :RedirectResponse
    {
     
        $max = Models::max('num');
        $request->merge(['num'=>$max+1]);
        if($request->model_id == 'NULL'){
            
            $request->merge(['model_id'=>null]);
        }
        
        $model = Models::create($request->except('images'));
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'الاقسام الفرعية','action'=>'اضافة','product_id'=>$model->id]);
       
        // Insert Description
        $this->saveData( $request, $model->id );

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

    /**
     * Show the form for editing the specified Model.
     *
     * @param  Model  $model
     * @return View
     */
    public function edit(Models $model) :View
    {
        $action= route('models.update', $model->id);
        $head = __('models.edit');
        $query = ModelDescription::where('model_id', $model->id)
        ->join('languages', 'languages.id', 'model_descriptions.language_id')
        ->select(['model_descriptions.*', 'languages.local']);

        $modelDescription= $query->get();

        foreach ($modelDescription as $row) {
            $model[$row->local]= $row;
        }
        
        $models = Models::where('category_id',$model->category_id)->get();
        
        return view( $this->viewDirectory.'form', compact('model', 'action','head','models') );
    }

    /**
     * Update the specified Model in storage.
     * @param ModelRequest $request
     * @param Model $model
     * @return RedirectResponse|Redirector
     */
    public function update(ModelRequest $request, Models $model) :RedirectResponse
    {
        // Update the "updated_at" column only
        
        if($request->model_id == 'NULL'){
            $request->merge(['model_id'=>null]);
        }
        $model->update($request->all());
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'الاقسام الفرعية','action'=>'تعديل','product_id'=>$model->id]);
       

        // Delete old description
        ModelDescription::where('model_id', $model->id)->delete();
       
        $this->saveData( $request, $model->id );

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

    /**
     * Handle Save form data
     *
     * @param ModelRequest $request
     * @param int $model_id
     * @return void
     */

     private function saveData(ModelRequest $request, int $model_id ) :void
     {

        $requestData= $request->all();

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

            ModelDescription::create($data);
        }
        
        if ($request->has('images')){

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

                ModelPhoto::create($data);

            }
        }

     }

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

    /**
     * Remove several models 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) {
            Models::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Models::whereIn('id', $ids)->delete();
        }

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

    /**
     * Restore the specified Model from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function restore(Request $request, int $id) :JsonResponse
    {
        $model= Models::withTrashed()->find($id);
        Log::create(['user_id'=>\Auth::user()->id,'type'=>'الاقسام الفرعية','action'=>'استرجاع']);
        if ($model) {
            $model->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);

    }

    /**
     * Restore several models 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'=>'استرجاع']);
        Models::whereIn('id', $ids)->onlyTrashed()->restore();
        return response()->json(['message'=> __('dashboard.saveDone')]);
    }
}
