<?php
// app/Services/MobileMoneyService.php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class MobileMoneyService
{
    private $baseUrl = "https://lipila-prod.hobbiton.app/transactions/mobile-money";
    
    public function initiatePayment(array $paymentData)
    {
        try {
            // Validate required fields
            $requiredFields = ['mobile_number', 'amount', 'customer_name', 'email', 'company_id'];
            foreach ($requiredFields as $field) {
                if (empty($paymentData[$field])) {
                    throw new \Exception("Missing required field: {$field}");
                }
            }

            // Format phone number
            $formattedNumber = $this->formatPhoneNumber($paymentData['mobile_number']);
            
            // Prepare transaction data for API
            $transactionData = [
                "currency" => "ZMW",
                "amount" => (float) $paymentData['amount'],
                "accountNumber" => $formattedNumber,
                "fullName" => $paymentData['customer_name'],
                "phoneNumber" => $formattedNumber,
                "email" => $paymentData['email'],
                "externalId" => Str::uuid()->toString()
            ];

            Log::info('Sending mobile money request', $transactionData);

            // TODO: Replace with your actual company API key
            //$authorizationKey = $this->getCompanyApiKey($paymentData['company_id']);
            $authorizationKey =  "LPLSECK-7c511d96d76a4a00b94d2b57f5c8e22a";

            // Make API request
            $response = Http::timeout(30)->withHeaders([
                'Authorization' => 'Bearer ' . $authorizationKey,
                'Content-Type' => 'application/json',
            ])->post($this->baseUrl, $transactionData);

            Log::info('Mobile money API response', [
                'status' => $response->status(),
                'body' => $response->body()
            ]);

            if (!$response->successful()) {
                throw new \Exception('Payment gateway error: ' . $response->body());
            }

            $responseData = $response->json();
            
            if (empty($responseData)) {
                throw new \Exception('Empty response from payment gateway');
            }

            return [
                'success' => true,
                'transaction_id' => $responseData['transactionId'] ?? null,
                'external_id' => $responseData['externalId'] ?? null,
                'status' => $responseData['status'] ?? null,
                'message' => $responseData['message'] ?? null,
                'amount' => $responseData['amount'] ?? null,
                'raw_response' => $responseData
            ];

        } catch (\Exception $e) {
            Log::error('Mobile money payment initiation failed', [
                'error' => $e->getMessage(),
                'payment_data' => $paymentData
            ]);

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

    public function checkTransactionStatus($transactionId, $companyId)
    {
        try {
            $authorizationKey = "LPLSECK-7c511d96d76a4a00b94d2b57f5c8e22a";
            
            $url = "https://lipila-prod.hobbiton.app/transactions/status?transactionId={$transactionId}";

            $response = Http::timeout(30)->withHeaders([
                'Authorization' => 'Bearer ' . $authorizationKey,
                'Content-Type' => 'application/json',
            ])->get($url);

            if (!$response->successful()) {
                throw new \Exception('Status check failed: ' . $response->body());
            }

            return $response->json();

        } catch (\Exception $e) {
            Log::error('Transaction status check failed', [
                'transaction_id' => $transactionId,
                'error' => $e->getMessage()
            ]);

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

    public function pollTransactionStatus($transactionId, $companyId, $maxTime = 300, $interval = 10)
    {
        $elapsedTime = 0;

        while ($elapsedTime < $maxTime) {
            $statusResponse = $this->checkTransactionStatus($transactionId, $companyId);
            
            if (isset($statusResponse['status'])) {
                $status = $statusResponse['status'];
                
                if ($status === 'Successful') {
                    return [
                        'success' => true,
                        'status' => 'successful',
                        'data' => $statusResponse
                    ];
                } elseif ($status === 'Failed') {
                    return [
                        'success' => false,
                        'status' => 'failed',
                        'data' => $statusResponse
                    ];
                }
            }

            sleep($interval);
            $elapsedTime += $interval;
        }

        return [
            'success' => false,
            'status' => 'timeout',
            'error' => 'Transaction status polling timed out'
        ];
    }

  private function formatPhoneNumber($phoneNumber)
{
    // Remove any non-digit characters
    $cleaned = preg_replace('/\D/', '', $phoneNumber);
    
    \Log::info('Phone number formatting', [
        'original' => $phoneNumber,
        'cleaned' => $cleaned,
        'length' => strlen($cleaned)
    ]);
    
    // Handle different Zambian phone number formats
    if (strlen($cleaned) === 9 && Str::startsWith($cleaned, '0')) {
        // Format: 0976379025 -> 260976379025
        $cleaned = '260' . substr($cleaned, 1);
    } elseif (strlen($cleaned) === 10 && Str::startsWith($cleaned, '26')) {
        // Format: 260976379025 (already correct)
        $cleaned = $cleaned;
    } elseif (strlen($cleaned) === 12 && Str::startsWith($cleaned, '260')) {
        // Format: 260976379025 (already correct)
        $cleaned = $cleaned;
    } else {
        // If it doesn't match expected formats, try to make it work
        if (Str::startsWith($cleaned, '0')) {
            $cleaned = '260' . substr($cleaned, 1);
        } elseif (!Str::startsWith($cleaned, '260')) {
            $cleaned = '260' . $cleaned;
        }
    }
    
    // The API wants the format 260XXXXXXXXX (without dashes)
    // Just ensure it's 12 digits starting with 260
    if (strlen($cleaned) === 12 && Str::startsWith($cleaned, '260')) {
        $formatted = $cleaned; // Keep as 260976379025
    } else {
        // If we can't format properly, return the cleaned version
        $formatted = $cleaned;
    }
    
    \Log::info('Phone number formatted', [
        'final_formatted' => $formatted
    ]);
    
    return $formatted;
}
    private function getCompanyApiKey($companyId)
    {
        // TODO: Replace this with your actual company API key retrieval
        // This is a placeholder - you need to implement this based on your company model
        // Example: return Company::find($companyId)->payment_api;
        
        // For testing, you can return a test key or throw an exception
        throw new \Exception('Company API key not configured. Please implement getCompanyApiKey method.');
        
        // Or for testing, return a test key:
        // return 'your-test-api-key-here';
    }
}