<?php

namespace App\Http\Controllers;

use App\Services\FlutterwaveService;
use App\Services\InvestmentProductService;
use App\Services\AMMService;
use App\Models\Order;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class MobileMoneyPaymentController extends Controller
{
    protected $flutterwaveService;
    protected $ammService;

    public function __construct(FlutterwaveService $flutterwaveService, AMMService $ammService)
    {
        $this->flutterwaveService = $flutterwaveService;
        $this->ammService = $ammService;
    }

    /**
     * Initier un paiement Mobile Money
     */
    public function initiate(Request $request)
    {
        $validated = $request->validate([
            'amount' => 'required|numeric|min:100',
            'country' => 'required|string|in:CI,SN,BF,CM',
            'network' => 'required|string',
            'phone_number' => 'required|string',
            'email' => 'required|email',
            'fullname' => 'required|string',
            'tx_ref' => 'nullable|string',
            'redirect_url' => 'nullable|url',
            'authorization_code' => 'nullable|string', // Pour Orange Money BF
            'payment_type' => 'required|string', // shop, plan, investment
            'order_id' => 'nullable|integer',
        ]);

        try {
            $user = Auth::user();
            
            // Préparer les données pour Flutterwave
            $paymentData = [
                'amount' => $validated['amount'],
                'currency' => config("payment.currencies.{$validated['country']}", 'XOF'),
                'country' => $validated['country'],
                'network' => $validated['network'],
                'phone_number' => $validated['phone_number'],
                'email' => $validated['email'],
                'fullname' => $validated['fullname'],
                'tx_ref' => $validated['tx_ref'] ?? 'MM-' . strtoupper(uniqid()) . '-' . time(),
                'redirect_url' => $validated['redirect_url'] ?? route('payment.mobile-money.callback'),
                'client_ip' => $request->ip(),
            ];

            // Ajouter le code d'autorisation si fourni (Orange Money BF)
            if (isset($validated['authorization_code'])) {
                $paymentData['authorization_code'] = $validated['authorization_code'];
            }

            // Pour Orange Money Sénégal, déterminer si on utilise QR ou redirect
            if ($validated['country'] === 'SN' && $validated['network'] === 'ORANGEMONEY') {
                // Détection si mobile ou desktop
                $userAgent = $request->header('User-Agent');
                $isMobile = preg_match('/(android|iphone|ipad|mobile)/i', $userAgent);
                $paymentData['use_qr'] = !$isMobile; // QR pour desktop, redirect pour mobile
            }

            // Sauvegarder en session pour callback
            session([
                'mm_tx_ref' => $paymentData['tx_ref'],
                'mm_payment_type' => $validated['payment_type'],
                'mm_order_id' => $validated['order_id'] ?? null,
                'mm_amount' => $validated['amount'],
            ]);

            Log::info('Initiation paiement Mobile Money', [
                'user_id' => $user->id ?? null,
                'payment_type' => $validated['payment_type'],
                'country' => $validated['country'],
                'network' => $validated['network'],
                'amount' => $validated['amount'],
                'tx_ref' => $paymentData['tx_ref'],
            ]);

            // Appeler Flutterwave
            $result = $this->flutterwaveService->initiateMobileMoneyPayment($paymentData);

            if ($result['success']) {
                return response()->json([
                    'success' => true,
                    'data' => $result,
                    'message' => 'Paiement Mobile Money initié avec succès',
                ]);
            }

            return response()->json([
                'success' => false,
                'message' => $result['message'] ?? 'Erreur lors de l\'initiation du paiement',
            ], 400);

        } catch (\Exception $e) {
            Log::error('Erreur initiation Mobile Money', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Erreur: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Callback après paiement Mobile Money
     */
    public function callback(Request $request)
    {
        $txRef = $request->query('tx_ref') ?? session('mm_tx_ref');
        
        if (!$txRef) {
            return redirect()->route('member.dashboard')->with('error', 'Transaction non trouvée.');
        }

        try {
            // Vérifier le paiement
            $verification = $this->flutterwaveService->verifyPayment($txRef);

            if ($verification['success']) {
                $paymentType = session('mm_payment_type');
                $orderId = session('mm_order_id');

                // Traiter selon le type de paiement
                switch ($paymentType) {
                    case 'shop':
                        return $this->handleShopPayment($orderId, $verification);
                    
                    case 'plan':
                        return $this->handlePlanPayment($orderId, $verification);
                    
                    case 'investment':
                        return $this->handleInvestmentPayment($orderId, $verification);
                    
                    default:
                        return redirect()->route('member.dashboard')
                            ->with('success', 'Paiement effectué avec succès.');
                }
            }

            return redirect()->route('member.dashboard')
                ->with('error', 'Le paiement n\'a pas été vérifié.');

        } catch (\Exception $e) {
            Log::error('Erreur callback Mobile Money', [
                'tx_ref' => $txRef,
                'error' => $e->getMessage(),
            ]);

            return redirect()->route('member.dashboard')
                ->with('error', 'Erreur lors de la vérification du paiement.');
        }
    }

    /**
     * Traiter le paiement boutique
     */
    protected function handleShopPayment($orderId, $verification)
    {
        // Récupérer la commande et la mettre à jour
        $order = Order::find($orderId);
        
        if ($order) {
            $order->payment_status = 'paid';
            $order->payment_method = 'mobile_money';
            $order->payment_reference = $verification['tx_ref'] ?? $order->payment_reference;
            $order->payment_gateway_response = json_encode($verification);
            $order->save();
            
            // === VÉRIFIER ET APPLIQUER L'AVANCE AMM AUTOMATIQUEMENT ===
            // Si l'acheteur est un membre connecté
            if ($order->user_id) {
                $user = \App\Models\User::find($order->user_id);
                if ($user) {
                    $ammAdvanceResult = $this->ammService->checkAndApplyAdvanceAfterPurchase($user);
                    if ($ammAdvanceResult['advance_applied']) {
                        Log::info('AMM Advance applied after Mobile Money shop purchase', [
                            'user_id' => $user->id,
                            'order_id' => $order->id,
                            'new_active_until' => $ammAdvanceResult['new_active_until'],
                        ]);
                    }
                }
            }
        }
        
        session()->forget(['mm_tx_ref', 'mm_payment_type', 'mm_order_id', 'mm_amount']);
        
        return redirect()->route('member.orders.show', $orderId)
            ->with('success', 'Commande payée avec succès via Mobile Money!');
    }

    /**
     * Traiter le paiement plan/abonnement
     */
    protected function handlePlanPayment($orderId, $verification)
    {
        if (!Auth::check()) {
            return redirect()->route('member.login')->with('error', 'Veuillez vous connecter.');
        }

        $user = Auth::user();
        $expectedAmount = (float) (session('mm_amount', Setting::get('subscription_price', 5000)));
        $paidAmount = (float) ($verification['amount'] ?? 0);

        if ($paidAmount > 0 && abs($paidAmount - $expectedAmount) > 1) {
            Log::warning('Montant abonnement incohérent (Mobile Money)', [
                'expected' => $expectedAmount,
                'paid' => $paidAmount,
                'tx_ref' => $verification['tx_ref'] ?? null,
            ]);
            return redirect()->route('member.dashboard')->with('error', 'Montant du paiement incorrect.');
        }

        $user->subscription_paid = true;
        $user->subscription_paid_at = now();
        if (!$user->is_active) {
            $user->is_active = true;
        }
        $user->save();

        // Appliquer l'exonération AMM pour le mois en cours (+ mois suivant si après le 16)
        $this->ammService->applySubscriptionExemption($user);

        session()->forget(['mm_tx_ref', 'mm_payment_type', 'mm_order_id', 'mm_amount']);

        return redirect()->route('member.dashboard')
            ->with('success', 'Abonnement activé avec succès via Mobile Money!');
    }

    /**
     * Traiter le paiement investissement
     */
    protected function handleInvestmentPayment($orderId, $verification)
    {
        if (!Auth::check()) {
            return redirect()->route('member.login')->with('error', 'Veuillez vous connecter.');
        }

        $user = Auth::user();
        $order = $orderId ? Order::find($orderId) : null;

        if ($order && $order->user_id === $user->id) {
            $order->payment_status = 'paid';
            $order->payment_method = 'mobile_money';
            $order->payment_reference = $verification['tx_ref'] ?? $order->payment_reference;
            $order->payment_gateway_response = json_encode($verification);
            $order->save();
        }

        try {
            app(InvestmentProductService::class)->markInvestmentProductAsPaid($user, $order);
        } catch (\Exception $e) {
            Log::error('Erreur activation produit investissement (MM)', [
                'user_id' => $user->id,
                'order_id' => $orderId,
                'error' => $e->getMessage(),
            ]);
        }

        session()->forget(['mm_tx_ref', 'mm_payment_type', 'mm_order_id', 'mm_amount']);

        return redirect()->route('shop.index')
            ->with('success', 'Investissement payé avec succès via Mobile Money!');
    }

    /**
     * Obtenir les réseaux disponibles pour un pays
     */
    public function getNetworks(Request $request)
    {
        $country = $request->input('country');
        $networks = $this->flutterwaveService->getMobileMoneyNetworks($country);

        return response()->json([
            'success' => true,
            'networks' => $networks,
        ]);
    }
}
