<?php
// app/Http/Controllers/SmsController.php

namespace App\Http\Controllers;

use App\Services\Fast2SmsService;
use Illuminate\Http\Request;

class Fast2SmsController extends Controller
{
    public function send(Request $request, Fast2SmsService $sms)
    {
        $result = $sms->send($request->phone, $request->message);

        if ($result['success']) {
            return response()->json(['success' => true, 'message' => 'SMS sent']);
        }

        return response()->json(['success' => false, 'error' => $result['error']], 500);
    }

    /**
     * API endpoint to send OTP via HTTP request
     */
    public function sendOtpToIndianNumber(Request $request, Fast2SmsService $sms)
    {
        $result = $this->sendOtpInternalToIndianNumber(
            $request->phone,
            $request->otp,
            $request->app_name,
            $sms
        );

        if ($result['success']) {
            return response()->json(['success' => true, 'message' => 'OTP sent']);
        }

        return response()->json(['success' => false, 'error' => $result['error']], $result['status'] ?? 500);
    }

    /**
     * Internal method to send OTP - can be called from anywhere in the codebase
     * 
     * @param string $phone Phone number (with or without +91)
     * @param string $otp OTP code
     * @param string $app_name Application name
     * @param Fast2SmsService $sms SMS service instance
     * @return array ['success' => bool, 'error' => string|null, 'status' => int|null]
     */
    public function sendOtpInternalToIndianNumber(string $phone, string $otp, string $app_name, Fast2SmsService $sms): array
    {
        // Remove any whitespace
        $phone = preg_replace('/\s+/', '', $phone);
        
        // Remove +91 or 91 prefix if present
        $phone = preg_replace('/^(\+91|91)/', '', $phone);
        
        // Validate Indian phone number (10 digits, starts with 6-9)
        if (!preg_match('/^[6-9]\d{9}$/', $phone)) {
            return [
                'success' => false,
                'error' => 'Invalid Indian phone number',
                'status' => 400
            ];
        }
        
        // Create OTP message
        $message = "Your OTP is: {$otp} from {$app_name}";
        
        // Send OTP
        $result = $sms->send($phone, $message);

        if ($result['success']) {
            return ['success' => true];
        }

        return [
            'success' => false,
            'error' => $result['error'],
            'status' => 500
        ];
    }
}