<?php

namespace App\Http\Controllers\SelfPaced\Dashboard;

use App\Http\Requests\SelfPaced\StorePaystackConfigRequest;
use App\Http\Controllers\Controller;
use App\Models\SelfPaced\PaystackConfig;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;

/**
 * PaystackConfigController
 *
 * Manages Paystack payment gateway configuration.
 * Middleware: permission:manage self-paced paystack
 *
 * Requirements: 1.1, 1.2, 10.3, 10.4, 10.5, 10.7
 */
class PaystackConfigController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('permission:manage self-paced paystack');
    }

    /**
     * Show Paystack configuration form
     *
     * @return View
     */
    public function show(): View
    {
        $config = PaystackConfig::getActive();

        return view('self-paced.dashboard.paystack.config', [
            'config' => $config,
            'maskedPublicKey' => $config ? $config->getMaskedPublicKey() : null,
            'maskedSecretKey' => $config ? $config->getMaskedSecretKey() : null,
        ]);
    }

    /**
     * Update Paystack configuration
     *
     * @param StorePaystackConfigRequest $request
     * @return RedirectResponse
     */
    public function update(StorePaystackConfigRequest $request): RedirectResponse
    {
        $config = PaystackConfig::getActive();

        if (!$config) {
            $config = new PaystackConfig();
        }

        $config->update([
            'public_key' => $request->input('public_key'),
            'secret_key' => $request->input('secret_key'),
            'webhook_secret' => $request->input('webhook_secret'),
            'currencies' => $request->input('currencies', ['KES']),
            'is_active' => true,
            'updated_by' => auth()->id(),
        ]);

        return redirect()->back()->with('success', 'Paystack configuration updated successfully');
    }
}
