<?php

namespace App\Http\Controllers\Admin;

use Exception;
use App\Models\Offer;
use Illuminate\View\View;
use App\Models\OfferDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\OfferRequest;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class OfferController extends Controller
{

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

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

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

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

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

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

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


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

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

        $offer = Offer::create($data);

        if($offer->status == 'true')
        {
            $other = Offer::where('status','true')->where('id','!=',$offer->id)->first();
            if($other)
            {
                $other->update(['status'=>'false']);
            }
        }
        // Insert Description
        $this->saveData($request, $offer->id);

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


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

        $query = OfferDescription::where('offer_id', $offer->id)
            ->join('languages', 'languages.id', 'offer_descriptions.language_id')
            ->select(['offer_descriptions.*', 'languages.local']);

        $offerDescription= $query->get();

        foreach ($offerDescription as $row) {
            $offer[$row->local]= $row;
        }

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

    /**
     * Update the specified resource in storage.
     *
     * @param OfferRequest $request
     * @param Offer $offer
     * @return RedirectResponse|Redirector
     */
    public function update(OfferRequest $request, Offer $offer) :RedirectResponse
    {
        $data = $request->all();

        $offer->update($data);

        if($offer->status == 'true')
        {
            $other = Offer::where('status','true')->where('id','!=',$offer->id)->first();
            if($other)
            {
                $other->update(['status'=>'false']);
            }
        }
        // Delete old description
        OfferDescription::where('offer_id', $offer->id)->delete();


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

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

    /**
     * Handle Save form data
     *
     * @param OfferRequest $request
     * @param int $offer_id
     * @return void
     */

    private function saveData(OfferRequest $request, int $offer_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'offer_id'=> $offer_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
                'second_name'=> $requestData['second_name_'.$lang->local],
                'second_description'=> $requestData['second_description_'.$lang->local],
            ];
            OfferDescription::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
    {
        $offer = Offer::withTrashed()->find($id);
        if ($offer) {
            if ($offer->deleted_at) {
                $offer->forceDelete();
            } else {
                $offer->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) {
            Offer::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Offer::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
    {
        $offer = Offer::withTrashed()->find($id);

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