<?php

namespace App\Http\Controllers\Admin\TopUp;

use App\Http\Controllers\Controller;
use App\Models\TripaySettings;
use App\Models\TripayTransaction;
use App\Services\Api\API;
use App\Traits\RefreshesSettingsCache;
use Illuminate\Http\Request;
use Inertia\Inertia;

class TripayController extends Controller
{
    use RefreshesSettingsCache;

    protected API $api;

    public function __construct(API $api)
    {
        $this->api = $api;
    }

    private function getCallbackUrls(): array
    {
        $baseUrl = rtrim(config('app.url'), '/');

        return [
            'return_url' => $baseUrl.'/topup/tripay/return',
            'callback_url' => $baseUrl.'/topup/tripay/callback',
        ];
    }

    public function index()
    {
        $settings = TripaySettings::first();
        $transactions = TripayTransaction::with('user')
            ->latest()
            ->paginate(50)
            ->withQueryString();

        $callbackUrls = $this->getCallbackUrls();

        return Inertia::render('admin/topup/tripay/index', [
            'settings' => $settings ? [
                'api_key' => $settings->api_key,
                'private_key' => $settings->private_key,
                'merchant_code' => $settings->merchant_code,
                'payment_method' => $settings->payment_method ?? 'BRIVA',
                'production_mode' => $settings->production_mode,
                'gold_rate' => $settings->gold_rate,
                'min_amount' => $settings->min_amount,
                'max_amount' => $settings->max_amount,
                'is_active' => $settings->is_active,
                'broadcast_enabled' => $settings->broadcast_enabled ?? true,
                'broadcast_message' => $settings->broadcast_message,
                'broadcast_channel' => $settings->broadcast_channel ?? 9,
                'discord_enabled' => $settings->discord_enabled ?? false,
                'discord_webhook_url' => $settings->discord_webhook_url,
                'discord_message' => $settings->discord_message,
                'discord_mention_everyone' => $settings->discord_mention_everyone ?? false,
            ] : null,
            'transactions' => $transactions->items(),
            'paymentMethods' => $this->getPaymentMethods(),
            'callbackUrls' => $callbackUrls,
        ]);
    }

    public function updateSettings(Request $request)
    {
        $validated = $request->validate([
            'api_key' => 'required|string',
            'private_key' => 'required|string',
            'merchant_code' => 'required|string',
            'payment_method' => 'required|string',
            'production_mode' => 'required|boolean',
            'gold_rate' => 'required|integer|min:1',
            'min_amount' => 'required|integer|min:1000',
            'max_amount' => 'required|integer|min:10000',
            'is_active' => 'required|boolean',
            'broadcast_enabled' => 'nullable|boolean',
            'broadcast_message' => 'nullable|string|max:500',
            'broadcast_channel' => 'nullable|integer|min:1|max:99',
            'discord_enabled' => 'nullable|boolean',
            'discord_webhook_url' => 'nullable|url|max:500',
            'discord_message' => 'nullable|string|max:1000',
            'discord_mention_everyone' => 'nullable|boolean',
        ]);

        TripaySettings::updateOrCreate(
            ['id' => TripaySettings::first()?->id ?? 1],
            $validated
        );

        $this->refreshSettingsCache();

        return back()->with('success', 'Tripay settings updated successfully.');
    }

    public function syncTransaction(Request $request, $id)
    {
        $transaction = TripayTransaction::find($id);

        if (! $transaction) {
            return back()->with('error', 'Transaction not found.');
        }

        $settings = TripaySettings::first();

        if (! $settings || ! $settings->isConfigured()) {
            return back()->with('error', 'Tripay settings not configured.');
        }

        try {
            // Get transaction detail from Tripay API
            $apiUrl = $settings->merchant_api_url.'/transaction/detail';

            $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_FRESH_CONNECT => true,
                CURLOPT_URL => $apiUrl.'?reference='.$transaction->reference,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HEADER => false,
                CURLOPT_HTTPHEADER => [
                    'Authorization: Bearer '.$settings->api_key,
                ],
                CURLOPT_FAILONERROR => false,
                CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
            ]);

            $response = curl_exec($curl);
            $error = curl_error($curl);
            curl_close($curl);

            if ($error) {
                return back()->with('error', 'Failed to connect to Tripay API: '.$error);
            }

            $result = json_decode($response, true);

            if (isset($result['success']) && $result['success'] && isset($result['data'])) {
                $data = $result['data'];
                $newStatus = strtolower($data['status']);
                $oldStatus = $transaction->status;

                // Update transaction status
                $transaction->updateStatus($newStatus, $result);

                // If status changed to paid, process payment
                if ($newStatus === 'paid' && $oldStatus !== 'paid') {
                    $transaction->processPayment();

                    // Send broadcast notification if enabled
                    if ($settings && ($settings->broadcast_enabled ?? true)) {
                        try {
                            $user = $transaction->user;
                            if ($user) {
                                $message = $settings->getBroadcastMessage($user, $transaction);
                                $channel = $settings->broadcast_channel ?? 9;
                                $this->api->WorldChat(0, $message, $channel);
                            }
                        } catch (\Exception $e) {
                            \Log::error('Failed to send Tripay donation broadcast on sync', [
                                'error' => $e->getMessage(),
                            ]);
                        }
                    }

                    // Send Discord notification if enabled
                    if ($settings && ($settings->discord_enabled ?? false)) {
                        try {
                            $user = $transaction->user;
                            if ($user) {
                                $settings->sendDiscordNotification($user, $transaction);
                            }
                        } catch (\Exception $e) {
                            \Log::error('Failed to send Tripay Discord notification on sync', [
                                'error' => $e->getMessage(),
                            ]);
                        }
                    }

                    return back()->with('success', 'Transaction synced and gold added to user.');
                }

                return back()->with('success', 'Transaction synced successfully.');
            }

            return back()->with('error', 'Failed to sync transaction status.');
        } catch (\Exception $e) {
            return back()->with('error', 'Error syncing transaction: '.$e->getMessage());
        }
    }

    private function getPaymentMethods()
    {
        // Based on Tripay API documentation: https://tripay.co.id/developer?tab=merchant-payment-channel
        return [
            'va' => [
                'name' => 'Virtual Account',
                'channels' => [
                    'MYBVA' => 'Maybank Virtual Account',
                    'PERMATAVA' => 'Permata Virtual Account',
                    'BNIVA' => 'BNI Virtual Account',
                    'BRIVA' => 'BRI Virtual Account',
                    'MANDIRIVA' => 'Mandiri Virtual Account',
                    'BCAVA' => 'BCA Virtual Account',
                    'SMSVA' => 'Sinarmas Virtual Account',
                    'MUAMALATVA' => 'Muamalat Virtual Account',
                    'CIMBVA' => 'CIMB Niaga Virtual Account',
                    'SAMPOERNAVA' => 'Sahabat Sampoerna Virtual Account',
                    'BSIVA' => 'BSI Virtual Account',
                    'OCBCVA' => 'OCBC NISP Virtual Account',
                    'DANAMONVA' => 'Danamon Virtual Account',
                ],
            ],
            'convenience_store' => [
                'name' => 'Convenience Store',
                'channels' => [
                    'ALFAMART' => 'Alfamart',
                    'INDOMARET' => 'Indomaret',
                ],
            ],
            'ewallet' => [
                'name' => 'E-Wallet',
                'channels' => [
                    'OVO' => 'OVO',
                    'DANA' => 'DANA',
                    'SHOPEEPAY' => 'ShopeePay',
                    'LINKAJA' => 'LinkAja',
                    'ASTRAPAY' => 'AstraPay',
                ],
            ],
            'qris' => [
                'name' => 'QRIS',
                'channels' => [
                    'QRIS' => 'QRIS (All E-Wallet)',
                    'QRISC' => 'QRIS Customizable',
                    'QRIS2' => 'QRIS Dynamic',
                ],
            ],
        ];
    }
}
