<?php

namespace App\Http\Controllers;

use App\Mail\OrderConfirmedMail;
use App\Mail\OrderInternalNotificationMail;
use App\Mail\OrderOnboardingMail;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Setting;
use App\Services\Card2CryptoService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class CheckoutController extends Controller
{
    public function index()
    {
        $cart = session('cart', []);
        if (empty($cart)) {
            return redirect()->route('services.index')->with('error', 'Your cart is empty.');
        }
        $total        = collect($cart)->sum(fn($item) => $item['price'] * $item['quantity']);
        $paymentInfo  = $this->activePaymentInfo();
        return view('checkout.index', compact('cart', 'total', 'paymentInfo'));
    }

    public function process(Request $request)
    {
        $cart = session('cart', []);
        if (empty($cart)) {
            return redirect()->route('services.index')->with('error', 'Your cart is empty.');
        }

        $validated = $request->validate([
            'full_name' => 'required|string|max:255',
            'email'     => 'required|email|max:255',
            'phone'     => 'required|string|max:30',
        ]);

        $total = collect($cart)->sum(fn($item) => $item['price'] * $item['quantity']);

        $order = Order::create([
            'order_number' => Order::generateOrderNumber(),
            'full_name'    => $validated['full_name'],
            'email'        => $validated['email'],
            'phone'        => $validated['phone'],
            'total'        => $total,
            'status'       => 'pending',
        ]);

        foreach ($cart as $item) {
            OrderItem::create([
                'order_id'     => $order->id,
                'package_id'   => $item['id'],
                'package_name' => $item['name'],
                'quantity'     => $item['quantity'],
                'unit_price'   => $item['price'],
            ]);
        }

        $payment = Setting::group('payment');

        // ── Card2Crypto ──────────────────────────────────────────────
        if (($payment['card2crypto_enabled'] ?? '0') === '1') {
            try {
                $service  = new Card2CryptoService();
                $result   = $service->createPayment($order);
                $redirect = $result['payment_url'] ?? $result['redirect_url'] ?? null;
                if ($redirect) {
                    return redirect()->away($redirect);
                }
            } catch (\Exception $e) {
                \Log::error('Card2Crypto error: ' . $e->getMessage());
            }
        }

        // ── MoonPay ──────────────────────────────────────────────────
        if (($payment['moonpay_enabled'] ?? '0') === '1' && !empty($payment['moonpay_api_key'])) {
            $base    = rtrim($payment['moonpay_widget_url'] ?? 'https://buy.moonpay.com', '/');
            $btc     = $payment['crypto_wallet_btc'] ?? '';
            $apiKey  = $payment['moonpay_api_key'];
            $url     = "{$base}?apiKey={$apiKey}&currencyCode=btc&walletAddress=" . urlencode($btc)
                     . '&baseCurrencyAmount=' . $order->total
                     . '&externalTransactionId=' . urlencode($order->order_number);
            return redirect()->away($url);
        }

        // ── Crypto wallets (manual / instruction page) ───────────────
        $hasCrypto = !empty($payment['crypto_wallet_btc'])
                  || !empty($payment['crypto_wallet_eth'])
                  || !empty($payment['crypto_wallet_usdt']);

        if ($hasCrypto) {
            session()->forget('cart');
            return redirect()->route('checkout.crypto', ['order' => $order->order_number]);
        }

        // ── Fallback: no payment method configured ────────────────────
        // Mark paid immediately (dev mode / free orders)
        $order->update(['status' => 'paid']);
        $this->sendOrderEmails($order);
        session()->forget('cart');

        return redirect()->route('checkout.success', ['order' => $order->order_number]);
    }

    public function cryptoInstructions(string $order)
    {
        $order   = Order::where('order_number', $order)->firstOrFail();
        $wallets = [
            'BTC'  => Setting::get('crypto_wallet_btc'),
            'ETH'  => Setting::get('crypto_wallet_eth'),
            'USDT' => Setting::get('crypto_wallet_usdt'),
        ];
        $wallets = array_filter($wallets);
        return view('checkout.crypto', compact('order', 'wallets'));
    }

    public function success(string $order)
    {
        $order = Order::where('order_number', $order)->firstOrFail();
        return view('checkout.success', compact('order'));
    }

    private function sendOrderEmails(Order $order): void
    {
        Mail::to($order->email)->send(new OrderConfirmedMail($order));
        Mail::to($order->email)->send(new OrderOnboardingMail($order));
        Mail::to(config('app.orders_email', env('ORDERS_EMAIL', 'orders@trollmasters.ai')))
            ->send(new OrderInternalNotificationMail($order));
    }

    private function activePaymentInfo(): array
    {
        $payment = Setting::group('payment');

        if (($payment['card2crypto_enabled'] ?? '0') === '1') {
            return ['method' => 'card2crypto', 'label' => 'Card / Crypto via Card2Crypto', 'icon' => '💳'];
        }
        if (($payment['moonpay_enabled'] ?? '0') === '1' && !empty($payment['moonpay_api_key'])) {
            return ['method' => 'moonpay', 'label' => 'Buy Crypto via MoonPay', 'icon' => '🌙'];
        }
        $hasCrypto = !empty($payment['crypto_wallet_btc'])
                  || !empty($payment['crypto_wallet_eth'])
                  || !empty($payment['crypto_wallet_usdt']);
        if ($hasCrypto) {
            return ['method' => 'crypto', 'label' => 'Pay with Cryptocurrency', 'icon' => '₿'];
        }

        return ['method' => 'none', 'label' => 'Secure Payment', 'icon' => '🔒'];
    }
}
