<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\MemberRequest;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\View\View;
use App\Country;
use App\Subscribe;
use App\City;
use App\Package;
use App\User;
use App\Module;

class MemberController extends Controller
{
    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath= '/dashboard/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) :View
    {
        $query = User::where('role', 'member')
            ->orderBy('name', 'ASC');

        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->hanqr) {
            $query->where('hanqr',$request->hanqr);
        }
        if ($request->package_id) {
            $query->whereIn('id',subscribes($request->package_id));
        }

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

        if ($request->role) {
            $query->where('role', strtolower($request->role) );
        }

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

        $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');
        $countries = Country::cursor();
        $packages = Package::cursor();
        $head = metaFields('members', 'add_new', getCurrentLocale()) ?? __('members.new');


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

    /**
     * Store a newly created resource in storage.
     *
     * @param MemberRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(MemberRequest $request) :RedirectResponse
    {
        $request->merge(['role'=>'member']);
        $request->merge(['password'=>bcrypt($request->password)]);
        $member= User::create($request->all());
        if(!is_null($request->package_id)){
        $sub = Subscribe::create(['user_id'=>$member->id,'package_id'=>$request->package_id,'type'=>'1','paymentId'=>'done']);
        $sub->created_at = $request->date_expire;
        $sub->updated_at = $request->date_expire;
        $sub->save();
        }

       
        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);
        $countries = Country::cursor();
        $packages = Package::cursor();
        $cities = City::where('country_id',$member->country_id)->get();
        $head = metaFields('members', 'edit', getCurrentLocale()) ?? __('members.edit');

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

    /**
     * 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());
        $request->merge(['role'=>'member']);
        $data= $request->all();

        if($data['password']) {
            $data['password']= bcrypt( $data['password'] );
        } else {
            unset($data['password']);
        }
        
        $member->update($data);
        if(!is_null($request->package_id)){
        $sub = Subscribe::create(['user_id'=>$member->id,'package_id'=>$request->package_id,'type'=>'1','paymentId'=>'done']);
        $sub->created_at = $request->date_expire;
        $sub->updated_at = $request->date_expire;
        $sub->save();
        }
        // dd($member->toArray());
        // Insert modules
      
        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)->forceDelete();
        } else {
            User::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
    {
        $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')]);
        }
    }
}
