<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\MobileVerification;
use App\Models\User;
use App\Services\PayamMatni;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class MobileVerificationController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function showVerifyForm()
    {
        if (Auth::user()->mobile_verify) {
            return redirect('/');
        }

        $verification = MobileVerification::where('mobile', Auth::user()->mobile)->first();
        $lastSentAt   = $verification?->last_sent_at;
        $sentCount    = $verification?->sent_count ?? 0;
        $firstSentAt  = $verification?->first_sent_at;

        $cooldown = 0;
        if ($lastSentAt) {
            $elapsed  = max(0, now()->timestamp - $lastSentAt->timestamp);
            $cooldown = max(0, 90 - $elapsed);
        }

        // Resends used in this hour window
        $hourlyUsed = 0;
        if ($firstSentAt && now()->diffInMinutes($firstSentAt) < 60) {
            $hourlyUsed = $sentCount;
        }

        return view('auth.verify-mobile', compact('cooldown', 'hourlyUsed'));
    }

    public function verify(Request $request)
    {
        $request->validate(['code' => 'required|digits:5']);

        $user         = Auth::user();
        $verification = MobileVerification::where('mobile', $user->mobile)->first();

        if (!$verification || now()->isAfter($verification->expires_at)) {
            return back()->withErrors(['code' => 'کد تأیید منقضی شده است. لطفاً کد جدیدی درخواست دهید.']);
        }

        if ($request->code !== $verification->code) {
            return back()->withErrors(['code' => 'کد وارد شده اشتباه است.']);
        }

        User::where('id', $user->id)->update(['mobile_verify' => 1]);
        $verification->delete();

        return redirect('/');
    }

    public function resend(Request $request)
    {
        $user         = Auth::user();
        $verification = MobileVerification::where('mobile', $user->mobile)->first();
        $now          = now();

        if ($verification) {
            if ($verification->last_sent_at && ($now->timestamp - $verification->last_sent_at->timestamp) < 90) {
                return back()->withErrors(['resend' => '۱ دقیقه و نیم صبر کنید.']);
            }

            // Max 5 per hour
            $windowStart = $verification->first_sent_at;
            if ($windowStart && $now->diffInMinutes($windowStart) < 60 && $verification->sent_count >= 5) {
                return back()->withErrors(['resend' => 'حداکثر ۵ بار در ساعت می‌توانید کد دریافت کنید.']);
            }

            // Reset hourly window if an hour has passed
            if (!$windowStart || $now->diffInMinutes($windowStart) >= 60) {
                $verification->first_sent_at = $now;
                $verification->sent_count    = 0;
            }
        } else {
            $verification = new MobileVerification(['mobile' => $user->mobile, 'sent_count' => 0, 'first_sent_at' => $now]);
        }

        $code = str_pad(random_int(10000, 99999), 5, '0', STR_PAD_LEFT);

        $verification->code         = $code;
        $verification->expires_at   = $now->addMinutes(5);
        $verification->last_sent_at = $now;
        $verification->sent_count   += 1;
        $verification->save();

        PayamMatni::sendOtp($user->mobile, $code);

        return back()->with('resent', true);
    }
}
