<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\File;
use App\Models\AppSetting;

class TestPaymentController extends Controller
{
    public function test()
    {
        // 1. Retrieve Current Payment Configuration
        $config = [
            'sslcommerz_store_id' => Config::get('sslcommerz.store.id'),
            'sslcommerz_sandbox_mode' => Config::get('sslcommerz.sandbox'),
            'app_settings_db' => AppSetting::where('key', 'like', '%payment%')
                                    ->orWhere('key', 'like', '%sslcommerz%')
                                    ->orWhere('key', 'like', '%bkash%')
                                    ->orWhere('key', 'like', '%nagad%')
                                    ->orWhere('key', 'like', '%rocket%')
                                    ->get()
                                    ->pluck('value', 'key')
                                    ->toArray()
        ];

        // 2. Simulate Payment Data
        $paymentData = [
            'timestamp' => now()->toDateTimeString(),
            'transaction_id' => 'TEST_' . uniqid(),
            'amount' => 100.00,
            'currency' => 'BDT',
            'gateway' => 'SSLCommerz (Simulation)',
            'status' => 'Pending',
            'configuration_used' => $config
        ];

        // 3. Format Log Entry
        $logEntry = "=================================================\n";
        $logEntry .= "PAYMENT TEST EXECUTION [" . $paymentData['timestamp'] . "]\n";
        $logEntry .= "=================================================\n";
        $logEntry .= "Transaction ID: " . $paymentData['transaction_id'] . "\n";
        $logEntry .= "Amount: " . $paymentData['amount'] . " " . $paymentData['currency'] . "\n";
        $logEntry .= "Gateway: " . $paymentData['gateway'] . "\n";
        $logEntry .= "Status: " . $paymentData['status'] . "\n";
        $logEntry .= "Active Configuration:\n";
        $logEntry .= json_encode($config, JSON_PRETTY_PRINT) . "\n";
        $logEntry .= "-------------------------------------------------\n\n";

        // 4. Write to payment.txt (Append mode)
        $filePath = base_path('payment.txt');
        File::append($filePath, $logEntry);

        return response()->json([
            'message' => 'Payment test executed successfully.',
            'log_file' => $filePath,
            'data_written' => $paymentData
        ]);
    }

    public function testStripe()
    {
        // 1. Retrieve Stripe Configuration
        $settings = AppSetting::where('key', 'payment_key')
                             ->orWhere('key', 'payment_secret')
                             ->orWhere('key', 'payment_gateway')
                             ->get()
                             ->pluck('value', 'key');

        $stripeKey = $settings['payment_key'] ?? null;
        $stripeSecret = $settings['payment_secret'] ?? null;
        $gateway = $settings['payment_gateway'] ?? 'unknown';

        $config = [
            'gateway' => $gateway,
            'public_key' => $stripeKey ? '***' . substr($stripeKey, -4) : 'Not Set',
            'secret_key' => $stripeSecret ? '***' . substr($stripeSecret, -4) : 'Not Set',
            'has_keys' => !empty($stripeKey) && !empty($stripeSecret)
        ];

        // 2. Simulate Stripe Payment Data
        $paymentData = [
            'timestamp' => now()->toDateTimeString(),
            'transaction_id' => 'ch_test_' . uniqid(),
            'amount' => 50.00,
            'currency' => 'USD',
            'gateway' => 'Stripe (Simulation)',
            'status' => 'Succeeded', // Simulated success
            'configuration_used' => $config,
            'simulated_response' => [
                'id' => 'ch_test_' . uniqid(),
                'object' => 'charge',
                'amount' => 5000,
                'amount_captured' => 5000,
                'amount_refunded' => 0,
                'application' => null,
                'application_fee' => null,
                'application_fee_amount' => null,
                'balance_transaction' => 'txn_test_' . uniqid(),
                'billing_details' => [
                    'address' => [
                        'city' => null,
                        'country' => null,
                        'line1' => null,
                        'line2' => null,
                        'postal_code' => null,
                        'state' => null,
                    ],
                    'email' => null,
                    'name' => null,
                    'phone' => null,
                ],
                'captured' => true,
                'created' => time(),
                'currency' => 'usd',
                'customer' => null,
                'description' => 'Test Charge',
                'status' => 'succeeded',
            ]
        ];

        // 3. Format Log Entry
        $logEntry = "=================================================\n";
        $logEntry .= "STRIPE PAYMENT TEST EXECUTION [" . $paymentData['timestamp'] . "]\n";
        $logEntry .= "=================================================\n";
        $logEntry .= "Transaction ID: " . $paymentData['transaction_id'] . "\n";
        $logEntry .= "Amount: " . $paymentData['amount'] . " " . $paymentData['currency'] . "\n";
        $logEntry .= "Gateway: " . $paymentData['gateway'] . "\n";
        $logEntry .= "Status: " . $paymentData['status'] . "\n";
        $logEntry .= "Configuration Status:\n";
        $logEntry .= json_encode($config, JSON_PRETTY_PRINT) . "\n";
        $logEntry .= "Simulated Response Payload:\n";
        $logEntry .= json_encode($paymentData['simulated_response'], JSON_PRETTY_PRINT) . "\n";
        $logEntry .= "-------------------------------------------------\n\n";

        // 4. Write to stripe_payment.txt (Append mode)
        $filePath = base_path('stripe_payment.txt');
        File::append($filePath, $logEntry);

        return response()->json([
            'message' => 'Stripe payment test executed successfully.',
            'log_file' => $filePath,
            'data_written' => $paymentData
        ]);
    }
}
