<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use Illuminate\Http\Request;
use Razorpay\Api\Api;

class RazorpaySettingsController extends Controller
{
    public function index()
    {
        $razorpayKey = Setting::get('razorpay_key', '');
        $razorpaySecret = Setting::get('razorpay_secret', '');

        return view('admin.razorpay-settings.index', compact('razorpayKey', 'razorpaySecret'));
    }

    public function update(Request $request)
    {
        $validated = $request->validate([
            'razorpay_key' => 'required|string|max:255',
            'razorpay_secret' => 'required|string|max:255',
        ]);

        // Validate Razorpay key format
        if (!str_starts_with($validated['razorpay_key'], 'rzp_test_') && !str_starts_with($validated['razorpay_key'], 'rzp_live_')) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Invalid Razorpay Key format. Key should start with rzp_test_ or rzp_live_');
        }

        // Test the credentials by trying to create a test order
        try {
            $api = new Api($validated['razorpay_key'], $validated['razorpay_secret']);
            // Try to create a test order with minimal amount to verify credentials
            $testOrder = $api->order->create([
                'receipt' => 'TEST_' . time(),
                'amount' => 100, // 1 rupee in paise
                'currency' => 'INR',
            ]);
        } catch (\Razorpay\Api\Errors\BadRequestError $e) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Invalid Razorpay credentials. Authentication failed. Error: ' . $e->getMessage() . '. Please check your API Key and Secret.');
        } catch (\Razorpay\Api\Errors\ServerError $e) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Razorpay server error. Please try again later.');
        } catch (\Exception $e) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Failed to verify Razorpay credentials: ' . $e->getMessage() . '. Please check your API Key and Secret.');
        }

        Setting::set('razorpay_key', $validated['razorpay_key'], 'encrypted', 'Razorpay API Key');
        Setting::set('razorpay_secret', $validated['razorpay_secret'], 'encrypted', 'Razorpay API Secret');

        return redirect()->route('admin.razorpay-settings.index')
            ->with('success', 'Razorpay settings updated and verified successfully.');
    }
}
