<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\MemberRequest;
use App\Models\Country;
use App\Models\City;
use Exception;
use App\Exports\MemberExport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\View\View;

use App\Models\User;

class MemberController extends Controller
{
    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath = '/admin/members';
    /** View folder */
    private $viewDirectory = 'admin.members.';

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

    /**
     * return data of the members.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request)
    {
        $query = User::whereIn('role', ['user','seller'])
            ->latest();

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

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

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

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

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

        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }
        
        if($request->export)
        {
            $members= $query->cursor();
            return Excel::download(new MemberExport($members), 'Members.xlsx');
        }

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

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param MemberRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(MemberRequest $request) :RedirectResponse
    {
        $data = $request->all();
        
        if(is_null($request->photo))
        {
            $data['photo'] = 'user.png';
        }
        $data['password'] = bcrypt($request->password);

        $member= User::create($data);

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  User  $member
     * @return View
     */
    public function edit(User $member): View
    {
        $action= route('members.update', $member->id);
        $head = metaFields('members', 'edit', getCurrentLocale()) ?? __('members.edit');
        $countries = Country::withDescription()->cursor();
        $cities = City::withDescription()->where('country_id',$member->country_id)->cursor();

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

    /**
     * Update the specified resource in storage.
     *
     * @param  MemberRequest  $request
     * @param  User  $member
     * @return RedirectResponse|Redirector
     */
    public function update(MemberRequest $request, User $member) :RedirectResponse
    {
        // dd($request->all());
        $data= $request->all();

        if(is_null($request->photo))
        {
            $data['photo'] = 'user.png';
        }
        if($data['password']) {
            $data['password']= bcrypt( $data['password'] );
        } else {
            unset($data['password']);
        }
        $member->update($data);

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

    /**
     * Remove the specified resource from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :JsonResponse
    {
        $member = User::withTrashed()->find($id);
        if ($member) {
            if ($member->deleted_at) {
                $member->forceDelete();
            } else {
                $member->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) {
            User::onlyTrashed()->whereIn('id', $ids)->where('role', '!=', 'admin')->forceDelete();
        } else {
            User::whereIn('id', $ids)->where('role', '!=', 'admin')->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
    {
        $member = User::withTrashed()->find($id);

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