<?php

namespace App\Http\Controllers\Admin;

use Exception;
use App\Models\Founder;
use Illuminate\View\View;
use App\Models\FounderDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\FounderRequest;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class FounderController extends Controller
{

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

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

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

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

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

        if ($request->description) {
            $query->where('ad.description', 'LIKE', '%'.$request->description.'%');
        }
        if ($request->link) {
            $query->where('link', 'LIKE', '%'.$request->link.'%');
        }
        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }

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

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param FounderRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(FounderRequest $request) :RedirectResponse
    {
        $founder = Founder::create($request->all());

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

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


    /**
     * Show the form for editing the specified resource.
     *
     * @param Founder $founder
     * @return View
     */
    public function edit(Founder $founder) :View
    {
        $action= route('founders.update', $founder->id);

        $head= __('founders.edit');

        $query = FounderDescription::where('founder_id', $founder->id)
            ->join('languages', 'languages.id', 'founder_descriptions.language_id')
            ->select(['founder_descriptions.*', 'languages.local']);

        $founderDescription= $query->get();

        foreach ($founderDescription as $row) {
            $founder[$row->local]= $row;
        }

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

    /**
     * Update the specified resource in storage.
     *
     * @param FounderRequest $request
     * @param Founder $founder
     * @return RedirectResponse|Redirector
     */
    public function update(FounderRequest $request, Founder $founder) :RedirectResponse
    {
        // Update image and category id if request has it

        $founder->update($request->all());

        // Delete old description
        FounderDescription::where('founder_id', $founder->id)->delete();

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

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

    /**
     * Handle Save form data
     *
     * @param FounderRequest $request
     * @param int $founder_id
     * @return void
     */

    private function saveData(FounderRequest $request, int $founder_id ):void
    {

        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'founder_id'=> $founder_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
            ];
            FounderDescription::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
    {
        $founder = Founder::withTrashed()->find($id);
        if ($founder) {
            if ($founder->deleted_at) {
                $founder->forceDelete();
            } else {
                $founder->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) {
            Founder::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Founder::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
    {
        $founder = Founder::withTrashed()->find($id);

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