<?php

/*
|--------------------------------------------------------------------------
| OwnStore - Build your own online store
| Author: TakfeDev (MKJUEL)
| All Rights Reserved
|--------------------------------------------------------------------------
*/

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SmsGateway;
use App\Services\Sms\SmsGatewayRegistry;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\Http;

class SmsGatewayController extends Controller
{
    public function index()
    {
        $registryGateways = SmsGatewayRegistry::getSupportedGateways();
        
        foreach ($registryGateways as $gatewayData) {
            SmsGateway::firstOrCreate(
                ['code' => $gatewayData['code']],
                $gatewayData
            );
        }

        return Inertia::render('cp/Settings/SmsGateways/Index', [
            'gateways' => SmsGateway::all()
        ]);
    }

    public function update(Request $request, SmsGateway $gateway)
    {
        $validated = $request->validate([
            'is_active' => 'boolean',
            'credentials' => 'nullable|array',
        ]);

        if ($validated['is_active']) {
            SmsGateway::where('id', '!=', $gateway->id)->update(['is_active' => false]);
        }

        $gateway->update($validated);

        return back()->with('success', $gateway->name . ' configuration updated successfully.');
    }

    // --- NEW: Test SMS Connection Logic ---
    // --- Test SMS Connection Logic ---
    public function testSms(Request $request, SmsGateway $gateway)
    {
        $request->validate([
            'phone_number' => 'required|string',
            'credentials' => 'required|array'
        ]);

        $creds = $request->credentials;
        $phone = $request->phone_number;
        
        // Remove +, -, or spaces from phone number just to be safe for strict APIs
        $cleanPhone = preg_replace('/[^0-9]/', '', $phone); 
        $message = "Test message from " . config('app.name') . ". Your SMS Gateway is working!";

        try {
            if ($gateway->code === 'twilio') {
                $sid = $creds['account_sid'] ?? '';
                $token = $creds['auth_token'] ?? '';
                $from = $creds['from_number'] ?? '';

                if (empty($sid) || empty($token) || empty($from)) {
                    throw new \Exception("Twilio credentials are incomplete.");
                }

                $response = Http::asForm()->withBasicAuth($sid, $token)
                    ->post("https://api.twilio.com/2010-04-01/Accounts/{$sid}/Messages.json", [
                        'To' => $phone, // Twilio likes the '+' sign
                        'From' => $from,
                        'Body' => $message,
                    ]);

                if ($response->failed()) {
                    throw new \Exception($response->json('message') ?? 'Twilio API Error');
                }

            } elseif ($gateway->code === 'vonage') {
                $apiKey = $creds['api_key'] ?? '';
                $apiSecret = $creds['api_secret'] ?? '';
                $from = $creds['from_number'] ?? '';

                if (empty($apiKey) || empty($apiSecret) || empty($from)) {
                    throw new \Exception("Vonage credentials are incomplete.");
                }

                $response = Http::post("https://rest.nexmo.com/sms/json", [
                    'to' => $cleanPhone, // Vonage expects no '+'
                    'from' => $from,
                    'text' => $message,
                    'api_key' => $apiKey,
                    'api_secret' => $apiSecret,
                ]);

                $data = $response->json();
                if (isset($data['messages'][0]['status']) && $data['messages'][0]['status'] != 0) {
                    throw new \Exception($data['messages'][0]['error-text'] ?? 'Vonage API Error');
                }

            } elseif ($gateway->code === 'infobip') {
                // --- NEW INFOBIP LOGIC ---
                $baseUrl = $creds['base_url'] ?? '';
                $apiKey = $creds['api_key'] ?? '';
                $from = $creds['from_sender'] ?? '';

                if (empty($baseUrl) || empty($apiKey) || empty($from)) {
                    throw new \Exception("Infobip credentials are incomplete.");
                }

                // Clean the Base URL just in case the user typed "https://" into the input field
                $baseUrl = rtrim(str_replace(['http://', 'https://'], '', $baseUrl), '/');

                $response = Http::withHeaders([
                    'Authorization' => "App {$apiKey}",
                    'Content-Type'  => 'application/json',
                    'Accept'        => 'application/json',
                ])->post("https://{$baseUrl}/sms/2/text/advanced", [
                    'messages' => [
                        [
                            'destinations' => [['to' => $cleanPhone]],
                            'from' => $from,
                            'text' => $message,
                        ]
                    ]
                ]);

                if ($response->failed()) {
                    $errorData = $response->json();
                    $errorMsg = $errorData['requestError']['serviceException']['text'] ?? 'Infobip API Error';
                    throw new \Exception($errorMsg);
                }
            } else {
                throw new \Exception("Test connection not implemented for this provider.");
            }

            return response()->json(['message' => 'Test SMS sent successfully! Please check your phone.']);

        } catch (\Exception $e) {
            return response()->json(['message' => $e->getMessage()], 500);
        }
    }
}