<?php

namespace App\Http\Controllers\Client;

use App\Models\Client;
use App\Models\Company;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\ClientProfile;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class ClientController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:قائمة المستخدمين', ['only' => ['index']]);
        $this->middleware('permission:إضافة مستخدم', ['only' => ['create','store']]);
        $this->middleware('permission:تعديل مستخدم', ['only' => ['edit','update']]);
        $this->middleware('permission:حذف مستخدم', ['only' => ['destroy']]);

    }

    public function index(Request $request)
    {        
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $auth_id = Auth::user()->id;
        $users = Client::where('company_id',$company_id)->where('founder',0)->where('id','!=',$auth_id)->get();
        return view('client.clients.index', compact('users'));
    }

    public function create()
    {
        $company_id = Auth::user()->company_id;
        $user = Auth::user();
        $company = Company::FindOrFail($company_id);
        $roles = Role::where('company_id',$company_id)->get();
        $type_name = $user->company->subscription->type->type_name;
        if ($type_name == "تجربة"){
            $users_count = "غير محدود";
        }
        else{
            $users_count = $user->company->subscription->type->package->users_count;
        }
        $company_users_count = $company->clients->count();
        if ($users_count == "غير محدود") {
            return view('client.clients.create', compact('roles','company','company_id'));
        }
        else{
            if($users_count > $company_users_count){
                return view('client.clients.create', compact('roles','company','company_id'));
            }
            else{
                return redirect()->route('client.home')->with('error','باقتك الحالية لا تسمح بالمزيد من المستخدمين');
            }
        }
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|unique:clients',
            'password' => 'required|same:confirm-password|min:8',
            'role_name' => 'required'
        ]);
        $company_id = Auth::user()->company_id;
        $company = Company::FindOrFail($company_id);
        $type_name = $company->subscription->type->type_name;
        if ($type_name == "تجربة"){
            $users_count = "غير محدود";
        }
        else{
            $users_count = $company->subscription->type->package->users_count;
        }
        $company_users_count = $company->suppliers->count();
        if ($users_count == "غير محدود") {
            
        }
        else{
            if(!$users_count > $company_users_count){

                return response()->json(['message' => 'باقتك الحالية لا تسمح بالمزيد من المستخدمين','status'=>false]);
            }
        }


        $input = $request->all();
        $input['password'] = Hash::make($input['password']);
        $input['company_id'] = $company_id;
        $client = Client::create($input);
        $client->email_verified_at = now();
        $client->save();

        $role = Role::where('company_id',$company_id)->where('name',$request->input('role_name'))->first();
        $client->assignRole($role->id);

        $profile = ClientProfile::create([
            'phone_number' => '',
            'city_name' => '',
            'age' => '',
            'gender' => '',
            'profile_pic' => 'app-assets/images/user.png',
            'client_id' => $client->id,
            'company_id' => $company_id
        ]);

        return response()->json(['message'=>"تم إضافة المستخدم بنجاح ",'status'=>true]);

    }

    public function edit($id)
    {
        
        $company_id = Auth::user()->company_id;
        $client = Client::where('company_id',$company_id)->findOrFail($id);
        $roles = Role::where('company_id',$company_id)->get();
        $clientRole = $client->roles->pluck('id')->all();
        return view('client.clients.edit', compact('client', 'roles', 'clientRole'));
    }

    public function update(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|unique:clients,email,'.$request->id,
            // 'password' => 'required|same:confirm-password|min:8',
            'password'=>'nullable|min:8|same:confirm-password',
            'role_name' => 'required'
        ]);
        $company_id = Auth::user()->company_id;
        $client = Client::findOrFail($request->id);
        $input = $request->all();
        if (!empty($input['password'])) {
            $input['password'] = Hash::make($input['password']);
        } else {
            $input['password'] = $client->password;
        }
        $client->update($input);            
        $client->syncRoles([]);
        
        $role = Role::where('company_id',$company_id)->where('name',$request->input('role_name'))->first();
        $client->assignRole($role->id);
        return response()->json(['message'=>"تم تعديل المستخدم بنجاح ",'status'=>true]);


    }

    public function destroy(Request $request)
    {
        $client = Client::findOrFail($request->id);
        $client->delete();
        return response()->json(['message'=>"تم حذف المستخدم بنجاح ",'status'=>true]);        
    }
}
