<?php

namespace App\Http\Controllers;

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

class OrangeMoneyController extends Controller
{
    //BNKSBFJS00000060000141

    public function index(){

        return view('orange_money.index');

    }


public function get_balance_form(){

        return view('orange_money.get_balance_form');

    }




    public function getAccountBalance(Request $request)
    {
        $url = "https://sandbox.orange-money.com/b2w/"; // Replace with the correct URL

        // Construct the SOAP XML payload directly as a string
        $xmlRequest = '<?xml version="1.0" encoding="UTF-8"?>' .
                      '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="https://sandbox.orange-money.com/b2w/">' .
                      '<SOAP-ENV:Body>' .
                      '<ns1:GetAccountBalance>' .
                      '<AccountBalanceInquiryRequest>' .
                      '<mmHeaderInfo>' .
                      '<operatorCode>ORANGEMONEYML</operatorCode>' .
                      '<requestId>OR' . now()->format('YmdHis') . strtoupper(Str::random(6)) . '</requestId>' .
                      '<requestToken></requestToken>' .
                      '<requestType>GETACCBAL</requestType>' .
                      '<affiliateCode>EML</affiliateCode>' .
                      '</mmHeaderInfo>' .
                      '<accountAlias>' . $request->accountAlias . '</accountAlias>' .
                      '<reason></reason>' .
                      '</AccountBalanceInquiryRequest>' .
                      '</ns1:GetAccountBalance>' .
                      '</SOAP-ENV:Body>' .
                      '</SOAP-ENV:Envelope>';

        // Send the SOAP request
        $response = Http::withHeaders([
            'Content-Type' => 'text/xml', // Use 'text/xml' or 'application/xml' as the content type
        ])->withBody($xmlRequest, 'text/xml')->post($url);

        // Check if the request was successful
        if ($response->successful()) {
            // Parse the response, assuming it is in XML format
            $xmlResponse = simplexml_load_string($response->body());
            // Extract balance from the response
            $balance = (string) $xmlResponse->xpath('//availableBalance')[0];

            return response()->json(['balance' => $balance]);
        } else {
            return response()->json(['error' => 'Failed to retrieve balance', 'details' => $response->body()], 500);
        }
    }

    //TEST SOAP API

    public function sendSoapRequest()
    {
        // Construct the SOAP XML payload
        $soapXml = '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="https://sandbox.orange-money.com/b2w/">' .
            '   <SOAP-ENV:Body>' .
            '       <ns1:GetAccountBalance>' .
            '           <AccountBalanceInquiryRequest>' .
            '               <mmHeaderInfo>' .
            '                   <operatorCode>ORANGEMONEYSX</operatorCode>' .
            '                   <requestId>OR' . now()->format('YmdHis') . strtoupper(Str::random(6)) . '</requestId>' .
            '                   <requestToken/>' .
            '                   <requestType>GETACCBAL</requestType>' .
            '                   <affiliateCode>ESX</affiliateCode>' .
            '               </mmHeaderInfo>' .
            '               <accountNo/>' .
            '               <accountAlias>BNKSBFJS00000060000141</accountAlias>' .
            '               <reason/>' .
            '           </AccountBalanceInquiryRequest>' .
            '       </ns1:GetAccountBalance>' .
            '   </SOAP-ENV:Body>' .
            '</SOAP-ENV:Envelope>';

        // Log the XML payload for debugging
        Log::info('SOAP Request XML:', ['xml' => $soapXml]);

        // Send the SOAP request
        $response = Http::withHeaders([
            'Content-Type' => 'text/xml; charset=utf-8',
            'SOAPAction' => 'balance' // Add the appropriate SOAPAction if required by the web service
        ])->withBody($soapXml, 'text/xml')
          ->post('https://sandbox.orange-money.com/b2w/simulator/simulator'); // Replace with the actual SOAP endpoint URL

        // Get the response body
        $body = $response->body();

        // Log the response for debugging
        Log::info('SOAP Response:', ['response' => $body]);

        // Output the response
        return response($body)
            ->header('Content-Type', 'text/xml');
    }




    //----------------------------------------------------------------

    public function registerCustomer(Request $request)
{
    $bic = 'BNKSBFJS';  // Replace with actual BIC
    $url = "https://sandbox.orange-money.com/b2w/register?bic={$bic}";

    // Data for the request
    $data = [
        "operatorCode" => " ORANGEMONEYML",  // Replace with actual operator code
        "requestId" => "OR" . now()->format('YmdHis') . strtoupper(Str::random(6)),
       // "requestToken" => hash('sha512', 'BICBICBI0000000001300' . 'OR151029ABCDEFGH' . 'ORANGEMONEYSX' . 'yourpassword' . $request->amount),
        "requestType" => "REGISTER",
        "affiliateCode" => "OML",
        "accountAlias" => $request->alias,
    ];

    // Send POST request to the register endpoint
    $response = Http::withHeaders([
        'Content-Type' => 'application/json',
    ])->post($url, $data);

     // Vérifier si la requête a réussi
     if ($response->successful()) {
        return response()->json(['message' => 'Statut de la transaction récupéré avec succès', 'data' => $response->json()]);
    } else {
        return response()->json(['message' => 'Erreur lors de la vérification du statut', 'error' => $response->body()], 500);
    }
}

public function checkIdleStatus()
{
    $bic = 'BNKSBFJS';  // Replace with actual BIC
    $url = "https://sandbox.orange-money.com/b2w/idle?bic=".$bic;

    // Send GET request to the idle endpoint
    $response = Http::withHeaders([
        'Content-Type' => 'application/json',
    ])->get($url);

    // Vérifier si la requête a réussi
    if ($response->successful()) {
        return response()->json(['message' => 'Statut de la transaction récupéré avec succès', 'data' => $response->json()]);
    } else {
        return response()->json(['message' => 'Erreur lors de la vérification du statut', 'error' => $response->body()], 500);
    }
}





}
