<?php

namespace App\Http\Controllers\Customer;

use App\Http\Controllers\Controller;
use App\Models\AuthorizationToken;
use App\Models\Customer;
use App\Models\CustomerSettings;
use App\Models\Label;
use App\Models\Plan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;

class StaffController extends Controller
{

    public function index(){

        return view('customer.staff.index');
    }

    public function getAll()
    {
        $staffs = Customer::orderBy('created_at', 'desc')->where('owner_id', auth('customer')->user()->id);

        return datatables()->of($staffs)
            ->addColumn('full_name', function ($q) {
                return $q->full_name;
            })
            ->addColumn('role', function ($q) {

                return ucwords(str_replace('_','-', $q->role->name));
            })
            ->addColumn('action', function (Customer $q) {
                return "<a class='btn btn-sm btn-info' data-toggle='tooltip' data-placement='top' title='Edit' href='" . route('customer.staff.edit', [$q]) . "'>"."<i class='fas fa-edit'></i>"."</a>  &nbsp; &nbsp;".
                    '<button class="btn btn-sm btn-primary" data-message="Are you sure you want to delete this staff?"
                                        data-action='.route('customer.staff.destroy',[$q]).'
                                        data-input={"_method":"delete"}
                                        data-toggle="modal" data-target="#modal-confirm" data-toggle="tooltip" data-placement="top" title="Login as">
                                        <i class="fas fa-trash"></i>
                     </button>'.
                    '<button class="btn btn-sm btn-primary ml-2" data-message="You will be logged in as customer?"
                                        data-action='.route('customer.login.as.staff').'
                                        data-input={"id":'.$q->id.'}
                                        data-toggle="modal" data-target="#modal-confirm" data-toggle="tooltip" data-placement="top" title="Login as">
                                        <i class="fas fa-sign-in-alt"></i>
                     </button>';
            })
            ->addColumn('status', function ($q) {
                if ($q->status == 'Active'){
                    return '<span class="pl-2 pr-2 pt-1 pb-1 bg-success" style="border-radius:25px;">'.$q->status.'</span>';
                }else {
                    return '<span class="pl-2 pr-2 pt-1 pb-1 bg-danger" style="border-radius:25px;">'.$q->status.'</span>';
                }
            })
            ->rawColumns(['status','action'])
            ->toJson();
    }

    public function create(){
        $data['roles']=Role::where('customer_id', auth('customer')->user()->id)->get();

        return view('customer.staff.create', $data);
    }


    public function store(Request $request)
    {
        $request->validate([
            'first_name' => 'required',
            'last_name' => 'required',
            'email' => 'required|unique:customers',
            'password' => 'required',
            'status' => 'required',
            'role_id' => 'required'
        ]);

        DB::beginTransaction();
        try{

            $role= Role::where('id', $request->role_id)->first();

            if (!$role){
                return redirect()->back()->withErrors(['error'=>'Invalid Role']);
            }

            $customer=new Customer();
            $customer->first_name=$request->first_name;
            $customer->last_name=$request->last_name;
            $customer->email=$request->email;
            $customer->password=$request->password;
            $customer->status=$request->status;
            $customer->email_verified_at=now();
            $customer->type='staff';
            $customer->role_id=$role->id;
            $customer->owner_id=auth('customer')->user()->id;
            $customer->save();

            $customer->assignRole($role);


            $access_token= $customer->createToken($customer->email)->plainTextToken;
            $preToken = AuthorizationToken::where('customer_id', $customer->id)->first();
            $authorization = isset($preToken) ? $preToken : new AuthorizationToken();
            $authorization->access_token = $access_token;
            $authorization->customer_id=$customer->id;
            $authorization->refresh_token = $access_token;
            $authorization->save();

            $setting= new CustomerSettings();
            $setting->customer_id = $customer->id;
            $setting->name = 'email_notification';
            $setting->value = 'false';
            $setting->save();


            //Assigning plan to customer
            $pre_plan=auth('customer')->user()->currentPlan();

            $plan = Plan::findOrFail($pre_plan->plan_id);
            $customer->plans()->create(['plan_id' => $plan->id,
                'sms_limit' => $plan->sms_limit,
                'contact_limit' => $plan->contact_limit,
                'daily_send_limit' => $plan->daily_send_limit,
                'daily_receive_limit' => $plan->daily_receive_limit,
                'device_limit' => $plan->device_limit,
                'is_current' => 'yes',
                'status' => 'accepted',
                'price' => $plan->price]);

            DB::commit();
            return redirect()->route('customer.staff.index')->with('success', 'Staff successfully created');
        }catch(\Exception $ex){
            DB::rollBack();
            return redirect()->back()->withErrors(['failed'=>$ex->getMessage()]);
        }
    }

    public function edit(Customer $staff)
    {
        $data['customer'] = $staff;
        $data['staff'] = $staff;
        $data['roles']=Role::where('customer_id', auth('customer')->user()->id)->get();
        return view('customer.staff.edit', $data);
    }

    public function update(Customer $staff, Request $request)
    {
        $request->validate([
            'first_name' => 'required',
            'last_name' => 'required',
            'email' => 'required|unique:customers,email,' . $staff->id,
            'status' => 'required'
        ]);

        DB::beginTransaction();
        try{

            $role= Role::where('id', $request->role_id)->first();

            if (!$role){
                return redirect()->back()->withErrors(['error'=>'Invalid Role']);
            }

            $staff->first_name=$request->first_name;
            $staff->last_name=$request->last_name;
            $staff->email=$request->email;
            if($request->password) {
                $staff->password = $request->password;
            }
            $staff->status=$request->status;
            $staff->role_id=$role->id;
            $staff->save();

            DB::commit();
            return redirect()->route('customer.staff.index')->with('success', 'Staff successfully updated');
        }catch(\Exception $ex){
            DB::rollBack();
            return redirect()->back()->withErrors(['failed'=>$ex->getMessage()]);
        }
    }
    public function destroy(Customer $staff){
        $role = Role::where('id', $staff->role_id)->first();
        if($role) {
            $staff->removeRole($role);
        }
        $staff->delete();

        return redirect()->route('customer.staff.index')->with('success', 'Staff successfully deleted');

    }


    public function loginAs(Request $request){
        if(!$request->id) abort(404);
        auth('customer')->loginUsingId($request->id);
        return redirect()->route('customer.dashboard')->with('success',trans('You are now logged as staff'));
    }
}
