<?php

namespace App\Http\Controllers;

use DB;
use App\Models\User;
use App\Models\EmpTeam;
use App\Models\TeamHistory;
use Illuminate\Http\Request;
use App\Models\EmpTeamsMember;
use App\Models\EmpCompanyDetails;
use App\Models\EmpPersonalDetails;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use App\Models\EmpTeamsMemberNotCompelete;

class EmpTeamController extends Controller
{

    public function index(Request $request)
    {
        $userTable = $this->getUserTable();
        $query = EmpTeam::query();
        if ($userTable === "customer") {
            $query->where('del', '0')->where('customer_id', auth()->id())
                ->where('workspace_id', auth()->user()->current_workspace_id);
        }
        if ($userTable === "emp") {
          
            $query->where('del', '0')->where('customer_id', auth()->user()->customer_id) // Assuming customer_id links employee to projects
                ->where('workspace_id', auth()->user()->workspace_id);
        }
      
        $emp_teams =  $query->get();
        return $this->success($emp_teams, 'Employee Teams Get Successfully');   
    }

    public function get_supervisors(){

        $user = auth()->user();
        

        $userTable = $this->getUserTable();

        if ($userTable === "customer") {

            $supervisor  =  EmpCompanyDetails::with('empPersonalDetails')
                            ->where('customer_id', $user->id)
                            ->where('workspace_id', $user->current_workspace_id)               
                            ->where('access_role','SPV') // Supervisor
                            ->orderBy('id', 'DESC')
                            ->get();
        }
        if ($userTable === "emp") {
            
            $supervisor  =  EmpCompanyDetails::with('empPersonalDetails')
                            ->where('customer_id', auth()->user()->customer_id)
                            ->where('workspace_id', auth()->user()->workspace_id)               
                            ->where('access_role','SPV') // Supervisor
                            ->orderBy('id', 'DESC')
                            ->get();
        }

        $data['supervisor'] = $supervisor;
 
        return $this->success($data, 'Supervisor List  Get Successfully');     
    }

    public function store(Request $request)
    {
        $user = auth()->user();
        $validator = Validator::make($request->all(), [
            'title' => 'required',
            'supervisor' => 'nullable',
            'description' => 'required'
        ]);
        
        if ($validator->fails()) {

            $error = $validator->errors()->first();
            return $this->error($error,422);
        
        } else {       
           $validatedData =  $validator->validated();

           $userTable = $this->getUserTable();
           $auth_id =0;
           $workspace_id = 0;
           if ($userTable === "customer") {
               $auth_id = Auth::user()->id;
               $workspace_id = Auth::user()->current_workspace_id;  
               $authPersonalDetails = User::where('id', Auth::user()->id)->first(); 
           }
           if ($userTable === "emp") {
               $auth_id = auth()->user()->customer_id;
               $workspace_id = auth()->user()->workspace_id;
               $authPersonalDetails = EmpPersonalDetails::where('emp_id', Auth::user()->id)->first();  
           }
           $validatedData['created_by'] = Auth::user()->id;
           $validatedData['customer_id'] = $auth_id;
           $validatedData['workspace_id'] = $workspace_id;
           EmpTeam::insert($validatedData);

           $emp_teams =  EmpTeam::where('del','0')
                                    ->where('customer_id', $auth_id)
                                    ->where('workspace_id', $workspace_id)
                                  ->orderBy('id', 'DESC')->get();

           $data['emp_teams'] = $emp_teams;

           return $this->success($data, 'Employee Team Saved Successfully');
        }        

    }
    public function show($id)
    {
        //
    }
    public function team_edit(Request $request)
    {
        $id=$request->id;
        $userTable = $this->getUserTable();
        $emp_teams = EmpTeam::find($id);
        if (
            $userTable == "customer" && ($emp_teams->workspace_id != auth()->user()->current_workspace_id || $emp_teams->customer_id != auth()->user()->id)
        ) {
            return $this->message('You do not have access to this Employee Teams', 403);
        }

        if ($userTable == "emp" && ($emp_teams->customer_id != auth()->user()->customer_id || $emp_teams->workspace_id != auth()->user()->workspace_id)) {
            return $this->message('You do not have access to this Employee Teams', 403);
        }
        return $this->success($emp_teams, 'Get Employee Teams Details Successfully');

    }

    public function team_update(Request $request)
    {
        $user = auth()->user();
        $validator = Validator::make($request->all(), [
            'id' => 'required',
            'title' => 'required',
            'supervisor' => 'nullable',
            'description' => 'required'
        ]);
        
        if ($validator->fails()) {

            $error = $validator->errors()->first();

            return $this->error($error,422);

        } else {
            $id=$request->id;
            $validatedData =  $validator->validated();
             $emp_teams = EmpTeam::where('id', $id)->first();
            $userTable = $this->getUserTable();
        
            if ($userTable == "customer" && ($emp_teams->workspace_id != auth()->user()->current_workspace_id || $emp_teams->customer_id != auth()->user()->id)
            ) {
                return $this->message('You do not have access to this emp_teams', 403);
            }

            if ($userTable == "emp" && ($emp_teams->customer_id != auth()->user()->customer_id || $emp_teams->workspace_id != auth()->user()->workspace_id)) {
                return $this->message('You do not have access to this emp_teams', 403);
            }
            if (!$emp_teams) {
                return $this->notFound('emp_teams Not Found', 404);
            }
            $emp_teams->update($validatedData);
     
            if($userTable == "customer"){
                $data['emp_teams'] = EmpTeam::where('customer_id', $user->id)
                ->where('workspace_id', $user->current_workspace_id)
                ->where('del', '0')
                ->get();
            }
            elseif($userTable == "emp"){
                $data['emp_teams'] = EmpTeam::where('customer_id',auth()->user()->customer_id)
                ->where('workspace_id', auth()->user()->workspace_id)
                ->where('del', '0')
                ->get();
            }

            return $this->success($data, 'Employee Team Updated Successfully');   

        }        

    }

    public function team_delete(Request $request)
    {
        $id=$request->id;
        $userTable = $this->getUserTable();
        $EmpTeam = EmpTeam::find($id);
    
        if ($userTable == "customer" && ($EmpTeam->workspace_id != auth()->user()->current_workspace_id || $EmpTeam->customer_id != auth()->user()->id)) {
            return $this->message('You do not have access to this Employee Teams', 403);
        }

        if ($userTable == "emp" && ($EmpTeam->customer_id != auth()->user()->customer_id || $EmpTeam->workspace_id != auth()->user()->workspace_id)) {
            return $this->message('You do not have access to this Employee Teams', 403);
        }
        $EmpTeam->del='1';
        $EmpTeam->save();
         
        $user = auth()->user();
        if($userTable == "customer"){
                $data['emp_teams'] = EmpTeam::where('customer_id', $user->id)
                ->where('workspace_id', $user->current_workspace_id)
                ->where('del', '0')
                ->get();
            }
            elseif($userTable == "emp"){
                $data['emp_teams'] = EmpTeam::where('customer_id',auth()->user()->customer_id)
                ->where('workspace_id', auth()->user()->workspace_id)
                ->where('del', '0')
                ->get();
            }

        return $this->success($data, 'Employee Team Deleted Successfully');
    }

    public function addRemoveTeamMember(Request $request)
    {


        $authPersonalDetails  = EmpPersonalDetails::where('emp_id',Auth::user()->id)->first();
        $empPersonalDetails   = EmpPersonalDetails::where('emp_id',$request->emp_id)->first();
        $teamDetails   = EmpTeam::where('id',$request->team_id)->first();
           $userTable = $this->getUserTable();
           $auth_id =0;
           $workspace_id = 0;
           if ($userTable === "customer") {
               $auth_id = Auth::user()->id;
               $workspace_id = Auth::user()->current_workspace_id;  
               $authPersonalDetails = User::where('id', Auth::user()->id)->first(); 
           }
           if ($userTable === "emp") {
               $auth_id = auth()->user()->customer_id;
               $workspace_id = auth()->user()->workspace_id;
               $authPersonalDetails = EmpPersonalDetails::where('emp_id', Auth::user()->id)->first();  
           }
         
        if( EmpTeamsMember::where(['team_id' => $request->team_id, 'emp_id' => $request->emp_id])->count() > 0 )    
        {

            EmpTeamsMember::where([
                'team_id' => $request->team_id,
                'emp_id' => $request->emp_id,
                ])->delete();

            if($request->applied == 1){
                if(Auth::check() )
            {
                if ($userTable === "customer") {

                    $description = "<a href='".url('/')."/customer-profile/".$auth_id."' style='text-transform: capitalize;' role='button' class='primary text-decoration-none'> {$authPersonalDetails->name} </a>deleted the memeber: '{$empPersonalDetails->first_name} {$empPersonalDetails->middle_name} {$empPersonalDetails->last_name}'  from  '{$teamDetails->title}' team.";
       
                }
                if ($userTable === "emp") {
                         $description = "<a href='".url('/')."/user-profile/".$auth_id."' style='text-transform: capitalize;' role='button' class='primary text-decoration-none'> {$authPersonalDetails->first_name} {$authPersonalDetails->middle_name} {$authPersonalDetails->last_name}</a> deleted the memeber: '{$empPersonalDetails->first_name} {$empPersonalDetails->middle_name} {$empPersonalDetails->last_name}'  from  '{$teamDetails->title}' team.";
                }
            }
               
            }
        }
        else
        {
            EmpTeamsMember::insert([
                'team_id' => $request->team_id,
                'emp_id' => $request->emp_id,
                'applied' => $request->applied
            ]);
            if($request->applied == 1){  
                if(Auth::check() )
                {
                    if ($userTable === "customer") {
    
                        $description = "<a href='".url('/')."/customer-profile/".$auth_id."' style='text-transform: capitalize;' role='button' class='primary text-decoration-none'> {$authPersonalDetails->name} </a>Add the memeber: '{$empPersonalDetails->first_name} {$empPersonalDetails->middle_name} {$empPersonalDetails->last_name}'  from  '{$teamDetails->title}' team.";
           
                    }
                    if ($userTable === "emp") {
                             $description = "<a href='".url('/')."/user-profile/".$auth_id."' style='text-transform: capitalize;' role='button' class='primary text-decoration-none'> {$authPersonalDetails->first_name} {$authPersonalDetails->middle_name} {$authPersonalDetails->last_name}</a> Add the memeber: '{$empPersonalDetails->first_name} {$empPersonalDetails->middle_name} {$empPersonalDetails->last_name}'  from  '{$teamDetails->title}' team.";
                    }
                }
                
            }
        }

        if($request->applied == 1){
            
          
            TeamHistory::create([
                'team_id' => $request->team_id,
                'emp_id' => $request->emp_id,
                'customer_id'=>$auth_id,
                'workspace_id'=> $workspace_id,
                'description' => $description
            ]);

        }
        return $this->message('Team Memeber Updated Successfully');
    }

    public function GetTeamMember(Request $request)
    {
        $userTable = $this->getUserTable();
        $emp_teams = EmpTeam::find($request->team_id);
        if ($userTable == "customer" && ($emp_teams->workspace_id != auth()->user()->current_workspace_id || $emp_teams->customer_id != auth()->user()->id)) {
            return $this->message('You do not have access to this Employee Teams', 403);
        }

        if ($userTable == "emp" && ($emp_teams->customer_id != auth()->user()->customer_id || $emp_teams->workspace_id != auth()->user()->workspace_id)) {
            return $this->message('You do not have access to this Employee Teams', 403);
        }
        $teams_member =   EmpTeamsMember::where('team_id' , $request->team_id)->where('applied' , '1')->orderBy('id', 'DESC')->get();
        $emp_team =   EmpTeam::with('teamSupervisor')->where('id', $request->team_id)->orderBy('id', 'DESC')->first();

        $data['teams_member'] = $teams_member;
        $data['emp_team'] = $emp_team;

        return $this->success($data, 'Get Team Memeber Successfully');
    }

    public function GetTeamHistory(Request $request)
    {
        $id=$request->team_id;
        $userTable = $this->getUserTable();
        $auth_id =0;
        $workspace_id = 0;
        if ($userTable === "customer") {
            $auth_id = Auth::user()->id;
            $workspace_id = Auth::user()->current_workspace_id;  
            $authPersonalDetails = User::where('id', Auth::user()->id)->first(); 
        }
        if ($userTable === "emp") {
            $auth_id = auth()->user()->customer_id;
            $workspace_id = auth()->user()->workspace_id;
            $authPersonalDetails = EmpPersonalDetails::where('emp_id', Auth::user()->id)->first();  
        }
        $team_history =   TeamHistory::where('customer_id',$auth_id)->where('workspace_id',$workspace_id)->where('team_id',$id)->orderBy('id', 'DESC')->get();
        return $this->success($team_history, 'Get Team History Successfully');
    }

    

}
