<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Mail\PasswordResetMail;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;

use Exception;
use Carbon\Carbon;

class ForgetPasswordController extends Controller
{
    public function create_password(Request $request)
    {
        $validated = $request->validate([
            'email'    => 'required|email',
            'password' => 'required|string|min:8|confirmed'
        ]);
        $user = User::where('email', $request->email)->first();
        if (!$user) {
            Log::error('User not found:', ['email' => $request->email]);
            return response()->json([
                'status'  => 'error',
                'message' => 'User not found.',
                'code'    => 404,
            ], 404);
        }
        $user->password = Hash::make($request->password);
        $user->save();
        Log::info('Password reset successfully for:', ['email' => $request->email]);
        return response()->json([
            'status'  => 'success',
            'message' => 'Password has been reset successfully.',
            'code'    => 200,
        ], 200);
    }
    public function forgetpassword(Request $request)
{
    
    try {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation Error',
                'errors' => $validator->errors()
            ], 422);
        }
        do {
            $random_id = 'FT' . rand(100000, 999999);
            $existing_id = User::where('forgot_token', $random_id)->exists();
        } while ($existing_id);
        $email_check = User::where('email', $request->email)->where('role', 'user')->first();
        if ($email_check) {
            $email_check->forgot_token = $random_id;
            $email_check->save();
            Mail::to($request->input('email'))->send(new PasswordResetMail($random_id, $request->email));
            return response()->json([
                'status' => 'success',
                'message' => 'Email sent successfully.',
                'code' => 200
            ], 200);
        } else {
            return response()->json([
                'status' => 'error',
                'message' => 'Invalid Email.',
                'errors' => 'Email Not Found'
            ], 422);
        }
    } catch (Exception $e) {
        return response()->json([
            'status' => 'error',
            'message' => 'Exception occurred.',
            'errors' => $e->getMessage()
        ], 417);
    }
}

}

