<?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\PaymentGateway;
use App\Models\Currency;
use App\Models\Country;
use App\Services\Payments\GatewayRegistry; // <-- Import the Registry
use Illuminate\Http\Request;
use Inertia\Inertia;

class PaymentGatewayController extends Controller
{
    public function index()
    {
        // 1. AUTO-SYNC REGISTRY WITH DATABASE
        // This ensures if a seeder wasn't run, or if we added a new gateway in a code update, 
        // it automatically appears in the database without overwriting existing configured keys.
        $registryGateways = GatewayRegistry::getSupportedGateways();
        
        foreach ($registryGateways as $gatewayData) {
            PaymentGateway::firstOrCreate(
                ['code' => $gatewayData['code']], // Check if this gateway exists by code
                $gatewayData // If it doesn't exist, insert the default registry data
            );
        }

        // 2. Return data to the view
        return Inertia::render('cp/Settings/Gateways/Index', [
            'gateways' => PaymentGateway::all(),
            'currencies' => Currency::where('is_active', true)->get(['code', 'name', 'symbol']),
            'countries' => Country::where('is_active', true)->orderBy('name')->get(['iso2', 'name'])
        ]);
    }

    public function update(Request $request, PaymentGateway $gateway)
    {
        $validated = $request->validate([
            'is_active' => 'boolean',
            'mode' => 'in:sandbox,live',
            'is_global' => 'boolean',
            'allowed_countries' => 'nullable|array',
            'supported_currencies' => 'nullable|array',
            'test_credentials' => 'nullable|array',
            'live_credentials' => 'nullable|array',
        ]);

        // Ensure allowed_countries is an empty array if null
        if (!isset($validated['allowed_countries'])) {
            $validated['allowed_countries'] = [];
        }

        $gateway->update($validated);

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