<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Traits\EmailTrait;
use App\Http\Controllers\Traits\HelperTrait;
use App\Models\EmpCompanyDetails;
use App\Models\PasswordResetOtp;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class PasswordResetController extends Controller
{

    use EmailTrait ,HelperTrait;
    /**
     * Request OTP for password reset
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function requestOtp(Request $request)
    {
        // Validate request
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
        ]);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }
        $email = $request->email;
        $user = User::where('email', $email)->where('del', '0')->first();
        $customer_id = $this->getSuperAdminId() ?? null;
        if (!$user) {
            $user = EmpCompanyDetails::where('employee_email', $email)->where('del', '0')->first();
            $customer_id = $user->customer_id;
        }
        if (!$user) {
            return $this->message('User with this email does not exist or deleted', 404);
        }
        
        // Delete any existing OTP records for this email before generating new one
        PasswordResetOtp::where('email', $email)->delete();
        
        // Generate OTP
        try {
            $otp = PasswordResetOtp::generateOtp($email);
            // Send OTP email
            $emailParams = [
                'to' => $email,
                'subject' => 'Password Reset OTP',
                'msg' => view('Emails.otp-email', [
                    'email' => $email,
                    'otp_code' => $otp,
                    'subject' => 'Password Reset OTP',
                    'customer_id' => $customer_id
                ])->render()
            ];
            $emailSent = $this->SendInstantEmail($emailParams);
            if (!$emailSent) {
                return $this->message('Failed to send OTP. Please try again later.', 500);
            }
            return $this->success($email,'OTP sent to your email. It will expire in 5 minutes.');
        } catch (\Exception $e) {
            Log::error('Failed to generate or send OTP: ' . $e->getMessage());
            return $this->message('An error occurred. Please try again later.', 500);
        }
    }

    /**
     * Verify OTP
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function verifyOtp(Request $request)
    {
        // Validate request
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'otp' => 'required|string|size:6',
        ]);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }
        $email = $request->email;
        $otp = $request->otp;
        // Verify OTP
        $isValid = PasswordResetOtp::verifyOtp($email, $otp);
        if ($isValid) {
            // Generate a temporary token for password reset
            $token = Str::random(60);
            
            // Update the existing record with token (since we already have the OTP record)
            PasswordResetOtp::where('email', $email)->update([
                'token' => $token, 
                'created_at' => now()
            ]);
            
            return $this->success($token, 'OTP verified successfully');
        } else {
            return $this->message('Invalid or expired OTP', 400);
        }
    }

    /**
     * Reset password
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function resetPassword(Request $request)
    {
        // Validate request
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'token' => 'required|string',
            'password' => 'required|string|min:8',
            'password_confirmation' => 'required|same:password'
        ]);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }
        $email = $request->email;
        $token = $request->token;

        // Verify token from database
        $resetData = PasswordResetOtp::where('email', $email)
            ->where('token', $token)
            ->where('created_at', '>', now()->subHours(1))
            ->first();
        if (!$resetData) {
            return $this->message('Invalid or expired password reset token', 400);
        }
        
        // Update password
        try {
            $user = User::where('email', $email)->first();
            if (!$user) {
                $user = EmpCompanyDetails::where('employee_email', $email)->first();
            }
            if (!$user) {
                return $this->message('User with this email does not exist', 404);
            }

            $user->password = Hash::make($request->password);
            $user->remember_token = '';  // Clear any remember token
            $user->save();

            // Delete the used token/OTP record completely after successful password reset
            $resetData->delete();

            return $this->message('Password reset successfully');
        } catch (\Exception $e) {
            Log::error('Failed to reset password: ' . $e->getMessage());
            return $this->message('An error occurred while resetting password', 500);
        }
    }
    
    /**
     * Optional: Clean up expired OTP records (you can call this periodically)
     */
    public function cleanupExpiredOtps()
    {
        try {
            // Delete OTP records older than 1 hour
            $deletedCount = PasswordResetOtp::where('created_at', '<', now()->subHours(1))->delete();
            Log::info("Cleaned up {$deletedCount} expired OTP records");
            return $this->message("Cleaned up {$deletedCount} expired records");
        } catch (\Exception $e) {
            Log::error('Failed to cleanup expired OTPs: ' . $e->getMessage());
            return $this->message('Failed to cleanup expired records', 500);
        }
    }
}