<?php

namespace App\Http\Controllers\Admin;

use App\Models\Brand;
use App\Http\Requests\Admin\BrandRequest;
use Exception;
use App\Models\BrandDescription;
use App\Services\Response\ResponseService;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;

class BrandController extends Controller
{

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

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

    /**
     * return data of the courses.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Brand::join('brand_descriptions AS cd', 'brands.id', 'cd.brand_id')
            ->where('cd.language_id', currentLanguage()->id)
            ->select(['cd.name', 'brands.*']);

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

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

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


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

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

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

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

    /**
     * Store a newly created resource in storage.
     * @param BrandRequest $request
     * @return JsonResponse
     */
    public function store(BrandRequest $request)
    {
        $brand = Brand::create($request->all());
        $this->saveData( $request, $brand->id );
        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> $this->redirectSuccessPath,
        ];
        return ResponseService::response($response);
    }


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

        $query = BrandDescription::where('brand_id', $brand->id)
            ->join('languages', 'languages.id', 'brand_descriptions.language_id')
            ->select(['brand_descriptions.*', 'languages.local']);

        $brandDescription= $query->get();

        foreach ($brandDescription as $row) {
            $brand[$row->local]= $row;
        }

        $local = getCurrentLocale();

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

    /**
     * Update the specified resource in storage.
     * @param BrandRequest $request
     * @param Brand $brand
     * @return JsonResponse
     */
    public function update(BrandRequest $request, Brand $brand)
    {
        $brand->update($request->all());
        // Delete old description
        BrandDescription::where('brand_id', $brand->id)->delete();
        $this->saveData( $request, $brand->id );
        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> $this->redirectSuccessPath,
        ];
        return ResponseService::response($response);
    }


    /**
     * Handle Save form data
     *
     * @param BrandRequest $request
     * @param int $brand_id
     * @return void
     */

    private function saveData(BrandRequest $request, int $brand_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'name'=> $requestData['name_'.$lang->local],
                'brand_id'=> $brand_id,
                'language_id'=> $lang->id,
            ];
            BrandDescription::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
    {
        $brand = Brand::withTrashed()->find($id);
        if ($brand) {
            if ($brand->deleted_at) {
                $brand->forceDelete();
            } else {
                $brand->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

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

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

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