<?php

namespace App\Services;

use App\Models\Transaction;
use Illuminate\Support\Facades\Log;

class OrderService
{
    private $vipResellerService;
    private $emailService;

    public function __construct(
        VipResellerService $vipResellerService,
        EmailNotificationService $emailService
    ) {
        $this->vipResellerService = $vipResellerService;
        $this->emailService = $emailService;
    }

    /**
     * Process order after payment success
     * ✅ FIXED: Work directly with Transaction, no Order model needed
     */
    public function processOrder(Transaction $transaction)
    {
        // ✅ CRITICAL: Check if already processing
        if ($transaction->status === 'processing' && $transaction->trx_id) {
            Log::warning('Order already being processed', [
                'transaction_id' => $transaction->id,
                'invoice' => $transaction->invoice_number,
                'trx_id' => $transaction->trx_id,
            ]);
            
            return [
                'success' => false,
                'message' => 'Order already being processed',
                'code' => 'ALREADY_PROCESSING',
            ];
        }

        // ✅ CRITICAL: Check if already completed
        if ($transaction->status === 'success' && $transaction->provider_sn) {
            Log::warning('Order already completed', [
                'transaction_id' => $transaction->id,
                'invoice' => $transaction->invoice_number,
                'provider_sn' => $transaction->provider_sn,
            ]);
            
            return [
                'success' => true,
                'message' => 'Order already completed',
                'code' => 'ALREADY_COMPLETED',
                'sn' => $transaction->provider_sn,
            ];
        }

        try {
            // ✅ Mark as processing FIRST (prevent double processing)
            $transaction->update([
                'status' => 'processing',
                'processing_at' => now(),
            ]);

            Log::info('🚀 Processing order to VIP Reseller', [
                'transaction_id' => $transaction->id,
                'invoice' => $transaction->invoice_number,
                'product_code' => $transaction->product_code,
                'customer_data' => $transaction->customer_data,
            ]);

            // ✅ Extract User ID & Zone ID from customer_data
            $customerData = explode('|', $transaction->customer_data);
            $userId = $customerData[0] ?? null;
            $zoneId = $customerData[1] ?? null;

            // ✅ Validate customer data
            if (!$userId || $userId === 'VOUCHER-') {
                Log::error('Invalid customer data', [
                    'transaction_id' => $transaction->id,
                    'customer_data' => $transaction->customer_data,
                ]);
                
                $transaction->update([
                    'status' => 'failed',
                    'provider_note' => 'Invalid customer data',
                ]);
                
                return [
                    'success' => false,
                    'message' => 'Invalid customer data',
                ];
            }

            // ✅ Create order to VIP Reseller
            $result = $this->vipResellerService->createOrder(
                $transaction->product_code,
                $userId,
                $zoneId
            );

            Log::info('VIP Reseller Response', [
                'transaction_id' => $transaction->id,
                'result' => $result,
            ]);

            // ✅ Handle VIP Reseller response
            if ($result['success'] && isset($result['data']['trxid'])) {
                $data = $result['data'];

                // ✅ Update transaction with VIP Reseller data
                $transaction->update([
                    'trx_id' => $data['trxid'],
                    'provider_status' => $data['status'] ?? 'waiting',
                    'provider_note' => $data['note'] ?? null,
                    'provider_sn' => $data['sn'] ?? null,
                    'status' => $this->mapProviderStatus($data['status'] ?? 'waiting'),
                ]);

                // ✅ If instant success, send completion email
                if ($transaction->status === 'success' && $transaction->provider_sn) {
                    $this->sendCompletionEmail($transaction);
                }

                return [
                    'success' => true,
                    'message' => 'Order processed successfully',
                    'trx_id' => $data['trxid'],
                    'status' => $data['status'],
                    'sn' => $data['sn'] ?? null,
                ];

            } else {
                // ❌ Order failed
                $errorMsg = $result['message'] ?? 'Order creation failed';
                
                $transaction->update([
                    'status' => 'failed',
                    'provider_note' => $errorMsg,
                ]);

                Log::error('VIP Reseller order failed', [
                    'transaction_id' => $transaction->id,
                    'error' => $errorMsg,
                ]);

                return [
                    'success' => false,
                    'message' => $errorMsg,
                ];
            }

        } catch (\Exception $e) {
            Log::error('❌ Order processing exception', [
                'transaction_id' => $transaction->id,
                'invoice' => $transaction->invoice_number,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            // ✅ Mark as failed
            $transaction->update([
                'status' => 'failed',
                'provider_note' => 'Exception: ' . $e->getMessage(),
            ]);

            return [
                'success' => false,
                'message' => 'System error: ' . $e->getMessage(),
            ];
        }
    }

    /**
     * Send order completion email
     */
    private function sendCompletionEmail(Transaction $transaction)
    {
        if (!$transaction->customer_email) {
            Log::info('No email to send completion', [
                'transaction_id' => $transaction->id,
            ]);
            return;
        }

        try {
            $this->emailService->sendOrderComplete($transaction->fresh());
            
            Log::info('✅ Completion email sent', [
                'transaction_id' => $transaction->id,
                'email' => $transaction->customer_email,
            ]);
            
        } catch (\Exception $e) {
            Log::error('Failed to send completion email', [
                'transaction_id' => $transaction->id,
                'error' => $e->getMessage(),
            ]);
            // Don't fail the order if email fails
        }
    }

    /**
     * Map VIP Reseller status to our status
     */
    private function mapProviderStatus($providerStatus)
    {
        $statusMap = [
            'waiting' => 'processing',
            'process' => 'processing',
            'success' => 'success',
            'failed' => 'failed',
            'error' => 'failed',
        ];

        return $statusMap[strtolower($providerStatus)] ?? 'processing';
    }

    /**
     * Retry failed order
     */
    public function retryOrder(Transaction $transaction)
    {
        if (!in_array($transaction->status, ['failed', 'expired'])) {
            return [
                'success' => false,
                'message' => 'Can only retry failed/expired orders',
            ];
        }

        if ($transaction->payment_status !== 'PAID') {
            return [
                'success' => false,
                'message' => 'Payment not completed',
            ];
        }

        Log::info('🔄 Retrying order', [
            'transaction_id' => $transaction->id,
            'invoice' => $transaction->invoice_number,
        ]);

        // Reset status
        $transaction->update([
            'trx_id' => null,
            'provider_status' => null,
            'provider_note' => null,
            'processing_at' => null,
        ]);

        // Process again
        return $this->processOrder($transaction);
    }

    /**
     * Check order status from VIP Reseller
     */
    public function checkOrderStatus(Transaction $transaction)
    {
        if (!$transaction->trx_id) {
            return [
                'success' => false,
                'message' => 'No VIP Reseller transaction ID',
            ];
        }

        try {
            $result = $this->vipResellerService->checkOrderStatus($transaction->trx_id);

            if ($result['success'] && isset($result['data'])) {
                $data = $result['data'];

                $transaction->update([
                    'provider_status' => $data['status'] ?? null,
                    'provider_note' => $data['note'] ?? null,
                    'provider_sn' => $data['sn'] ?? null,
                    'status' => $this->mapProviderStatus($data['status'] ?? 'waiting'),
                ]);

                // Send completion email if just completed
                if ($transaction->status === 'success' && $transaction->provider_sn) {
                    $this->sendCompletionEmail($transaction);
                }

                return [
                    'success' => true,
                    'data' => $data,
                ];
            }

            return $result;

        } catch (\Exception $e) {
            Log::error('Check order status error', [
                'transaction_id' => $transaction->id,
                'error' => $e->getMessage(),
            ]);

            return [
                'success' => false,
                'message' => $e->getMessage(),
            ];
        }
    }
}