<?php

namespace App\Http\Controllers;

use App\DataTables\EmployersDataTable;
use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\User;
use App\Models\SubAccount;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Spatie\Permission\Models\Role;

class EmployerController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(EmployersDataTable $dataTable)
    {
    
        return $dataTable->render('employers.index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        if(!$this->canAddEmployer())return redirect()->route('employers.index')->with('error', __('You have exceeded your staff '));
        return view('employers.create');
    }

    function canAddEmployer(){
        $user = auth()->user();
        $employers_number=$user->office!=''?$user->office->employers_number:0;
        if($user->countEmployers()>=$employers_number){
            return false;
        }
        return true;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        if(!$this->canAddEmployer())return redirect()->route('employers.index')->with('error', __('You have exceeded your staff '));
        $data=$this->validate($request,[
            'name'=>'required|string|max:191',
            'password'=>'required',
            'email'=>'required|email|unique:users',
            'image' => 'image',
            'locale' => 'nullable|string',
            'phone' => 'string|nullable',
            'roles_id'=>'nullable|array',
            'admin_id' => 'nullable|numeric'
        ]);
        $data['status']=$request->status?true:false;
        $data['admin_id']=isset($data)?auth()->id():$data['admin_id'];
        $admin=User::find($request->admin_id);
        
        
    
    
        $data['office_id']=$admin->office_id;

        if($request->image){
            $data['image'] = time().'.'.$request->image->extension();  
            $request->image->move(public_path('uploads'), $data['image']);
        }
     
        $data['password']=bcrypt($request->password);
        $data['api_token'] =  Str::random(60);
        if(Auth::user()->isSuperAdmin()){
            $data['is_admin'] = true;
        }
        $user = User::create($data);
        if($request->roles_id){
            foreach ($request->roles_id as  $value) {
                $role=Role::find($value);
                $user->assignRole($role->name);
            }
        }   
        if(!$user->office_id){
 
            Account::create([
                'number' => time(),
                'balance' => 0,
                'currency_code'=>$request->currency_code??config('currency.default'),
                'user_id' => $user->id,
                'state' => true
            ]);
        }
       
           if($request->booking_commission){
              $office_id=User::find($request->admin_id)->office_id;
               $account_id=Account::where('office_id',$office_id)->first();
         $sub_account=   SubAccount::create([
            'number' => time(),
            'balance' => 0,
              'account_id'=>$account_id->id,
            'currency_code'=>$request->currency_code??config('currency.default'),
            'office_id' => $office_id,
            'state' => true
          ]);
          $user->sub_account_id=$sub_account->id;
          $user->save();
        }



        return redirect()->route('employers.index')->with('success', __('Task was successful'));

    }

    /**
     * Display the specified resource.
     *
     * @param  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function show(User $user)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $user= User::find($id);
        return view('employers.edit',['user'=>$user]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\User  $user
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $user= User::find($id);
        $data=$this->validate($request,[
            'name'=>'required|string|max:191',
            'email'=>'required|email|unique:users,email,'.$id,
            'phone'=>'nullable|string',
            'image' => 'image',
        ]);
        $data['status']=$request->status?true:false;
        if($request->image){
            $data['image'] = time().'.'.$request->image->extension();  
            $request->image->move(public_path('uploads'), $data['image']);
            $this->destroyImage($user->image);
        }
        if($request->password){
            $data['password']=bcrypt($request->password);
        }
        $user->update($data);


        return redirect()->route('employers.index')->with('success', __('Task was successful'));  
    }

    /**
     * Remove the specified resource from storage.
     *

     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $user= User::findOrFail($id);
        @unlink(public_path().'/'.$user->image);
        return $user->delete();
    }

}
