<?php

namespace App\Http\Controllers\Admin;

use Exception;
use App\Suplier;
use Illuminate\View\View;
use App\SuplierDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use App\Http\Requests\SuplierRequest;
use Illuminate\Http\RedirectResponse;

class SuplierController extends Controller
{

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

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

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

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

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

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param SuplierRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(SuplierRequest $request) :RedirectResponse
    {
        $data = $request->all();
        $suplier = Suplier::create($data);
        $this->saveData($request, $suplier->id);

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


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

        $query = SuplierDescription::where('suplier_id', $suplier->id)
            ->join('languages', 'languages.id', 'suplier_descriptions.language_id')
            ->select(['suplier_descriptions.*', 'languages.local']);

        $suplierDescription= $query->get();

        foreach ($suplierDescription as $row) {
            $suplier[$row->local]= $row;
        }

        $local = getCurrentLocale();

        return view( $this->viewDirectory.'form', get_defined_vars() );
    }

    /**
     * Update the specified resource in storage.
     *
     * @param SuplierRequest $request
     * @param Suplier $suplier
     * @return RedirectResponse|Redirector
     */
    public function update(SuplierRequest $request, Suplier $suplier) :RedirectResponse
    {

        $data = $request->all();
        $suplier->update($data);
        SuplierDescription::where('suplier_id', $suplier->id)->delete();
        $this->saveData( $request, $suplier->id );
        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Handle Save form data
     *
     * @param SuplierRequest $request
     * @param int $suplier_id
     * @return void
     */

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

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