<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include '../../database/dbconfig.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $json = file_get_contents('php://input');
    $data = json_decode($json, true);
    if (json_last_error() === JSON_ERROR_NONE) {
    // Extract data
    $agent_api = $data['agent_api'];
    $recipient_number = $data['recipient_number'];
    $network = $data['network'];
    $gig = $data['gig'];
    $reference_id = $data['reference_id'];

    // Date and time generation
    date_default_timezone_set('GMT');
    $order_time = date('H:i:s A');
    $order_date = date('l, F d, Y');
    $real_date = date('Y-m-d');
    $mode = "External API";
    $purpose = "Order";
    $price = "0";
    $real_package = $gig."000";
    $medium = "External API";
    $status = "Crediting successful";
        
    // Check if the agent exists
    $stmt = $con->prepare("SELECT * FROM agents WHERE api = ?");
        if ($stmt) {
            $stmt->bind_param("s", $agent_api);
            $stmt->execute();
            $result = $stmt->get_result();
            if ($result->num_rows > 0) {
                $row = $result->fetch_assoc();
                $console = $row['console'];
                $first_name = $row['first_name'];
                $last_name = $row['last_name'];
                $user_id = $row['user_id'];
                $agent_email = $row['email'];
                $agent_tel = $row['telephone'];
                $account_type = $row['agent_type'];
                $agent_name = $first_name . " " . $last_name;
                $stmt->close();
                if($account_type=="SUPER AGENT"){
                //AT     
                if($network=="AT"){
  
                    // Prepare the SOAP request
                    if ($console < $gig) {
                        http_response_code(100);
                        echo json_encode(['message' => 'Admin is having low wallet balance']);
                    } else {
                            
    $selects = "SELECT * FROM console_activation";
        $sqls = mysqli_query($con, $selects);
            if ($sqls && mysqli_num_rows($sqls) > 0) {
                while ($row = mysqli_fetch_array($sqls)) {
                    if($row['status']=="ACTIVATED"){
                       // Prepare the SOAP request
                        $soap_request = <<<XML
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
    <soapenv:Header/>
    <soapenv:Body>
        <tem:FlexiIshareBundle>
            <tem:username>GeosamsPlusLtd</tem:username>
            <tem:password>8b91f93c375a3425889e17e0ba8e4eda</tem:password>
            <tem:dealerMsisdn>233276650033</tem:dealerMsisdn>
            <tem:recipientMsisdn>{$recipient_number}</tem:recipientMsisdn>
            <tem:transactionId>{$reference_id}</tem:transactionId>
            <tem:sharedBundle>{$real_package}</tem:sharedBundle>
        </tem:FlexiIshareBundle>
    </soapenv:Body>
</soapenv:Envelope>
XML;

                        $url = "http://41.215.168.146:443/FlexiShareBundles.asmx"; // API endpoint

                        // Initialize cURL
                        $ch = curl_init($url);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                        curl_setopt($ch, CURLOPT_POST, true);
                        curl_setopt($ch, CURLOPT_HTTPHEADER, [
                            'Content-Type: text/xml; charset=utf-8',
                            'SOAPAction: "http://tempuri.org/FlexiIshareBundle"'
                        ]);
                        curl_setopt($ch, CURLOPT_POSTFIELDS, $soap_request);

                        // Execute the cURL request and capture the response
                        $response = curl_exec($ch);

                        // Check for cURL errors
                        if (curl_errno($ch)) {
                            http_response_code(509);
                            echo json_encode(["message" => "cURL Error: " . curl_error($ch)]);
                            curl_close($ch);
                            exit;
                        }

                        // Parse the SOAP XML response
                        libxml_use_internal_errors(true);
                        $xml = simplexml_load_string($response);

                        // Check if XML parsing was successful
                        if ($xml === false) {
                            http_response_code(508);
                            echo json_encode(["message" => "Error: Unable to parse SOAP response"]);
                            curl_close($ch);
                            exit;
                        }
                        // Extract the error code and message from the response
                        $namespace = "http://tempuri.org/";  // SOAP namespace
                        $body = $xml->children("http://schemas.xmlsoap.org/soap/envelope/")->Body;
                        $flexi_response = $body->children($namespace)->FlexiIshareBundleResponse->FlexiIshareBundleResult->ApiResponse;
                        $response_code = (string)$flexi_response->ResponseCode; // Extract ResponseCode
                        $response_msg = (string)$flexi_response->ResponseMsg;   // Extract ResponseMsg
                        // Check the response code
                        if ($response_code == '200') {
                            
                            
                            
                            
                            // Insert the order into the `orders_at` table
$insertOrderQuery = "INSERT INTO orders_at (reference_id, beneficiary, gig, real_package, order_time, order_date, real_date, order_status, error_code, message, client_email) 
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$insertOrderStmt = $con->prepare($insertOrderQuery);

if ($insertOrderStmt) {
    $insertOrderStmt->bind_param("sssssssssss", $reference_id, $recipient_number, $gig, $real_package, $order_time, $order_date, $real_date, $status, $response_code, $response_msg, $agent_email);
    
    if ($insertOrderStmt->execute()) {
        $insertOrderStmt->close();

        // Insert into `console_orders`
        $consoleOrderQuery = "INSERT INTO console_orders (reference_id, agent_id, agent_name, agent_tel, agent_email, beneficiary, gig, order_time, order_date, real_date, order_status, medium) 
                              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $consoleOrderStmt = $con->prepare($consoleOrderQuery);

        if ($consoleOrderStmt) {
            $consoleOrderStmt->bind_param("ssssssssssss", $reference_id, $user_id, $agent_name, $agent_tel, $agent_email, $recipient_number, $gig, $order_time, $order_date, $real_date, $status, $medium);
            
            if ($consoleOrderStmt->execute()) {
                $consoleOrderStmt->close();

                // Update agent's console
                $new_console = $console - $gig;
                $updateConsoleStmt = $con->prepare("UPDATE agents SET console = ? WHERE user_id = ?");
                
                if ($updateConsoleStmt) {
                    $updateConsoleStmt->bind_param("ds", $new_console, $user_id);

                    if ($updateConsoleStmt->execute()) {
                        $updateConsoleStmt->close();

                        // Insert into `console_transactions`
                        $transactionQuery = "INSERT INTO console_transactions (reference_id, trans_id, user_id, agent_name, email, amount, console, trans_date, purpose) 
                                             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
                        $transactionStmt = $con->prepare($transactionQuery);

                        if ($transactionStmt) {
                            $transactionStmt->bind_param("sssssdsss", $reference_id, $reference_id, $user_id, $agent_name, $agent_email, $price, $new_console, $real_date, $purpose);

                            if ($transactionStmt->execute()) {
                                $transactionStmt->close();

                                // Send SMS notification
                                sendSmsNotification($recipient_number, $gig, $response_msg, true);

                                http_response_code(200);
                                echo json_encode(['message' => 'Successful']);
                            } else {
                                http_response_code(500);
                                echo json_encode(['message' => 'Failed to insert transaction: ' . $transactionStmt->error]);
                            }
                        } else {
                            http_response_code(501);
                            echo json_encode(['message' => 'Failed to prepare transaction statement: ' . $con->error]);
                        }
                    } else {
                        http_response_code(502);
                        echo json_encode(['message' => 'Failed to update wallet: ' . $updateConsoleStmt->error]);
                    }
                } else {
                    http_response_code(503);
                    echo json_encode(['message' => 'Failed to prepare wallet update statement: ' . $con->error]);
                }
            } else {
                http_response_code(504);
                echo json_encode(['message' => 'Failed to insert into console_orders: ' . $consoleOrderStmt->error]);
            }
        } else {
            http_response_code(505);
            echo json_encode(['message' => 'Failed to prepare console order statement: ' . $con->error]);
        }
  } else {
        http_response_code(506);
        echo json_encode(['message' => 'Failed to insert into orders_at: ' . $insertOrderStmt->error]);
    }
} else {
    http_response_code(507);
    echo json_encode(['message' => 'Failed to prepare order insertion statement: ' . $con->error]);
}
                } else {
                        // SOAP response indicates failure
                        http_response_code(511);
                        echo json_encode(['message' => "Order Failed: " . htmlspecialchars($response_msg)]);
                        }
                        curl_close($ch);
                    }
                    else{
                    http_response_code(101);
                    echo json_encode(['message' => 'Account is out of stock']);
                    }
                }
            }
        }
    }
                }
                else {
                http_response_code(104);
                echo json_encode(['message' => 'Network is not AT']);
            }
                
            } else {
                http_response_code(102);
                echo json_encode(['message' => 'Transaction failed']);
            }
        } else {
            http_response_code(500);
            echo json_encode(['message' => 'Failed to prepare agent selection statement: ' . $con->error]);
        }
   
    } else {
        http_response_code(400);
        echo json_encode(['message' => 'Invalid JSON']);
    }
} else {
    http_response_code(405);
    echo json_encode(['message' => 'Method Not Allowed']);
}

// Close the database connection
$con->close();

// Function to send SMS
function sendSmsNotification($recipient_number, $gig, $message, $isSuccess) {
    $status = $isSuccess ? "Crediting successful" : "Crediting failed";
    $smsData = [
        "type" => 1,
        "senderid" => "GEOSAMS",
        "messages" => [
            [
                "recipient" => $recipient_number,
                "message" => "You have received a new bundle allocation of {$gig} GB."
            ]
        ]
    ];
    $ch_sms = curl_init('https://api.moolre.com/open/sms/send');
    curl_setopt($ch_sms, CURLOPT_POST, true);
    curl_setopt($ch_sms, CURLOPT_POSTFIELDS, json_encode($smsData));
    curl_setopt($ch_sms, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'X-API-VASKEY: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ2YXNpZCI6MTM5NywiZXhwIjoxOTI0OTkxOTk5fQ.um2n8JA1Hmd8WBPpYAZBA_jhOD4QiA0IXxqjzXNhKGo'
    ]);
    curl_setopt($ch_sms, CURLOPT_RETURNTRANSFER, true);
    $sms_response = curl_exec($ch_sms);
    $sms_http_code = curl_getinfo($ch_sms, CURLINFO_HTTP_CODE);
    curl_close($ch_sms);
    if ($sms_http_code != 200) {
        error_log("Failed to send SMS: " . $sms_response);
    }
}

?>
