<?php

namespace App\Http\Controllers\Admin;

use Exception;
use App\Photo;
use App\PhotoCategory;
use App\PhotoDescription;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\PhotoCategoryDescription;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use App\Http\Requests\PhotoCategoryRequest;

class PhotoCategoryController extends Controller
{
    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath = '/admin/photoCategories';
    /** View folder */
    private $viewDirectory = 'admin.photo_categories.';

    /**
     * Display a listing of the resource.
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('photoCategories.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 = PhotoCategory::latest()
            ->join('photo_category_descriptions AS pcd', 'photo_categories.id', 'pcd.photo_category_id')
            ->select(['pcd.name', 'photo_categories.*']);

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

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

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

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

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

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

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

    /**
     * Store a newly created resource in storage.
     * @param PhotoCategoryRequest $request
     * @return RedirectResponse
     */
    public function store(PhotoCategoryRequest $request) :RedirectResponse
    {
        $photoCategory = PhotoCategory::create();

        // Insert Description
        $this->saveData($request, $photoCategory->id);

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


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

        $query = PhotoCategoryDescription::where('photo_category_id', $photoCategory->id)
            ->join('languages', 'languages.id', 'photo_category_descriptions.language_id')
            ->select(['photo_category_descriptions.*', 'languages.local']);

        $photoCategoryDescription= $query->get();

        foreach ($photoCategoryDescription as $row) {
            $photoCategory[$row->local]= $row;
        }


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

    /**
     * Update the specified resource in storage.
     *
     * @param PhotoCategoryRequest $request
     * @param PhotoCategory $photoCategory
     * @return RedirectResponse|Redirector
     */
    public function update(PhotoCategoryRequest $request, PhotoCategory $photoCategory) :RedirectResponse
    {
        // Update the "updated_at" column only
        $photoCategory->touch();

        // Delete old description
        PhotoCategoryDescription::where('photo_category_id', $photoCategory->id)->delete();

        // Delete old photos
        Photo::where('photo_category_id', $photoCategory->id)->delete();

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

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

    /**
     * Handle Save form data
     *
     * @param PhotoCategoryRequest $request
     * @param int $photo_category_id
     * @return void
     */

    private function saveData(PhotoCategoryRequest $request, int $photo_category_id):void
    {
        $requestData= $request->all();

        $photoCategoryDescription=[
            'name'=> $requestData['name_'.getCurrentLocale()],
            'slug'=> $requestData['slug_'.getCurrentLocale()],
            'photo_category_id'=> $photo_category_id,
            'language_id'=> currentLanguage()->id,
        ];

        PhotoCategoryDescription::create($photoCategoryDescription);

        if ($request->has('images')) {
            foreach ($request->images as $key => $image) {
                $photoData = [
                    'image' => $image,
                    'photo_category_id' => $photo_category_id
                ];

                $photo = Photo::create($photoData);

                $photoDescription = [
                    'title'=> $requestData['image_title_'.getCurrentLocale()][$key],
                    'photo_id'=> $photo->id,
                    'language_id'=> currentLanguage()->id,
                ];

                PhotoDescription::create($photoDescription);
            }
        }
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :JsonResponse
    {
        $photoCategory = PhotoCategory::withTrashed()->find($id);
        if ($photoCategory) {
            if ($photoCategory->deleted_at) {
                $photoCategory->forceDelete();
            } else {
                $photoCategory->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) {
            PhotoCategory::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            PhotoCategory::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
    {
        $photoCategory = PhotoCategory::withTrashed()->find($id);

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