<?php

namespace App\Services;

use App\Models\OtpCode;
use App\Models\Setting;
use App\Models\SmsTemplate;
use App\Models\User;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class PasswordResetService
{
    protected Client $client;

    public function __construct()
    {
        $this->client = new Client([
            'base_uri' => 'https://www.fast2sms.com',
            'timeout' => 10,
        ]);
    }

    public function generateOtp(): string
    {
        return str_pad((string) random_int(100000, 999999), 6, '0', STR_PAD_LEFT);
    }

    public function sendResetOtp(string $mobile, string $otp): bool
    {
        try {
            // Get SMS settings from database
            $apiKey = Setting::get('sms_fast2sms_api_key');
            
            if (!$apiKey) {
                Log::error('Fast2SMS API key not configured. Please configure it in Admin > Settings > SMS Configuration');
                return false;
            }

            $sender = Setting::get('sms_fast2sms_sender', 'KIYO');
            $route = Setting::get('sms_fast2sms_route', 'q');
            $template = SmsTemplate::where('identifier', 'login_otp')->where('is_active', true)->first();
            $templateId = $template?->template_id;
            $message = $template?->body ?? "{$otp} is your password reset code for Kiyo E-commerce.";
            $message = str_replace('[[otp]]', $otp, $message);

            $params = [
                'route' => $route,
                'sender_id' => $sender,
                'message' => $message,
                'language' => 'english',
                'flash' => 0,
                'numbers' => $this->normalizeIndianMobile($mobile),
            ];

            if ($templateId) {
                $params['variables_values'] = $otp;
                $params['template_id'] = $templateId;
            }

            $response = $this->client->post('/dev/bulkV2', [
                'headers' => [
                    'authorization' => $apiKey,
                ],
                'form_params' => $params,
            ]);

            $result = json_decode($response->getBody()->getContents(), true);

            Log::info('Fast2SMS Password Reset OTP sent', [
                'mobile' => $mobile,
                'response' => $result,
            ]);

            return $result['return'] ?? false;
        } catch (\Exception $e) {
            Log::error('Fast2SMS Password Reset OTP failed', [
                'mobile' => $mobile,
                'error' => $e->getMessage(),
            ]);

            return false;
        }
    }

    public function storeResetOtp(string $mobile, string $otp): void
    {
        // Delete old OTPs for this mobile
        OtpCode::where('mobile', $mobile)
            ->where('type', 'password_reset')
            ->delete();

        OtpCode::create([
            'mobile' => $mobile,
            'otp_hash' => Hash::make($otp),
            'expires_at' => now()->addMinutes(10), // 10 minutes for password reset
            'type' => 'password_reset',
        ]);
    }

    public function verifyResetOtp(string $mobile, string $otp): bool
    {
        $otpCode = OtpCode::where('mobile', $mobile)
            ->where('type', 'password_reset')
            ->where('expires_at', '>', now())
            ->latest()
            ->first();

        if (!$otpCode) {
            return false;
        }

        if (Hash::check($otp, $otpCode->otp_hash)) {
            $otpCode->delete();
            return true;
        }

        return false;
    }

    public function resetPassword(string $mobile, string $password): bool
    {
        $user = User::where('mobile', $mobile)->first();

        if (!$user) {
            return false;
        }

        $user->update([
            'password' => Hash::make($password),
        ]);

        return true;
    }

    protected function normalizeIndianMobile(string $mobile): string
    {
        // Remove +91 prefix if present (expecting +91 prefix from validation)
        $mobile = preg_replace('/^\+91/', '', $mobile);

        return $mobile;
    }
}

