<?php

namespace App\Http\Controllers\Admin;

use Exception;
use App\Models\Category;
use App\Models\Branch;
use Illuminate\View\View;
use App\Models\BranchDescription;
use Illuminate\Http\Request;
use App\Services\Response\ResponseService;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\BranchRequest;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class BranchController extends Controller
{

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

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

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

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

        if ($request->name) {
            $query->where('ad.name', 'LIKE', '%'.$request->name.'%');
        }
        if ($request->category_id) {
            $query->where('branches.category_id', $request->category_id);
        }


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

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

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

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

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

        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> route('branches.index'),
        ];
        return ResponseService::response($response);
    }


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

        $query = BranchDescription::where('branch_id', $branch->id)
            ->join('languages', 'languages.id', 'branch_descriptions.language_id')
            ->select(['branch_descriptions.*', 'languages.local']);

        $branchDescription= $query->get();
        foreach ($branchDescription as $row) {
            $branch[$row->local]= $row;
        }

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

    /**
     * Update the specified resource in storage.
     *
     * @param BranchRequest $request
     * @param Branch $branch
     * @return RedirectResponse|Redirector
     */
    public function update(BranchRequest $request, Branch $branch)
    {
        // Update image and category id if request has it
        $branch->update($request->all());
        // Delete old description
        BranchDescription::where('branch_id', $branch->id)->delete();
        // Insert new description
        $this->saveData( $request, $branch->id );

        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> route('branches.index'),
        ];
        return ResponseService::response($response);
    }

    /**
     * Handle Save form data
     *
     * @param BranchRequest $request
     * @param int $branch_id
     * @return void
     */

    private function saveData(BranchRequest $request, int $branch_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang)
        {
            $data=[
                'branch_id'=> $branch_id,
                'language_id'=> $lang->id,
                'title'=> $requestData['title_'.$lang->local],
                'address'=> $requestData['address_'.$lang->local],
            ];
            BranchDescription::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
    {
        $branch = Branch::withTrashed()->find($id);
        if ($branch) {
            if ($branch->deleted_at) {
                $branch->forceDelete();
            } else {
                $branch->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) {
            Branch::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Branch::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
    {
        $branch = Branch::withTrashed()->find($id);

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