<?php

namespace App\Http\Controllers\Admin;

/** Ajax Request */

use Exception;
use App\Branch;
use Illuminate\View\View;
use App\BranchDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use Illuminate\Http\RedirectResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\BranchRequest; // for Validation
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 branches.
     *
     * @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 ld', 'branches.id', 'ld.branch_id')
        ->join('languages', 'languages.id', 'ld.language_id')
        ->where('local', LaravelLocalization::getCurrentLocale())
        ->select(['ld.title','ld.address', 'branches.*']);

        if ($request->phone) {
            $query->where('meta->phone', 'LIKE', '%'.$request->phone.'%');
        }

        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->title) {
            $query->where('ld.title', 'LIKE', '%'.$request->title.'%');
        }

        if ($request->address) {
            $query->where('ld.address', 'LIKE', '%'.$request->address.'%');
        }

        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 branch.
     *
     * @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 branch in storage.
     * @param BranchRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(BranchRequest $request) :RedirectResponse
    {
        $data= [
            'meta'=> [
                'latitude'=> $request->latitude ?? null,
                'longitude'=> $request->longitude ?? null,
                'phone'=> $request->phone ?? null,
                'email'=> $request->email ?? null,
            ]
        ];
        // dd($data, $request->all());
        $branch = Branch::create($data);

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

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

    /**
     * Show the form for editing the specified branch.
     *
     * @param  Branch  $branch
     * @return View
     */
    public function edit(Branch $branch) :View
    {
        $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']);


        $personsEmails= [];
        $personsPhones= [];
        if(old("persons_emails", null)) {
            $personsEmails= old("persons_emails", []);
            $personsPhones= old("persons_phones", []);
            array_pop($personsEmails);
            array_pop($personsPhones);
        } else{
            $personsEmails= $branch->persons_emails;
            $personsPhones= $branch->persons_phones;
        }

        $branchDescription= $query->get();

        $personsNames= [];
        $personsDesignations= [];
        foreach ($branchDescription as $row) {
            $branch[$row->local]= $row;
            if(old("persons_names_{$row->local}", null)) {
                $personsNames[$row->local]= old("persons_names_{$row->local}");
                $personsDesignations[$row->local]= old("persons_designations_{$row->local}");
                array_pop($personsNames[$row->local]);
                array_pop($personsDesignations[$row->local]);
            } else{
                $personsNames[$row->local]= $row->persons_names;
                $personsDesignations[$row->local]= $row->persons_designations;
            }
        }
        // dd($personsNames, $personsDesignations, $personsPhones, $personsEmails);
        return view( $this->viewDirectory.'form', compact('branch', 'action', 'personsNames', 'personsDesignations', 'personsPhones', 'personsEmails') );
    }

    /**
     * Update the specified branch in storage.
     * @param BranchRequest $request
     * @param Branch $branch
     * @return RedirectResponse|Redirector
     */
    public function update(BranchRequest $request, Branch $branch) :RedirectResponse
    {
        // 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();

        // save contacts
        $personsEmails = [];
        $personsPhones = [];
        foreach ($requestData['persons_emails'] as $i => $value) {
            if ($requestData['persons_designations_en'][$i]) {
                $personsEmails[] = $value;
                $personsPhones[]= $requestData['persons_phones'][$i] ?? '';
            }
        }
        //
        $data= [
            'meta'=>[
                'latitude'=> $request->latitude ?? null,
                'longitude'=> $request->longitude ?? null,
                'phone'=> $request->phone ?? null,
                'email'=> $request->email ?? null,
                'persons_emails'=> $personsEmails,
                'persons_phones'=> $personsPhones,
            ]
        ];
        Branch::where('id', $branch_id)->update($data);
        // dump($data);

        foreach (languages() as $lang) {
            $data=[
                'branch_id'=> $branch_id,
                'language_id'=> $lang->id,
                'title'=> $requestData['title_'.$lang->local],
                'address'=> $requestData['address_'.$lang->local],
            ];

            // save persons
            $personsNames = [];
            $personsDesignations = [];
            foreach ($requestData['persons_names_'.$lang->local] as $i => $value) {
                if ($value) {
                    $personsNames[] = $value;
                    $personsDesignations[]= $requestData['persons_designations_'.$lang->local][$i] ?? '';
                }
            }
            //
            $data['meta']=[
                'persons_names'=> $personsNames,
                'persons_designations'=> $personsDesignations,
            ];
            // dump($data);
            BranchDescription::create($data);
        }
        // dd($requestData);
     }

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