<?php

namespace App\Http\Controllers\Admin;

use App\Module;
use Exception;
use App\Cobon;
use App\CobonItem;
use App\Product;
use App\Category;
use Illuminate\View\View;
use App\CobonDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use App\Http\Requests\CobonRequest;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class CobonController extends Controller
{

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

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

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

        if ($request->date_to) {
            $query->whereDate('cobons.created_at', '<=', $request->date_to);
        }
         if ($request->discount_type &&  $request->discount_type != 'null') {
            $query->where('discount_type', $request->discount_type);
        }
        
        if ($request->title) {
            $query->where('ad.title', 'LIKE', '%'.$request->title.'%');
        }
        if ($request->code) {
            $query->where('cobons.code', 'LIKE', '%'.$request->code.'%');
        }
       
        

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

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

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param CobonRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(CobonRequest $request) :RedirectResponse
    {
        $request->merge(['code'=>str_random(20)]);
        $cobon = Cobon::create($request->all());


        // Insert Description
        $this->saveData($request, $cobon->id);
        
        $cobon->items()->attach($request->item_id);

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


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

        $query = CobonDescription::where('cobon_id', $cobon->id)
            ->join('languages', 'languages.id', 'cobon_descriptions.language_id')
            ->select(['cobon_descriptions.*', 'languages.local']);

        $cobonDescription= $query->get();

        foreach ($cobonDescription as $row) {
            $cobon[$row->local]= $row;
        }
        $cobonitems = CobonItem::where('cobon_id',$cobon->id);
        $products = Product::cursor();
        $categories = Category::cursor();

        return view( $this->viewDirectory.'form', compact('cobon', 'action','cobonitems','products','categories') );
    }

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

        // Update image and category id if request has it
        $cobon->update($request->all());

        // update image to youtube api thumbnail if request have not image
       

        // Delete old description
        CobonDescription::where('cobon_id', $cobon->id)->delete();

        // delete old photos
    
        $cobon->items()->sync($request->item_id);        

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

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

    /**
     * Handle Save form data
     *
     * @param CobonRequest $request
     * @param int $cobon_id
     * @return void
     */

    private function saveData(CobonRequest $request, int $cobon_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'cobon_id'=> $cobon_id,
                'language_id'=> $lang->id,
                'title'=> $requestData['title_'.$lang->local],
                
            ];
            CobonDescription::create($data);
        }

        if ($request->has('images')){

            foreach ($request->images as $image) {
                $data=[
                    'image'=> $image,
                    'cobon_id'=> $cobon_id,
                ];

                cobonPhoto::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
    {
        $cobon = Cobon::withTrashed()->find($id);
        if ($cobon) {
            if ($cobon->deleted_at) {
                $cobon->forceDelete();
            } else {
                $cobon->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) {
            Cobon::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Cobon::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
    {
        $cobon = Cobon::withTrashed()->find($id);

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