<?php

namespace App\Http\Controllers\Admin;

use Exception;
use App\Models\Partner;
use Illuminate\View\View;
use App\Models\PartnerDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\PartnerRequest;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

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 pages.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Partner::latest()
            ->join('partner_descriptions AS ad', 'partners.id', 'ad.partner_id')
            ->join('languages', 'languages.id', 'ad.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['ad.*', '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->title) {
            $query->where('ad.name', 'LIKE', '%'.$request->title.'%');
        }

        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();
        }

        $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= __('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= __('partners.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','head','action') );
    }

    /**
     * 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 and category id if request has it

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

        // 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],


            ];
            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 pages 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 pages 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')]);
        }
        return response()->json(['message'=> __('dashboard.saveDone')]);
    }
}
