<?php

namespace App\Http\Controllers\Admin;

use App\Branch;
use Exception;
use App\Language;
use App\BranchDescription;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Requests\BranchRequest;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
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 branches.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Branch::latest()
            ->join('branch_descriptions AS pd', 'branches.id', 'pd.branch_id')
            ->join('languages', 'languages.id', 'pd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['pd.name', '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('pd.name', 'LIKE', '%'.$request->name.'%');
        }

        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) :RedirectResponse
    {
        $branch = Branch::create($request->all());
        // Insert Description
        $this->saveData( $request, $branch->id );

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


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

        $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','head', 'action') );
    }

    /**
     * Update the specified resource in storage.
     *
     * @param BranchRequest $request
     * @param Branch $branch
     * @return RedirectResponse|Redirector
     */
    public function update(BranchRequest $request, Branch $branch) :RedirectResponse
    {
        // Update image if request has it
        $branch->update(['image' => $request->image??null]);

        // Delete old description
        BranchDescription::where('branch_id', $branch->id)->delete();

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

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

    /**
     * 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();
        $languages= Language::where('status', 1)->cursor();

        foreach ($languages as $lang) {
            $data=[
                'branch_id'=> $branch_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$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 branches 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 branches by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function restoreAll(Request $request) :JsonResponse
    {
        $branches = Branch::whereIn('id', $request->ids)->onlyTrashed();
        if ($branches){
            $branches->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}