<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\GeneralSetting;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;

class PasswordOtpController extends Controller
{
    public function showRequestForm()
    {
        if (Auth::check()) {
            return redirect('/dashboard');
        }

        $settings = GeneralSetting::firstOrCreate(['id' => 1], [
            'verify_fee' => 300,
            'bondhonpay_api_key' => '',
            'site_name' => 'TASK EARNING',
            'site_description' => 'TASK EARNING - Build your career smartly.',
            'background_color' => '#ffffff',
            'icon_color' => '#0B5D1E',
            'hover_color' => '#0F7A2E',
            'text_color' => '#0f172a',
            'facebook_link' => null,
            'youtube_link' => null,
            'whatsapp_link' => null,
            'telegram_link' => null,
            'support_general' => null,
            'support_verify' => null,
            'support_withdraw' => null,
            'support_technical' => null,
            'logo' => null,
            'favicon' => '/favicon.png',
            'banner' => null,
            'reselling_banner' => null,
        ]);

        return view('auth.password.forgot_otp', compact('settings'));
    }

    public function sendOtp(Request $request)
    {
        if (Auth::check()) {
            return redirect('/dashboard');
        }

        $request->validate([
            'email' => ['required', 'email', 'max:255'],
        ]);

        $email = strtolower(trim($request->email));

        $last = DB::table('password_reset_otps')
            ->where('email', $email)
            ->orderByDesc('id')
            ->first();

        if ($last && Carbon::parse($last->created_at)->diffInSeconds(now()) < 60) {
            return back()->with('status', 'আমরা ইতোমধ্যে একটি কোড পাঠিয়েছি, একটু পর আবার চেষ্টা করুন।');
        }

        $user = User::where('email', $email)->first();

        if (!$user) {
            return back()->with('status', 'যদি ইমেইলটি সঠিক হয়, একটি কোড পাঠানো হবে।');
        }

        $otp = random_int(100000, 999999);
        $hash = hash('sha256', $otp);

        DB::table('password_reset_otps')->insert([
            'email' => $email,
            'code_hash' => $hash,
            'expires_at' => now()->addMinutes(10),
            'attempts' => 0,
            'used_at' => null,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $subject = 'Your password reset code';

        $html = view('emails.otp_code', [
            'user' => $user,
            'code' => $otp,
            'app' => config('app.name'),
        ])->render();

        try {
            Mail::html($html, function ($message) use ($email, $subject) {
                $message->to($email)->subject($subject);
            });
        } catch (\Throwable $e) {
            return back()->withErrors('ইমেইল পাঠাতে সমস্যা হয়েছে: ' . $e->getMessage());
        }

        return redirect()
            ->route('password.otp.verify.form', ['email' => $email])
            ->with('status', '৬ সংখ্যার OTP আপনার ইমেইলে পাঠানো হয়েছে। ১০ মিনিটের মধ্যে ব্যবহার করুন।');
    }

    public function showVerifyForm(Request $request)
    {
        if (Auth::check()) {
            return redirect('/dashboard');
        }

        $settings = GeneralSetting::firstOrCreate(['id' => 1], [
            'verify_fee' => 300,
            'bondhonpay_api_key' => '',
            'site_name' => 'TASK EARNING',
            'site_description' => 'TASK EARNING - Build your career smartly.',
            'background_color' => '#ffffff',
            'icon_color' => '#0B5D1E',
            'hover_color' => '#0F7A2E',
            'text_color' => '#0f172a',
            'facebook_link' => null,
            'youtube_link' => null,
            'whatsapp_link' => null,
            'telegram_link' => null,
            'support_general' => null,
            'support_verify' => null,
            'support_withdraw' => null,
            'support_technical' => null,
            'logo' => null,
            'favicon' => '/favicon.png',
            'banner' => null,
            'reselling_banner' => null,
        ]);

        $email = $request->query('email');

        return view('auth.password.verify_otp', compact('settings', 'email'));
    }

    public function verifyAndReset(Request $request)
    {
        if (Auth::check()) {
            return redirect('/dashboard');
        }

        $request->validate([
            'email' => ['required', 'email'],
            'otp' => ['required', 'digits:6'],
            'password' => ['required', 'min:6', 'confirmed'],
        ]);

        $email = strtolower(trim($request->email));
        $otp = trim($request->otp);

        return DB::transaction(function () use ($email, $otp, $request) {
            $row = DB::table('password_reset_otps')
                ->where('email', $email)
                ->orderByDesc('id')
                ->lockForUpdate()
                ->first();

            if (!$row) {
                return back()->withErrors('কোডটি পাওয়া যায়নি।')->withInput();
            }

            if ($row->used_at !== null) {
                return back()->withErrors('এই কোডটি ইতোমধ্যে ব্যবহার করা হয়েছে।')->withInput();
            }

            if (now()->greaterThan(Carbon::parse($row->expires_at))) {
                return back()->withErrors('কোডটির মেয়াদ শেষ। নতুন করে কোড নিন।')->withInput();
            }

            if ((int) $row->attempts >= 5) {
                return back()->withErrors('অনেকবার ভুল চেষ্টার কারণে কোডটি লক হয়েছে। নতুন কোড নিন।')->withInput();
            }

            DB::table('password_reset_otps')
                ->where('id', $row->id)
                ->update([
                    'attempts' => (int) $row->attempts + 1,
                    'updated_at' => now(),
                ]);

            $ok = hash_equals($row->code_hash, hash('sha256', $otp));

            if (!$ok) {
                return back()->withErrors('ভুল কোড দেওয়া হয়েছে।')->withInput();
            }

            $user = User::where('email', $email)->first();

            if (!$user) {
                return back()->withErrors('এই ইমেইলে কোনো ইউজার নেই।')->withInput();
            }

            $user->password = Hash::make($request->password);
            $user->save();

            DB::table('password_reset_otps')
                ->where('id', $row->id)
                ->update([
                    'used_at' => now(),
                    'updated_at' => now(),
                ]);

            return redirect()
                ->route('login.form')
                ->with('success', 'পাসওয়ার্ড পরিবর্তন হয়েছে। লগইন করুন।');
        });
    }
}
