<?php

use App\Models\PaymentGateway;
use Illuminate\Support\Facades\Crypt;
use Livewire\Component;

return new class extends Component {
    public $gateways;
    public $editingGateway = null;
    public $form = [
        'is_active' => false,
        'is_test_mode' => true,
        'credentials' => []
    ];
    public $showModal = false;


    public function mount() {
        $this->loadGateways();
    }

    public function loadGateways() {
        $this->gateways = PaymentGateway::orderBy('sort_order')->get();
    }

    public function edit($id) {
        $gateway = PaymentGateway::findOrFail($id);
        $this->editingGateway = $gateway;
        
        $this->form = [
            'is_active' => $gateway->is_active,
            'is_test_mode' => $gateway->is_test_mode,
            'credentials' => $gateway->credentials ?? []
        ];
        
        foreach ($this->form['credentials'] as $key => $value) {
            try {
                $this->form['credentials'][$key] = Crypt::decryptString($value);
            } catch (\Exception $e) { }
        }
        $this->showModal = true;
    }

    public function save() {
        // Encrypt sensitive keys before saving
        $securedCredentials = [];
        foreach ($this->form['credentials'] as $key => $value) {
            $securedCredentials[$key] = Crypt::encryptString($value);
        }

        $this->editingGateway->update([
            'is_active' => $this->form['is_active'],
            'is_test_mode' => $this->form['is_test_mode'],
            'credentials' => $securedCredentials
        ]);

        $this->editingGateway = null;
        $this->loadGateways();
        $this->dispatch('toast', text: 'Gateway settings updated.', type: 'success');
    }

    protected function view($data = [])
    {
        return app('view')->file('C:\laragon\www\ecommerce\storage\framework/views/livewire/views/ba7fef62.blade.php', $data);
    }
}; 