<?php

namespace App\Http\Controllers\Admin;

use App\Partner;
use Exception;
use App\Language;
use App\PartnerDescription;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Requests\PartnerRequest;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;

class PartnerController extends Controller
{

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

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

    /**
     * return data of the partner.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Partner::latest()
//            ->join('partner_descriptions AS pd', 'partners.id', 'pd.partner_id')
//            ->join('languages', 'languages.id', 'pd.language_id')
//            ->where('local', getCurrentLocale())
            ->select(['partners.*']);

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

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

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

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


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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('partners.store');
        $head = metaFields('partners', 'add_new', getCurrentLocale()) ?? __('partners.new');

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

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

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


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

//        $query = PartnerDescription::where('partner_id', $partner->id)
//            ->join('languages', 'languages.id', 'partner_descriptions.language_id')
//            ->select(['partner_descriptions.*', 'languages.local']);
//
//        $partnerDescription= $query->get();
//
//        foreach ($partnerDescription as $row) {
//            $partner[$row->local]= $row;
//        }

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

    /**
     * Update the specified resource in storage.
     *
     * @param PartnerRequest $request
     * @param Partner $partner
     * @return RedirectResponse|Redirector
     */
    public function update(PartnerRequest $request, Partner $partner) :RedirectResponse
    {
        // Update image if request has it
        $partner->update(['image' => $request->image??null]);

        // Delete old description
//        PartnerDescription::where('partner_id', $partner->id)->delete();

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

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

    /**
     * Handle Save form data
     *
     * @param PartnerRequest $request
     * @param int $partner_id
     * @return void
     */

    private function saveData(PartnerRequest $request, int $partner_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'partner_id'=> $partner_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
                'slug'=> $requestData['slug_'.$lang->local],
                'keywords'=> $requestData['keywords_'.$lang->local],
                'meta_description'=> $requestData['meta_description_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
            ];
            PartnerDescription::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
    {
        $partner = Partner::withTrashed()->find($id);
        if ($partner) {
            if ($partner->deleted_at) {
                $partner->forceDelete();
            } else {
                $partner->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

    /**
     * Remove several partner by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        if ($request->force) {
            Partner::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Partner::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
    {
        $partner = Partner::withTrashed()->find($id);

        if ($partner){
            $partner->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);
    }

    /**
     * Restore several partner by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function restoreAll(Request $request) :JsonResponse
    {
        $partner = Partner::whereIn('id', $request->ids)->onlyTrashed();
        if ($partner){
            $partner->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}
