<?php

class InternetData extends ApiAccess {
    
    // ======================================
    // SMEPLUG API INTEGRATION (ONLY)
    // ======================================
    const SMEPLUG_API_KEY = 'ca5a53a504a';
    const SMEPLUG_DATA_API_URL = 'https://smeplug.ng/api/v1/data/purchase';

    /**
     * Format Nigerian phone number for SMEPlug API
     * SMEPlug expects a standard 11-digit Nigerian number starting with 0
     */
    private function formatPhoneForSMEPlug($phone) {
        error_log("=== Phone Formatting Debug ===");
        error_log("Original phone: " . $phone);
        
        $phone = preg_replace('/[^0-9]/', '', $phone);
        error_log("Cleaned phone: " . $phone);
        error_log("Phone length: " . strlen($phone));
        
        if (strlen($phone) == 11 && substr($phone, 0, 1) == '0') {
            error_log("Format: 11-digit starting with 0 - VALID");
            return $phone;
        }
        
        if (strlen($phone) == 13 && substr($phone, 0, 3) == '234') {
            $formatted = '0' . substr($phone, 3);
            error_log("Format: 13-digit starting with 234 - converted to: " . $formatted);
            return $formatted;
        }
        
        if (strlen($phone) == 10) {
            $formatted = '0' . $phone;
            error_log("Format: 10-digit - converted to: " . $formatted);
            return $formatted;
        }
        
        error_log("Format: INVALID - no valid format found");
        return false;
    }

    /**
     * Map network to SMEPlug network ID
     */
    private function mapNetworkToSMEPlugId($networkName) {
        error_log("=== Network Mapping Debug ===");
        error_log("Original network: '" . $networkName . "'");
        
        $networkMap = [
            'MTN' => 1,
            'AIRTEL' => 2,
            'GLO' => 3,
            '9MOBILE' => 4,
            'ETISALAT' => 4  // Alternative name for 9Mobile
        ];
        
        $networkName = strtoupper(trim($networkName));
        error_log("Cleaned network: '" . $networkName . "'");
        
        $networkId = isset($networkMap[$networkName]) ? $networkMap[$networkName] : null;
        error_log("Mapped network ID: " . ($networkId ?? 'NULL'));
        
        return $networkId;
    }

    /**
     * Call SMEPlug Data API with detailed debugging
     */
    private function callSMEPlugDataAPI($apiKey, $apiUrl, $data) {
        error_log("=== SMEPlug API Call Debug ===");
        error_log("API URL: " . $apiUrl);
        error_log("API Key (first 20 chars): " . substr($apiKey, 0, 20) . "...");
        error_log("Request Data: " . json_encode($data, JSON_PRETTY_PRINT));

        $payload = json_encode($data);
        error_log("JSON Payload: " . $payload);
        error_log("Payload length: " . strlen($payload));
        
        $headers = [
            'Authorization: Bearer ' . $apiKey,
            'Accept: application/json',
            'Content-Type: application/json',
            'User-Agent: Mozilla/5.0 (compatible; DataSystem/1.0; SMEPlug)',
        ];
        
        error_log("Request Headers: " . json_encode($headers, JSON_PRETTY_PRINT));

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $apiUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_CONNECTTIMEOUT => 30,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 2,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_ACCEPT_ENCODING => '',
            CURLOPT_VERBOSE => true  // Enable verbose output for debugging
        ]);

        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $curlError = curl_error($curl);
        $curlInfo = curl_getinfo($curl);
        curl_close($curl);

        error_log("=== SMEPlug API Response Debug ===");
        error_log("HTTP Code: " . $httpCode);
        error_log("cURL Error: " . ($curlError ?: 'None'));
        error_log("Response Length: " . strlen($response));
        error_log("Full Response: " . $response);
        error_log("cURL Info: " . json_encode($curlInfo, JSON_PRETTY_PRINT));

        // Save detailed response to file for analysis
        $debugData = [
            'timestamp' => date('Y-m-d H:i:s'),
            'request_data' => $data,
            'http_code' => $httpCode,
            'curl_error' => $curlError,
            'response' => $response,
            'curl_info' => $curlInfo
        ];
        file_put_contents("smeplug_debug_" . date('Ymd') . ".log", json_encode($debugData, JSON_PRETTY_PRINT) . "\n\n", FILE_APPEND);

        return [
            'success' => !$curlError && $httpCode == 200 && !empty($response),
            'http_code' => $httpCode,
            'curl_error' => $curlError,
            'raw_response' => $response,
            'parsed_response' => json_decode($response, true),
            'curl_info' => $curlInfo
        ];
    }

    /**
     * Purchase data using SMEPlug API with multiple format attempts
     */
    public function purchaseDataWithSMEPlug($body, $networkDetails, $datagroup, $actualPlanId) {
        error_log("=== Starting SMEPlug Data Purchase ===");
        error_log("Input Validation:");
        error_log("- body->phone: " . ($body->phone ?? 'NULL'));
        error_log("- body->ref: " . ($body->ref ?? 'NULL'));
        error_log("- networkDetails: " . json_encode($networkDetails));
        error_log("- datagroup: " . $datagroup);
        error_log("- actualPlanId: " . $actualPlanId . " (type: " . gettype($actualPlanId) . ")");

        $response = array();

        try {
            // Format phone number
            $formattedPhone = $this->formatPhoneForSMEPlug($body->phone);
            if (!$formattedPhone) {
                error_log("FAILED: Invalid phone format");
                $response["status"] = "fail";
                $response["msg"] = "Invalid phone number format. Please use format: 08012345678";
                $response["api_response_log"] = "Phone format error: " . $body->phone;
                return $response;
            }

            // Map network to SMEPlug ID
            $networkId = $this->mapNetworkToSMEPlugId($networkDetails["network"]);
            if (!$networkId) {
                error_log("FAILED: Invalid network mapping");
                $response["status"] = "fail";
                $response["msg"] = "Unsupported network: " . $networkDetails["network"];
                $response["api_response_log"] = "Network mapping failed for: " . $networkDetails["network"];
                return $response;
            }

            // Try multiple API request formats to handle HTTP 422
            $requestFormats = [
                // Format 1: Basic required fields
                [
                    'network_id' => (int)$networkId,
                    'plan_id' => (int)$actualPlanId,
                    'phone' => $formattedPhone
                ],
                // Format 2: String plan_id
                [
                    'network_id' => (int)$networkId,
                    'plan_id' => (string)$actualPlanId,
                    'phone' => $formattedPhone
                ],
                // Format 3: With bypass flag
                [
                    'network_id' => (int)$networkId,
                    'plan_id' => (int)$actualPlanId,
                    'phone' => $formattedPhone,
                    'bypass' => true
                ],
                // Format 4: With request_id
                [
                    'network_id' => (int)$networkId,
                    'plan_id' => (int)$actualPlanId,
                    'phone' => $formattedPhone,
                    'request_id' => $body->ref ?? 'SMEPLUG_' . time() . '_' . rand(1000, 9999)
                ],
                // Format 5: Complete with all fields
                [
                    'network_id' => (int)$networkId,
                    'plan_id' => (int)$actualPlanId,
                    'phone' => $formattedPhone,
                    'bypass' => true,
                    'request_id' => $body->ref ?? 'SMEPLUG_' . time() . '_' . rand(1000, 9999)
                ]
            ];

            $lastResult = null;
            
            foreach ($requestFormats as $formatIndex => $apiData) {
                error_log("=== Trying Format " . ($formatIndex + 1) . " ===");
                error_log("Format data: " . json_encode($apiData, JSON_PRETTY_PRINT));

                // Make API call
                $result = $this->callSMEPlugDataAPI(
                    self::SMEPLUG_API_KEY,
                    self::SMEPLUG_DATA_API_URL,
                    $apiData
                );

                $lastResult = $result;

                // If not HTTP 422, use this result
                if ($result['http_code'] != 422) {
                    error_log("Format " . ($formatIndex + 1) . " returned HTTP " . $result['http_code'] . " - using this result");
                    break;
                } else {
                    error_log("Format " . ($formatIndex + 1) . " failed with HTTP 422 - trying next format");
                }
            }

            // Use the last result
            $result = $lastResult;
            $response["api_response_log"] = $result['raw_response'];

            // Handle API call failure
            if (!$result['success']) {
                $errorMsg = "API call failed";

                if ($result['curl_error']) {
                    $errorMsg = "Connection error: " . $result['curl_error'];
                } elseif ($result['http_code'] == 422) {
                    $errorMsg = "Invalid request data. Please check plan ID and network selection.";
                    // Parse 422 response for specific error
                    $apiResponse = $result['parsed_response'];
                    if ($apiResponse && isset($apiResponse['message'])) {
                        $errorMsg = "Request error: " . $apiResponse['message'];
                    } elseif ($apiResponse && isset($apiResponse['error'])) {
                        $errorMsg = "Request error: " . $apiResponse['error'];
                    }
                } elseif ($result['http_code'] == 424) {
                    $errorMsg = "Service temporarily unavailable";
                } elseif ($result['http_code'] == 401) {
                    $errorMsg = "Authentication failed";
                } elseif ($result['http_code'] == 403) {
                    $errorMsg = "Access forbidden";
                } elseif ($result['http_code'] != 200) {
                    $errorMsg = "Service error (HTTP " . $result['http_code'] . ")";
                }

                error_log("SMEPlug API call failed: " . $errorMsg);
                $response["status"] = "fail";
                $response["msg"] = $errorMsg;
                
                // Log error details
                file_put_contents("smeplug_error_" . date('Ymd') . ".log", 
                    date('Y-m-d H:i:s') . " - " . $errorMsg . "\n" . 
                    "Response: " . $result['raw_response'] . "\n\n", 
                    FILE_APPEND);
                
                return $response;
            }

            // Parse successful response
            $apiResponse = $result['parsed_response'];

            if (!$apiResponse) {
                error_log("Invalid JSON response from SMEPlug");
                $response["status"] = "fail";
                $response["msg"] = "Invalid response from service";
                file_put_contents("smeplug_invalid_json_" . date('Ymd') . ".log", 
                    date('Y-m-d H:i:s') . " - " . $result['raw_response'] . "\n\n", 
                    FILE_APPEND);
                return $response;
            }

            error_log("SMEPlug Parsed Response: " . json_encode($apiResponse, JSON_PRETTY_PRINT));

            // Handle SMEPlug response
            if (isset($apiResponse['status']) && $apiResponse['status'] === true) {
                $response["status"] = "success";
                $response["reference"] = $apiResponse['data']['reference'] ?? ('SMEPLUG_' . time());
                $response["msg"] = $apiResponse['data']['msg'] ?? $apiResponse['message'] ?? 'Data purchase successful';
                $response["api_response"] = $apiResponse['data'] ?? $apiResponse;
                
                error_log("✓ SMEPlug Data purchase successful");
                
                // Log success
                file_put_contents("smeplug_success_" . date('Ymd') . ".log", 
                    date('Y-m-d H:i:s') . " - Success: " . $formattedPhone . " - " . $networkDetails["network"] . "\n", 
                    FILE_APPEND);
                    
            } else {
                $response["status"] = "fail";
                $errorMsg = $apiResponse['msg'] ?? $apiResponse['message'] ?? $apiResponse['error'] ?? "Transaction failed. Please try again.";
                
                // Filter balance-related errors
                if (strpos(strtolower($errorMsg), 'balance') !== false || 
                    strpos(strtolower($errorMsg), 'insufficient') !== false ||
                    strpos(strtolower($errorMsg), 'wallet') !== false) {
                    $response["msg"] = "Unable to complete transaction. Please contact support. Error Code: BB";
                } else {
                    $response["msg"] = $errorMsg;
                }
                
                error_log("✗ SMEPlug Data purchase failed: " . $errorMsg);
                
                // Log failure
                file_put_contents("smeplug_fail_" . date('Ymd') . ".log", 
                    date('Y-m-d H:i:s') . " - Failed: " . $errorMsg . "\n" . 
                    "Response: " . json_encode($apiResponse) . "\n\n", 
                    FILE_APPEND);
            }

            error_log("=== Final Response: " . json_encode($response) . " ===");
            return $response;

        } catch (Exception $e) {
            error_log("Exception in SMEPlug data purchase: " . $e->getMessage());
            error_log("Exception trace: " . $e->getTraceAsString());
            
            $response["status"] = "fail";
            $response["msg"] = "System error. Please try again later.";
            $response["api_response_log"] = "Exception: " . $e->getMessage();
            
            // Log exception
            file_put_contents("smeplug_exception_" . date('Ymd') . ".log", 
                date('Y-m-d H:i:s') . " - Exception: " . $e->getMessage() . "\n" . 
                $e->getTraceAsString() . "\n\n", 
                FILE_APPEND);
                
            return $response;
        }
    }

    // ======================================
    // MAIN PURCHASE DATA METHOD (SMEPlug ONLY)
    // ======================================
    public function purchaseData($body, $networkDetails, $datagroup, $actualPlanId) {
        error_log("=== MAIN PURCHASE DATA METHOD ===");
        error_log("Timestamp: " . date('Y-m-d H:i:s'));
        error_log("User: isahhhdev");
        error_log("SMEPlug Only Integration");
        error_log("Parameters received:");
        error_log("- Phone: " . ($body->phone ?? 'NULL'));
        error_log("- Reference: " . ($body->ref ?? 'NULL'));
        error_log("- Network Details: " . json_encode($networkDetails));
        error_log("- Data Group: " . $datagroup);
        error_log("- Plan ID: " . $actualPlanId);
        
        return $this->purchaseDataWithSMEPlug($body, $networkDetails, $datagroup, $actualPlanId);
    }

    // ======================================
    // UTILITY METHODS
    // ======================================
    
    /**
     * Test SMEPlug API connectivity
     */
    public function testSMEPlugConnection() {
        error_log("=== Testing SMEPlug API Connection ===");
        
        $testData = [
            'network_id' => 1,  // MTN
            'plan_id' => 1,     // Test plan
            'phone' => '08012345678'  // Test phone
        ];
        
        $result = $this->callSMEPlugDataAPI(
            self::SMEPLUG_API_KEY,
            self::SMEPLUG_DATA_API_URL,
            $testData
        );
        
        error_log("Connection test result: " . json_encode($result));
        return $result;
    }

    /**
     * Get supported networks
     */
    public function getSupportedNetworks() {
        return [
            'MTN' => 1,
            'AIRTEL' => 2,
            'GLO' => 3,
            '9MOBILE' => 4,
            'ETISALAT' => 4
        ];
    }
}