<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\Employer;
use App\Models\Staff;
use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use Mail;
use App\Models\EmailTemplate;
use App\Mail\SendMail;
use Illuminate\Support\Str;
use Carbon\Carbon;
use App\Models\PasswordReset;


class StaffController extends Controller
{
    //


    public function staffLogin(Request $request) {

        if (!empty($request->all())) {
            $validator = Validator::make($request->all(), [
                'email_address' => 'required|email',
                'password' => 'required',

            ]);
            $validator->setAttributeNames([
                'email_address' => 'Email',
                'password' => 'Password',
            ]);

             if ($validator->fails()) {
                return Response(['response' => $validator->errors(), 'status' => 500], 200);
            } else {
                $credentials = $request->only('email_address', 'password');
                $user = Staff::where('email_address', $request->email_address)->first();
                
                if($user->status != 1){
                    return Response([
                        'response' => [
                            'success' => false,
                            'status' => 500,
                            'message' => 'Account is not activated. Please contact your employer.'
                        ]
                    ]);
                }
            
                if (Auth::guard('staff')->attempt($request->only('email_address', 'password'))) {
                    
                    
                    $token = $user->createToken('MyApp')->plainTextToken;
                    
                    if(!empty($user->profile_image)){
                        $profileImage = STAFF_PROFILE_PICTURE_DISPLAY_PATH.$user->profile_image;
                    }else{
                        $profileImage = '';
                    }
            
                    $response = [
                        'success' => true,
                        'token' => $token,
                        'user' => $user,
                        'profile_image' => $profileImage,
                        'message' => 'Staff logged in successfully',
                        'status' => 200
                    ];
                    return Response(['response' => $response]);
                } else {
                    $user = Staff::where('email_address', $request->email_address)->first();
                    if (!$user) {
                        $response = [
                            'success' => false,
                            'status' => 500,
                            'message' => 'Email not registered'
                        ];
                    } else {
                        $response = [
                            'success' => false,
                            'status' => 500,
                            'message' => 'Invalid credentials'
                            
                        ];
                    }
                   
                    return Response(['response' => $response]);
                }
            }

        }
    }
    
    public function listing(Request $request) {
        $currentUser = Auth::user()->id;
        $currentUserCheck = Admin::where('id',$currentUser)->first();

        $staffListData = array();
        if(!empty($currentUserCheck)) {

            $staff = Staff::orderBy('id', 'desc')->get();

            foreach($staff as $key => $value) {
                $staffListData[$key]['staff_id'] = $value->id;
                $staffListData[$key]['employer_id'] = $value->employer_id;
                $staffListData[$key]['first_name'] = $value->first_name;
                $staffListData[$key]['last_name'] = $value->last_name;
                $staffListData[$key]['email_address'] = $value->email_address;
                $staffListData[$key]['username'] = $value->username;
                $staffListData[$key]['status'] = $value->status;
                $staffListData[$key]['slug'] = $value->slug;
                $staffListData[$key]['role'] = $value->role;
                $staffListData[$key]['permission'] = $value->permission;
                $staffListData[$key]['created'] = format_date($value->created_at);
            }

        } else {
            $staff = Staff::where('employer_id', $currentUser)->orderBy('id', 'desc')->get();

            foreach($staff as $key => $value) {
                $staffListData[$key]['staff_id'] = $value->id;
                $staffListData[$key]['first_name'] = $value->first_name;
                $staffListData[$key]['last_name'] = $value->last_name;
                $staffListData[$key]['email_address'] = $value->email_address;
                $staffListData[$key]['username'] = $value->username;
                $staffListData[$key]['status'] = $value->status;
                $staffListData[$key]['slug'] = $value->slug;
                $staffListData[$key]['role'] = $value->role;
                $staffListData[$key]['permission'] = $value->permission;
                $staffListData[$key]['created'] = format_date($value->created_at);
            }

            
        }

        if ($request->filled('action')) {
            $idList = $request->idList;
            if ($idList) {
                if ($request->action == 'activate') {
                    Staff::whereIn('id', explode(',', $idList))->update(['status' => '1']);
                } elseif ($request->action == 'deactivate') {
                    Staff::whereIn('id', explode(',', $idList))->update(['status' => '0']);
                } elseif ($request->action == 'delete') {
                    Staff::whereIn('id', explode(',', $idList))->delete();
                   
                }
            }
        }
        return Response(['response' => $staffListData, 'status' => 200], 200);
      
    }


    public function addStaff (Request $request) {
        $currentUser = Auth::user()->id;
        $adminCheck = Admin::where('id', $currentUser)->first();
        $employerCheck = Employer::where('id', $currentUser)->first();
        // echo $currentUser;
        // echo "hi";
        if(!empty($request->all())){
            
        }
        
        
        if(!empty($adminCheck)){
            // echo "hi";
            $input = $request->all();
            if(!empty($input)){
                $validator = Validator::make($request->all(), [
                    'first_name' => 'required|string|max:255',
                    'last_name' => 'required|string|max:255',
                    'email_address' => 'required|string|email|max:255|unique:staffs', // assuming your table name is 'staffs'
                    'username' => 'required|string|max:255|unique:staffs',
                    'password' => 'required|string|min:6',
                    'c_password' => 'required|same:password',
                    // 'role' => 'required|string|max:255',
                    // 'permission' => 'required|string|max:255',
                ]);
            
                if ($validator->fails()) {
                    $msg = $this->validatersErrorString($validator->errors());
                    return Response(['response' => "", 'message' => $msg, 'status' => 500], 200);
                } else{
                    $password = Hash::make($input['password']); // use Hash facade to hash the password
                    $slug = createSlug('staffs', $request->first_name."-".$request->last_name);
                
                    $staff = DB::table('staffs')->insert([
                        'employer_id' => $request->employer_id,
                        'first_name' => $request->first_name,
                        'last_name' => $request->last_name,
                        'email_address' => $request->email_address,
                        'username' => $request->username,
                        'password' => $password,
                        'slug' => $slug,
                        // 'roles' => $request->role,
                        // 'permission' => $request->permission,
            
                        'status' => 1
                    ]);
                    return Response(['response' => "", 'message' => "Staff Added successfully", 'status' => 200], 200);
                }
                
            } else{
                $employersList = Employer::where('status', 1)->get();
                return Response(['response' => $employersList, 'message' => "", 'status' => 200], 200);

            }
            
            
        } else if(!empty($employerCheck)){
            $input = $request->all();
            if(!empty($input)){
                $validator = Validator::make($request->all(), [
                    'first_name' => 'required|string|max:255',
                    'last_name' => 'required|string|max:255',
                    'email_address' => 'required|string|email|max:255|unique:staffs', // assuming your table name is 'staffs'
                    'username' => 'required|string|max:255|unique:staffs',
                    'password' => 'required|string|min:6',
                    'c_password' => 'required|same:password',
                    // 'role' => 'required|string|max:255',
                    // 'permission' => 'required|string|max:255',
                ]);
            
                if ($validator->fails()) {
                    $msg = $this->validatersErrorString($validator->errors());
                    return Response(['response' => "", 'message' => $msg, 'status' => 500], 200);
                } else{
                    $password = Hash::make($input['password']); // use Hash facade to hash the password
                    $slug = createSlug('staffs', $request->first_name."-".$request->last_name);
                
                    $staff = DB::table('staffs')->insert([
                        'employer_id' => $currentUser,
                        'user_type' => 'staff',
                        'first_name' => $request->first_name,
                        'last_name' => $request->last_name,
                        'email_address' => $request->email_address,
                        'username' => $request->username,
                        'password' => $password,
                        'slug' => $slug,
                        // 'roles' => $request->role,
                        // 'permission' => $request->permission,
            
                        'status' => 1
                    ]);
                    
                    return Response(['response' => "", 'message' => "Staff Added successfully", 'status' => 200], 200);

                }
            } 
            
        } else{
            return Response(['response' => "", 'message' => "User not authenticated", 'status' => 200], 200);
        }
        // return Response(['response' => "", 'message' => "Staff Added successfully", 'status' => 200], 200);
    }
    
    public function editStaff(Request $request, $slug) {
        $staff = Staff::where('slug', $slug)->first();
    
        if (!$staff) {
            return Response(['response' => 'Staff not found', 'status' => 404], 404);
        }
    
        $existStaff = [
            'id' => $staff->id,
            'first_name' => $staff->first_name,
            'last_name' => $staff->last_name,
            'email_address' => $staff->email_address,
            'created_at' => format_date($staff->created),
            'status' => $staff->status,
            'username' => $staff->username,
            'slug' => $staff->slug,
        ];
    
        if (!empty($request->all())) {
            $validator = Validator::make($request->all(), [
                'first_name' => 'required',
                'last_name' => 'required',
                'email_address' => 'required|unique:staffs,email_address,',
                'username' => 'required|unique:staffs,username,',
            ]);
    
            $validator->setAttributeNames([
                'first_name' => 'First Name',
                'last_name' => 'Last Name',
                'email_address' => 'Email',
                'username' => 'Username',
            ]);
    
            if ($validator->fails()) {
                return Response(['response' => $validator->errors(), 'status' => 500], 200);
            } else {
                $updateData = [];
                if ($request->has('password') && !empty($request->password) && $request->password === $request->confirm_password) {
                    $updateData['password'] = Hash::make($request->password);
                }
    
                if ($staff->first_name !== $request->first_name) {
                    $updateData['first_name'] = $request->first_name;
                }
    
                if ($staff->last_name !== $request->last_name) {
                    $updateData['last_name'] = $request->last_name;
                }
    
                if ($staff->email_address !== $request->email_address) {
                    $updateData['email_address'] = $request->email_address;
                }
    
                if ($staff->username !== $request->username) {
                    $updateData['username'] = $request->username;
                    $updateData['slug'] = createSlug('staffs', $request->username);
                }
    
                if (!empty($updateData)) {
                    Staff::where('slug', $slug)->update($updateData);
                    return Response(['response' => '', 'message' => 'Staff updated successfully', 'status' => 200], 200);
                } else {
                    return Response(['response' => 'No fields updated', 'status' => 200], 200);
                }
            }
        } else {
            return Response(['response' => $existStaff, 'message' => '', 'status' => 200], 200);
        }
    }
    
    
    public function activateStaff($slug) {
        $staffData = Staff::where('slug', $slug)->first();
        if(!empty($staffData)){
            Staff::where('slug', $slug)->update([
                'status' => 1
            ]);
            return Response(['response' => "", 'message' => 'Staff activated successfully', 'status' => 200], 200);
        }
    }

    public function deactivateStaff($slug) {
        $staffData = Staff::where('slug', $slug)->first();
        if(!empty($staffData)){
            Staff::where('slug', $slug)->update([
                'status' => 0
            ]);
            return Response(['response' => "", 'message' => 'Staff deactivated successfully', 'status' => 200], 200);
        }
    }
    
        public function deleteStaff($slug) {
        $staffData = Staff::where('slug',$slug)->first();

       if(!empty($staffData)){
            Staff::where('slug',$slug)->delete();
            $msgString = 'Staff deleted successfully';
            return Response(['response' => $msgString , 'message' => $msgString ,'status' => 200  ],200);
       }else{

            $msgString = 'No record deleted';
            return Response(['response' => $msgString , 'message' => $msgString ,'status' => 500 ],200);
       }
    }
    
    
    public function forgetPassword(Request $request){
        
        try{
            
            if(empty($request->email)) {
                return Response(['response' => 'Email is required', 'status' => 500], 200);
            }
            $user = Staff::where('email_address', $request->email)->first();
               

              if(!empty($user)) {
                    $token = Str::random(60);
                    //   $domain = URL::to('/');
                    $url = HTTP_PATH_FRONTEND.'/staff/resetpassword/'.$token;
                  
                    $employerName = $user->first_name . ' ' . $user->last_name;
                  
                    $emailTemplate = EmailTemplate::where('id', 7)->first();
                  
                  
                    $toRepArray = ['[!employer_name!]', '[!url!]'];
                    $fromRepArray = [$employerName, $url]; 
                    $emailSubject = str_replace($toRepArray, $fromRepArray, $emailTemplate->subject);
                    $emailBody = str_replace($toRepArray, $fromRepArray, $emailTemplate->template);
                    
                    $logo = $user->company_logo;
                            
                            if(!empty($logo)){
                                $logoPath = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH . $logo;
                            } else{
                                $logoPath = LOGO_PATH;
                            }
                
                    // Send the email
                    try {
                        Mail::to($request->email)->send(new SendMail($emailBody, $emailSubject, $logoPath));
                    } catch (\Exception $e) {
                        return response()->json(['error' => 'Failed to send email.', 'message' => $e->getMessage()], 500);
                    }
                  

                //   $data['url'] = $url;
                //   $data['email'] = $request->email;
                //   $data['title'] = 'Reset Password';
                //   $data['body'] = 'Please click on the link below to reset your password';

                //   Mail::send('forgetpassword', ['data' => $data], function($message) use($data) {
                //       $message->to($data['email']);
                //       $message->subject($data['title']);
                //   });
                
                

                 $datetime = Carbon::now()->format('Y-m-d H:i:s');
                 
                 $passwordReset = PasswordReset::firstOrNew(
                    ['email' => $request->email]
                );
                
                $passwordReset->email = $request->email;
                $passwordReset->token = $token;
                $passwordReset->created_at = $datetime;
                
                $passwordReset->save();

                // echo "hi";
                 return Response(['response' => 'success', 'message'=> 'We have e-mailed your password reset link!', 'status' => 200], 200);

              }
              else{
                  return Response(['response' => 'Email not registered', 'status' => 500], 200);
              }
           

       

        }
        catch(Exception $e) {
            return Response(['response' => $e->getMessage(), 'status' => 500], 200);
        }
        
    }
    
    public function resetPassword(Request $request) 
    {
        try {
            // Validate input
            if (empty($request->token) || empty($request->new_password)) {
                return Response(['response' => 'Token and password are required', 'status' => 500], 200);
            }
    
            // Check if the token exists and is valid
            $passwordReset = PasswordReset::where('token', $request->token)->first();
    
            if (!$passwordReset) {
                return Response(['response' => 'Invalid or expired token', 'status' => 500], 200);
            }
    
            // Verify token expiry (optional)
            // $tokenCreationTime = Carbon::parse($passwordReset->created_at);
            // if ($tokenCreationTime->diffInHours(Carbon::now()) > 24) { // Token expires after 24 hours
            //     return Response(['response' => 'Token has expired', 'status' => 500], 200);
            // }
    
            // Find the user by email
            $user = Staff::where('email_address', $passwordReset->email)->first();
            if (!$user) {
                return Response(['response' => 'User not found', 'status' => 500], 200);
            }
            
            if (Hash::check($request->new_password, $user->password)) {
                return Response([
                    'response' => 'New password cannot be the same as the old password', 
                    'status' => 500
                ], 200);
            } 
    
            // Update the user's password
            $user->password = bcrypt($request->new_password);
            $user->save();
    
            // Delete the password reset token
            $passwordReset->delete();
    
            return Response(['response' => 'success', 'message' => 'Password has been reset successfully!', 'status' => 200], 200);
        } catch (\Exception $e) {
            return Response(['response' => $e->getMessage(), 'status' => 500], 200);
        }
    }

}

