<?php

namespace App\Http\Controllers\API;

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

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

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

            $employer = Employer::orderBy('id', 'desc')->get();

            foreach($employer as $key => $value) {
                $employerListData[$key]['id'] = $value->id;
                $employerListData[$key]['user_type'] = $value->user_type;
                $employerListData[$key]['first_name'] = $value->first_name;
                $employerListData[$key]['last_name'] = $value->last_name;
                $employerListData[$key]['email_address'] = $value->email_address;
                $employerListData[$key]['username'] = $value->username;
                $employerListData[$key]['contact'] = $value->contact;
                $employerListData[$key]['state'] = $value->state;
                $employerListData[$key]['city'] = $value->city;
                $employerListData[$key]['status'] = $value->status;
                $employerListData[$key]['slug'] = $value->slug;
                // $employerListData[$key]['role'] = $value->role;
                // $employerListData[$key]['permission'] = $value->permission;
                $employerListData[$key]['created'] = format_date($value->created_at);
            }

        } else {
            $employer = Employer::where('id', $currentUser)->orderBy('id', 'desc')->get();

            foreach($employer as $key => $value) {
                $employerListData[$key]['id'] = $value->id;
                $employerListData[$key]['user_type'] = $value->user_type;
                $employerListData[$key]['first_name'] = $value->first_name;
                $employerListData[$key]['last_name'] = $value->last_name;
                $employerListData[$key]['email_address'] = $value->email_address;
                $employerListData[$key]['username'] = $value->username;
                $employerListData[$key]['contact'] = $value->contact;
                $employerListData[$key]['state'] = $value->state;
                $employerListData[$key]['city'] = $value->city;
                $employerListData[$key]['status'] = $value->status;
                $employerListData[$key]['slug'] = $value->slug;
                // $employerListData[$key]['role'] = $value->role;
                // $employerListData[$key]['permission'] = $value->permission;
                $employerListData[$key]['created'] = format_date($value->created_at);
            }

            
        }
        
        return Response(['response' => $employerListData, 'status' => 200], 200);
    }

    //     public function employerRegister(Request $request) {
        
    //     $validator = Validator::make($request->all(), [
    //         'first_name' => 'required|string|max:255',
    //         'last_name' => 'required|string|max:255',
    //         'company_name' => 'required|string|max:255',
    //         'email' => 'required|string',
    //         'password' => 'required|string|min:6',
    //         'confirm_password' => 'required|same:password',
    //     ]);

    //     if ($validator->fails()) {
    //         $msg = $this->validatersErrorString($validator->errors());
    //         return Response(['response' => "", 'message' => $msg, 'status' => 500], 200);
    //     } else {

    //         Employer::insert([
    //             'first_name' => $request->first_name,
    //             'last_name' => $request->last_name,
    //             'email_address' => $request->email,
    //             'company_name' => $request->company_name,
    //             'username' => $request->username,
    //             'password' => bcrypt($request->password),
    //             'status' => 1,
    //             'slug' => createSlug('employers', $request->first_name.' '.$request->last_name),

    //         ]);
    
    //         return Response(['response' => "", 'message' => 'Employer registered successfully', 'status' => 200], 200);
    //     }
        
    // }
    
     public function employerAdd(Request $request) 
    {
        $validator = Validator::make($request->all(), [
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'username' => 'required|string|max:255',
            'company_name' => 'required|string|max:255',
            'email_address' => 'required|string|email|max:255|unique:employers,email_address',
            'password' => 'required|string|min:6',
            'confirm_password' => 'required|same:password',
            // 'profile_image' => 'required',
            // 'company_logo' => 'required',
        ]);
    
        if ($validator->fails()) {
            $msg = $this->validatersErrorString($validator->errors());
            return response(['response' => "", 'message' => $msg, 'status' => 500], 200);
        }
    
        try {
            
            // if($request->profile_image){
                    
                    
            //         // Extract the base64-encoded image data from the request
            //         $file = explode(";base64,", $request->profile_image);
            //         $image_type_pieces = explode("image/", $file[0]);
            //         $image_type = $image_type_pieces[1]; // Get the image type (e.g., png, jpeg)
                    
            //         // Generate a unique filename for the logo
            //         $originalName = 'logo_' . time() . '.' . $image_type;  // Using the image type to set the file extension
                    
            //         // Decode the base64 string into binary data
            //         $decoded_string = base64_decode($file[1]);
                    
            //         // Create a temporary file to store the decoded image
            //         $tempFile = tmpfile();
            //         fwrite($tempFile, $decoded_string);
            //         fseek($tempFile, 0);
                    
            //         // Use Laravel's storage to store the file in the public disk
            //         $filePath = Storage::disk('public')->put('uploads/employer/profile_picture/' . $originalName, $tempFile);
                    
            //         // Get the filename after it's stored (use str_replace to clean up the path if needed)
            //         $fileName = str_replace('uploads/employer/profile_picture/', '', $filePath);

            //     }else{
            //         return Response(['response' => '' , 'message'=> 'Profile picture required', 'status'=>500],200);
            //     }
            
            do {
                $employerCode = strtoupper(Str::random(10)); // e.g., "A9F6D2ZP1X"
            } while (Employer::where('employer_code', $employerCode)->exists());
    
            // Insert employer data into the database
            Employer::create([
                'first_name' => $request->first_name,
                'last_name' => $request->last_name,
                'username' => $request->username,
                'email_address' => $request->email_address,
                'company_name' => $request->company_name,
                'password' => bcrypt($request->password),
                'user_type' => 'employer',
                'status' => 1,
                'slug' => createSlug('employers', $request->first_name . ' ' . $request->last_name),
                'employer_code' => $employerCode,
                // 'profile_image' => $originalName,
                // 'company_logo' => $companyLogoName,
            ]);
    
            return response(['response' => "", 'message' => 'Employer registered successfully', 'status' => 200], 200);
        } catch (\Exception $e) {
            return response(['response' => "", 'message' => 'An error occurred: ' . $e->getMessage(), 'status' => 500], 200);
        }
    }

    public function employerLogin(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 {
                
                // $pp='Williamgrey1!';
    
                //  Employer::where('id',25)->update([
                //                 'password'=> Hash::make($pp),
                //             ]);
                            
                // return Response(['response' => '', 'message' => 'Employer logged in successfully', 'status' => 200],200);
                
                $credentials = $request->only('email_address', 'password');
            
                if (Auth::guard('employer')->attempt($request->only('email_address', 'password'))) {
                    $user = Employer::where('email_address', $request->email_address)->first();
                    $token = $user->createToken('MyApp')->plainTextToken;
                    
                    if(!empty($user->profile_image)){
                        $profileImage = EMPLOYER_PROFILE_PICTURE_DISPLAY_PATH.$user->profile_image;
                    } else{
                        $profileImage = '';
                    }
                    
                    if(!empty($user->company_logo)){
                        $websiteLogo = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH . $user->company_logo;
                    } else{
                        $websiteLogo = '';
                    }
            
                    $response = [
                        'success' => true,
                        'token' => $token,
                        'user' => $user,
                        'profile_image' => $profileImage,
                        'userType' => "Employer",
                        'website_logo' => $websiteLogo,
                    ];
                    return Response(['response' => $response, 'message' => 'Employer logged in successfully', 'status' => 200],200);
                } else {
                    $user = Employer::where('email_address', $request->email_address)->first();
                    if (!$user) {
                        $response = [
                            'success' => false,
                            'message' => 'Email not registered'
                        ];
                    } else {
                        $response = [
                            'success' => false,
                            'message' => 'Invalid credentials'
                        ];
                    }
                   
                    return Response(['response' => $response, 'status' => 500],200);
                }
            }

        }
    }
    
    
    public function employer_changeWebsiteLogo(Request $request) {
        $employerId = Auth::user()->id;
        $oldLogo = Employer::where('id',$employerId )->select('company_logo')->first();

        if(!empty($request->all())){

            if($request->company_logo){
                $file = explode( ";base64,", $request->logo);
                $image_type_pieces = explode( "image/", $file[0] );
                $image_type = $image_type_pieces[1];
                $originalName = 'logo.png';
                $decoded_string = base64_decode($file[1]);
                file_put_contents(EMPLOYER_COMPANY_LOGO_UPLOAD_PATH.$originalName, $decoded_string);

               

                $employer = Employer::find($employerId);
                $employer->company_logo = $originalName;
                $employer->save();
                
                // $data['logo_path'] = LOGO_PATH;
                // $data['logo'] = '';
            }else{
                return Response(['response' => '' , 'message'=> 'logo required', 'status'=>500],200);
            }
            
        }else{
            if(!empty($oldLogo)){
                $data['logo_path'] = EMPLOYER_COMPANY_LOGO_UPLOAD_PATH.$oldLogo;
                $data['logo'] = '';
            }
            else{
                $data['logo_path'] = '';
                $data['logo'] = '';
            }
        }

        return Response(['response'=>$data , 'message'=>'success' , 'status' => 200 ],200);
    }
    
    public function getEmployerCheck(Request $request) {
        $employerId = $request->employer_code;
    
        // Check if the employer exists
        $employer = Employer::where('employer_code', $employerId)
            ->select('first_name', 'last_name', 'company_logo')
            ->first();
    
        if ($employer) {
            // Add full URL for website_logo
            $employer->company_logo = EMPLOYER_COMPANY_LOGO_DISPLAY_PATH . $employer->company_logo;
    
            return response()->json([
                'response' => $employer,
                'message' => 'Employer Present',
                'status' => 200
            ], 200);
        } else {
            return response()->json([
                'response' => 'Employer not present',
                'message' => 'Employer not present',
                'status' => 500
            ], 200);
        }
    }

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

              if(!empty($user)) {
                    $token = Str::random(60);
                    //   $domain = URL::to('/');
                    $url = HTTP_PATH_FRONTEND.'/employer/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 = Employer::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);
        }
    }

    public function getEmployerNotification(Request $request){
        $employerId = $request->employer_id;
        
        $notifications = Notification::where('user_id', $employerId)->where('mark_as_read', '0')->orderBy('id', 'desc')->get();
        
        if(!empty($notifications)){
            return Response(['response' => $notifications, 'message' => '', 'status' => 200], 200);
        } else{
            return Response(['response' => '', 'message' => 'No Notifications', 'status' => 500], 200);
        }
        
    }

}
