<?php

class Account extends Model
{
  
    
      public function generatePocketFiAccount($id, $fname, $lname, $phone, $email, $nin, $bvn)
{
    // Log initial input data
    $logContent = "ID: $id\n";
    $logContent .= "First Name: $fname\n";
    $logContent .= "Last Name: $lname\n";
    $logContent .= "Phone: $phone\n";
    $logContent .= "Email: $email\n";
    $logContent .= "NIN: $nin\n";
    $logContent .= "BVN: $bvn\n";
    file_put_contents("pocketfi_log.txt", $logContent, FILE_APPEND);

    // Exact API endpoint
    $url = 'https://api.pocketfi.ng/api/v1/virtual-accounts/create';

    // Database connection
    $dbh = $this->connect();

    // Get API configuration
    $d = $this->getApiConfiguration();
    $PocketFiStatus = $this->getConfigValue($d, "PocketFiStatus");
    $PocketFiApiKey = $this->getConfigValue($d, "PocketFiApiKey");
    $PocketFiBusinessID = $this->getConfigValue($d, "PocketFiBusinessID");

    // Clean up input data
    $fname = trim($fname);
    $lname = trim($lname);
    $phone = trim($phone);
    $email = trim($email);
    $nin = trim($nin);
    $bvn = trim($bvn);

    // Prepare POST data for PocketFi API
    $postData = [
        "first_name" => $fname,
        "last_name" => $lname,
        "phone" => $phone,
        "email" => $email,
        "businessId" => $PocketFiBusinessID,
        "bank" => "palmpay",
        "nin" => $nin,
        "bvn" => $bvn
    ];

    // Initialize cURL
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => json_encode($postData),
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer $PocketFiApiKey",
            "Content-Type: application/json"
        ],
    ]);

    // Execute cURL request
    $result = curl_exec($ch);
    if ($result === false) {
        file_put_contents("pocketfi_log.txt", "cURL Error: " . curl_error($ch) . "\n", FILE_APPEND);
    }
    curl_close($ch);
    $value = json_decode($result, true);

    // Log API response
    file_put_contents("pocketfi_log.txt", "API Response: " . json_encode($value) . "\n", FILE_APPEND);

    // Check if account number exists in response and update database
    if (isset($value['banks'][0]['accountNumber'])) {
        $accountNumber = $value['banks'][0]['accountNumber'];

        file_put_contents("pocketfi_log.txt", "Account Number: $accountNumber\n", FILE_APPEND);

        // Update database
        $c = "UPDATE subscribers SET sPocketFiBank = :pfb, sAccountLimit = '10000' WHERE sId = :id";
        $queryC = $dbh->prepare($c);
        $queryC->bindParam(':pfb', $accountNumber, PDO::PARAM_STR);
        $queryC->bindParam(':id', $id, PDO::PARAM_INT);
        $queryC->execute();

        file_put_contents("pocketfi_log.txt", "Database updated successfully for ID: $id\n", FILE_APPEND);
    } else {
        file_put_contents("pocketfi_log.txt", "Error: Account number not found in response.\n", FILE_APPEND);
    }

    return $value; // Return the API response
}

public function generatePocketFiAccount2($id, $fname, $lname, $phone, $email, $nin, $bvn)
{
    // Log initial input data
    $logContent = "ID: $id\n";
    $logContent .= "First Name: $fname\n";
    $logContent .= "Last Name: $lname\n";
    $logContent .= "Phone: $phone\n";
    $logContent .= "Email: $email\n";
    $logContent .= "NIN: $nin\n";
    $logContent .= "BVN: $bvn\n";
    file_put_contents("pocketfi_log.txt", $logContent, FILE_APPEND);

    // Exact API endpoint
    $url = 'https://api.pocketfi.ng/api/v1/virtual-accounts/create';

    // Database connection
    $dbh = $this->connect();

    // Get API configuration
    $d = $this->getApiConfiguration();
    $PocketFiStatus2 = $this->getConfigValue($d, "PocketFiStatus2");
    $PocketFiApiKey = $this->getConfigValue($d, "PocketFiApiKey");
    $PocketFiBusinessID = $this->getConfigValue($d, "PocketFiBusinessID");

    // Clean up input data
    $fname = trim($fname);
    $lname = trim($lname);
    $phone = trim($phone);
    $email = trim($email);
    $nin = trim($nin);
    $bvn = trim($bvn);

    // Prepare POST data for PocketFi API
    $postData = [
        "first_name" => $fname,
        "last_name" => $lname,
        "phone" => $phone,
        "email" => $email,
        "businessId" => $PocketFiBusinessID,
        "bank" => "paga",
        "nin" => $nin,
        "bvn" => $bvn
    ];

    // Initialize cURL
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => json_encode($postData),
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer $PocketFiApiKey",
            "Content-Type: application/json"
        ],
    ]);

    // Execute cURL request
    $result = curl_exec($ch);
    if ($result === false) {
        file_put_contents("pocketfi_log.txt", "cURL Error: " . curl_error($ch) . "\n", FILE_APPEND);
    }
    curl_close($ch);
    $value = json_decode($result, true);

    // Log API response
    file_put_contents("pocketfi_log.txt", "API Response: " . json_encode($value) . "\n", FILE_APPEND);

    // Check if account number exists in response and update database
    if (isset($value['banks'][0]['accountNumber'])) {
        $accountNumber = $value['banks'][0]['accountNumber'];

        file_put_contents("pocketfi_log.txt", "Account Number: $accountNumber\n", FILE_APPEND);

        // Update database
        $c = "UPDATE subscribers SET sPocketFiBank2 = :pfb, sAccountLimit = '10000' WHERE sId = :id";
        $queryC = $dbh->prepare($c);
        $queryC->bindParam(':pfb', $accountNumber, PDO::PARAM_STR);
        $queryC->bindParam(':id', $id, PDO::PARAM_INT);
        $queryC->execute();

        file_put_contents("pocketfi_log.txt", "Database updated successfully for ID: $id\n", FILE_APPEND);
    } else {
        file_put_contents("pocketfi_log.txt", "Error: Account number not found in response.\n", FILE_APPEND);
    }

    return $value; // Return the API response
}

public function generatePocketFiAccount3($id, $fname, $lname, $phone, $email, $nin = null, $bvn = null)
{
    // Log initial input data
    $logContent = "ID: $id\n";
    $logContent .= "First Name: $fname\n";
    $logContent .= "Last Name: $lname\n";
    $logContent .= "Phone: $phone\n";
    $logContent .= "Email: $email\n";
    $logContent .= "NIN: " . ($nin ?? 'Not provided') . "\n";
    $logContent .= "BVN: " . ($bvn ?? 'Not provided') . "\n";
    file_put_contents("pocketfi_log.txt", $logContent, FILE_APPEND);

    // Exact API endpoint
    $url = 'https://api.pocketfi.ng/api/v1/virtual-accounts/create';

    // Database connection
    $dbh = $this->connect();

    // Get API configuration
    $d = $this->getApiConfiguration();
    $PocketFiStatus3 = $this->getConfigValue($d, "PocketFiStatus3");
    $PocketFiApiKey = $this->getConfigValue($d, "PocketFiApiKey");
    $PocketFiBusinessID = $this->getConfigValue($d, "PocketFiBusinessID");

    // Clean up input data
    $fname = trim($fname);
    $lname = trim($lname);
    $phone = trim($phone);
    $email = trim($email);
    if ($nin !== null) {
        $nin = trim($nin);
    }
    if ($bvn !== null) {
        $bvn = trim($bvn);
    }

    // Prepare POST data for PocketFi API
    $postData = [
        "first_name" => $fname,
        "last_name" => $lname,
        "phone" => $phone,
        "email" => $email,
        "businessId" => $PocketFiBusinessID,
        "bank" => "kuda"
    ];

    // Include NIN if provided
    if ($nin !== null) {
        $postData["nin"] = $nin;
    }

    // Include BVN if provided
    if ($bvn !== null) {
        $postData["bvn"] = $bvn;
    }

    // Initialize cURL
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => json_encode($postData),
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer $PocketFiApiKey",
            "Content-Type: application/json"
        ],
    ]);

    // Execute cURL request
    $result = curl_exec($ch);
    if ($result === false) {
        file_put_contents("pocketfi_log.txt", "cURL Error: " . curl_error($ch) . "\n", FILE_APPEND);
    }
    curl_close($ch);
    $value = json_decode($result, true);

    // Log API response
    file_put_contents("pocketfi_log.txt", "API Response: " . json_encode($value) . "\n", FILE_APPEND);

    // Check if account number exists in response and update database
    if (isset($value['banks'][0]['accountNumber'])) {
        $accountNumber = $value['banks'][0]['accountNumber'];

        file_put_contents("pocketfi_log.txt", "Account Number: $accountNumber\n", FILE_APPEND);

        // Update database
        $c = "UPDATE subscribers SET sPocketFiBank3 = :pfb, sAccountLimit = '10000' WHERE sId = :id";
        $queryC = $dbh->prepare($c);
        $queryC->bindParam(':pfb', $accountNumber, PDO::PARAM_STR);
        $queryC->bindParam(':id', $id, PDO::PARAM_INT);
        $queryC->execute();

        file_put_contents("pocketfi_log.txt", "Database updated successfully for ID: $id\n", FILE_APPEND);
    } else {
        $errorMessage = isset($value['message']) ? $value['message'] : 'Unknown error';
        file_put_contents("pocketfi_log.txt", "Error: Account number not found in response. API Message: $errorMessage\n", FILE_APPEND);
    }

    return $value; // Return the API response
}
    //Verify Admin Login Deatils
    public function verifyAdminAccount($uname, $pass)
    {
        $sql = "SELECT sysId,sysName,sysStatus,sysUsername,sysRole FROM sysusers WHERE sysUsername=:uname AND sysToken=:password";
        $query = self::$dbh->prepare($sql);
        $query->bindParam(':uname', $uname, PDO::PARAM_STR);
        $query->bindParam(':password', $pass, PDO::PARAM_STR);
        $query->execute();
        $result = $query->fetch(PDO::FETCH_ASSOC);

        if ($query->rowCount() > 0) {
            if ($result["sysStatus"] != 0) {
                return 2;
            }
            $_SESSION['sysUser'] = $result["sysUsername"];
            $_SESSION['sysRole'] = $result["sysRole"];
            $_SESSION['sysName'] = $result["sysName"];
            $_SESSION['sysId'] = $result["sysId"];
            return 0;
        } else {
            return 1;
        }
    }

    //Register/Create New User Account
    public function registerUser($fname, $lname, $email, $phone, $password, $state, $account, $referal, $transpin)
    {
        //if registration is done by admin, dont save cookies data
        if ($referal == "admin") {
            $saveCookies = false;
            $referal = "";
        } else {
            $saveCookies = true;
        }

        //Verify Registration Details
        $dbh = self::connect();
        $c = "SELECT sEmail,sPhone,sType FROM subscribers WHERE ";
        $c .= $email != "" ? " sEmail=:e OR sPhone=:p" : " sPhone=:p";
        $queryC = $dbh->prepare($c);
        if ($email != "") {
            $queryC->bindParam(':e', $email, PDO::PARAM_STR);
        }
        $queryC->bindParam(':p', $phone, PDO::PARAM_STR);
        $queryC->execute();
        $result = $queryC->fetch(PDO::FETCH_ASSOC);
        $data = 4;

        //Output Error Message If Data Already Exist
        if ($queryC->rowCount() > 0) {
            if ($result["sPhone"] == $phone) {
                $data = 3;
            }
            if ($email != "") {
                if ($result["sEmail"] == $email) {
                    $data = 2;
                }
            }
            if ($result["sEmail"] == $email && $result["sPhone"] == $phone) {
                $data = 1;
            }

            //Code 1 Phone And Email Exist, Code 2 Email Exist, Code 3 Phone Exist

            return $data;
        }

        //Insert And Register Member
        else {
            $hash = substr(sha1(md5($password)), 3, 10);
            $apiKey = substr(str_shuffle("0123456789ABCDEFGHIJklmnopqrstvwxyzAbAcAdAeAfAgAhBaBbBcBdC1C23C3C4C5C6C7C8C9xix2x3"), 0, 60) . time();
            $varCode = mt_rand(2000, 9000);

            $sql = "INSERT INTO subscribers (sFname,sLname,sEmail,sPhone,sPass,sState,sType,sApiKey,sReferal,sPin,sVerCode,sRegStatus)VALUES(:fname,:lname,:email,:phone,:pass,:s,:a,:k,:ref,:pin,:code,0)";

            $query = $dbh->prepare($sql);

            $query->bindParam(':fname', $fname, PDO::PARAM_STR);
            $query->bindParam(':lname', $lname, PDO::PARAM_STR);
            $query->bindParam(':email', $email, PDO::PARAM_STR);
            $query->bindParam(':phone', $phone, PDO::PARAM_STR);
            $query->bindParam(':pass', $hash, PDO::PARAM_STR);
            $query->bindParam(':s', $state, PDO::PARAM_STR);
            $query->bindParam(':a', $account, PDO::PARAM_STR);
            $query->bindParam(':k', $apiKey, PDO::PARAM_STR);
            $query->bindParam(':ref', $referal, PDO::PARAM_STR);
            $query->bindParam(':pin', $transpin, PDO::PARAM_INT);
            $query->bindParam(':code', $varCode, PDO::PARAM_STR);
            $query->execute();

            $lastInsertId = $dbh->lastInsertId();
            if ($lastInsertId) {
                $data = 0;

                if ($saveCookies) {
                    $_SESSION["loginId"] = $lastInsertId;
                    $_SESSION["loginName"] = $fname . " " . $lname;
                    $_SESSION["loginEmail"] = $email;
                    $_SESSION["loginPhone"] = $phone;

                    $loginId = base64_encode($lastInsertId);
                    $loginState = base64_encode($state);
                    $loginPhone = base64_encode($phone);
                    $loginAccount = base64_encode("1");
                    $loginName = base64_encode($fname);

                    $_SESSION["loginName"] = $fname;
                    setcookie("loginId", $loginId, time() + 2592000 * 30, "/");
                    setcookie("loginState", $loginState, time() + 2592000 * 30, "/");
                    setcookie("loginAccount", $loginAccount, time() + 2592000 * 30, "/");
                    setcookie("loginPhone", $loginPhone, time() + 31540000 * 30, "/");
                    setcookie("loginName", $loginName, time() + 31540000 * 30, "/");

                    //Generate User Login Token
                    $randomToken = substr(str_shuffle("ABCDEFGHIJklmnopqrstvwxyz"), 0, 10);
                    $userLoginToken = time() . $randomToken . mt_rand(100, 1000);

                    //Set User Login Token
                    $_SESSION["loginAccToken"] = $userLoginToken;

                    //Save New User Login Token For One Device Login Check

                    $sqlAc = "INSERT INTO userlogin (user,token) VALUES (:user,:token)";
                    $queryAc = $dbh->prepare($sqlAc);
                    $queryAc->bindParam(':user', $lastInsertId, PDO::PARAM_STR);
                    $queryAc->bindParam(':token', $userLoginToken, PDO::PARAM_STR);
                    $queryAc->execute();
                }

                //Get API Details
                $d = $this->getApiConfiguration();
                $a = $this->getSiteConfiguration();
                $monifyStatus = $this->getConfigValue($d, "monifyStatus");
                $monifyApi = $this->getConfigValue($d, "monifyApi");
                $monifySecrete = $this->getConfigValue($d, "monifySecrete");
                $monifyContract = $this->getConfigValue($d, "monifyContract");
                $adminEmail = $a->email;

                //If Monnify Is Active, Create Virtual Account For User
                if ($monifyStatus == "On") {
                    $this->createVirtualBankAccount($lastInsertId, $fname, $lname, $phone, $email, $monifyApi, $monifySecrete, $monifyContract);
                }

                //Send Email To User
                $subject = "Welcome (" . $this->sitename . ")";
                $message =
                    "Hi " .
                    $fname .
                    ", " .
                    "Welcome to {$this->sitename}. At {$this->sitename}, you can access instant recharge of Airtime, Data Bundle, CableTv, Electricity Bill Payment and Airtime to Cash. More features such as buying and selling gift cards, wallet to wallet transfer, and wallet to bank transfer would be made available soon. Our customer support line is available to you 24/7. Stay connected.";
                $message .= "<h3>Use The Verification Code \"" . $varCode . "\" To Recover Your Account.</h3>";
                $check = self::sendMail($email, $subject, $message);

                //Send Email To Admin
                $subject2 = "New User Registration (" . $this->sitename . ")";
                $message2 = "Hi " . $this->sitename . ", " . "This is to notify you that a new user just registered on your platform. Please find the below details for your usage: ";
                $message2 .= "<h3>Name: $fname $lname <br/> Phone Number: $phone <br/> Email: $email <br> State: $state</h3>";
                $message2 .= "<br/><br/><br/> <i>Notification Powered By Topupmate Technology</i>";
                $check = self::sendMail($adminEmail, $subject2, $message2);
                // Sending WhatsApp Message with Image

                $originalNumber = $phone;
                $modifiedNumber = $originalNumber;

                if (substr($originalNumber, 0, 1) === '0') {
                    $modifiedNumber = '234' . substr($originalNumber, 1);
                }

                $apiKeey = "7a901e61a0eb12c96ac3b6cec4231fdb";
                $image = "https://i.ibb.co/RCgzRSj/20230802-225840.jpg";
                $toNumber = $modifiedNumber;
                $text =
                    "We are pleased to have you on our platform https://dannvtu.com.ng. We hope to give you the best platform experience as a team. Please don't hesitate to reach out to me if you encounter any difficulties while using our platform. Have a great time! Best regards, DANNVTU.";

                $datta = [
                    "to" => $toNumber,
                    "text" => $text,
                    "mediaUrl" => $image,
                ];

                // Now you can use the $data array as needed for your API request

                $headeers = ["accept: application/json", "content-type: application/json"];

                $ch = curl_init();

                curl_setopt($ch, CURLOPT_URL, "https://node.jobians.top/whatsapp/api/sendImage/447459930441?apiKey=" . $apiKeey);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($datta));
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headeers);

                $response = curl_exec($ch);

                if (curl_errno($ch)) {
                    echo "Error: " . curl_error($ch);
                }

                curl_close($ch);

                // Rest of your code...
            } else {
                $data = 4;
            }

            return $data;
        }
    }

    public function createpayvessel($uId, $uFname, $uLname, $uPhone, $uEmail, $bvn, $nin, $payvesselapi, $payvesselsecret, $payvesselbusinessid)
    {
        $headers = ['api-key: ' . $payvesselapi, 'api-secret: Bearer ' . $payvesselsecret, 'Content-Type: application/json'];
        $data = [
            'email' => $uEmail,
            'name' => $uFname . ' ' . $uLname,
            'phoneNumber' => $uPhone,
            'bankcode' => ['120001'],
            'businessid' => $payvesselbusinessid,
        ];

        if (!empty($bvn)) {
            $data["bvn"] = $bvn;
        } elseif (!empty($nin)) {
            $data["nin"] = $nin;
        }

        $url = 'https://api.payvessel.com/api/external/request/customerReservedAccount/';

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'cURL Error: ' . curl_error($ch);
            return;
        }
        curl_close($ch);
        $responseData = json_decode($response, true);

        if ($responseData["status"] == true) {
            $account_name = $responseData["responseBody"]["accountName"];
            if ($responseData["service"] == "CREATE_VIRTUAL_ACCOUNT") {
                $payvessel = $responseData['banks'][0]['accountNumber'];

                $dbh = self::connect();
                $c = "UPDATE subscribers SET sPayVesselBank=:fb WHERE sId=:sId";
                $queryC = $dbh->prepare($c);
                $queryC->bindParam(':fb', $payvessel, PDO::PARAM_STR);
                $queryC->bindParam(':sId', $uId, PDO::PARAM_INT);
                $queryC->execute();
            }
        }
    }
function sendDeviceLogin($userId, $message) {
    // Your Node.js server URL
    $nodeJsServerUrl = 'https://wapaysupportchat.pxxl.xyz/device-login'; // Replace with your actual Node.js server URL
    
    // Data to send in the POST request
    $data = [
        'user_id' => $userId,
        'message' => $message
    ];

    // Initialize cURL session
    $ch = curl_init($nodeJsServerUrl);

    // Set cURL options
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return response as string
    curl_setopt($ch, CURLOPT_POST, true); // Set HTTP method to POST
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); // Set POST fields
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/x-www-form-urlencoded' // Set content type
    ]);

    // Execute the POST request and get the response
    $response = curl_exec($ch);

    // Check if there was an error with the cURL request
    if (curl_errno($ch)) {
        $error_message = 'cURL Error: ' . curl_error($ch);
        error_log($error_message); // Log the error
    }

    // Log the response, whether successful or error
    error_log('Response from Node.js server: ' . $response);

    // Close the cURL session
    curl_close($ch);

    // Return the server response
    return $response;
}
    //Login User Account
public function loginUserFingerPrint($phone, $key, $device, $fcmToken)
{
    $dbh = $this->connect();
    $hash = substr(sha1(md5($key)), 3, 10);
    $deviceToken = $device; // Directly use the provided device ID

    // Modify query to check if the input is either sPhone or sEmail
    $c = "SELECT * FROM subscribers WHERE (sPhone = :ph OR sEmail = :ph) AND sPass = :p";

    $queryC = $dbh->prepare($c);
    $queryC->bindParam(':ph', $phone, PDO::PARAM_STR);
    $queryC->bindParam(':p', $hash, PDO::PARAM_STR);
    $queryC->execute();

    $result = $queryC->fetch(PDO::FETCH_OBJ);

    if ($queryC->rowCount() > 0) {
        if ($result->sRegStatus == 1) {
            $response = [];
            $response["status"] = 2;
            return $response;
        }
        if ($result->sRegStatus == 4) {
            $response = [];
            $response["status"] = 4;
            return $response;
        }

        // ðŸ”¹ Check for existing FCM token
        $oldFcmToken = $result->sFcm;
        if ($fcmToken && $oldFcmToken && $oldFcmToken !== $fcmToken) {
            // Send logout notification to old device via POST request
            try {
                $ch = curl_init();
                $url = 'https://dannvtu.com.ng/fcm/wapay/send_notification.php'; // Replace with actual endpoint URL
                $payload = json_encode([
                    'id' => $oldFcmToken,
                    'title' => 'New Device Logged In', // Used as action identifier
                    'body' => "You recently logged in on a new device"
                ]);
                $headers = [
                    'Content-Type: application/json',
                    'Authorization: Basic 8TW9T9F9VFLSPE00T9' // Your API key
                ];

                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

                $resultCurl = curl_exec($ch);
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);

                if ($resultCurl === false || $httpCode !== 200) {
                    error_log("Failed to send FCM notification: HTTP $httpCode, Response: $resultCurl");
                } else {
                    error_log("FCM notification sent to old device token: $oldFcmToken");
                }
            } catch (Exception $e) {
                error_log("Error sending FCM notification: " . $e->getMessage());
            }
        }

        $newDeviceToken = $deviceToken; // Use provided device ID

        // ðŸ”¹ âœ… UPDATE both device ID and FCM token in the database
        $stmt = "UPDATE subscribers 
                 SET sDevice = :deviceToken, 
                     sFcm = :fcmToken, 
                     sDeviceCheck = 'match' 
                 WHERE sId = :sId";
        $query = $dbh->prepare($stmt);
        $query->bindParam(':deviceToken', $newDeviceToken, PDO::PARAM_STR);
        $query->bindParam(':fcmToken', $fcmToken, PDO::PARAM_STR);
        $query->bindParam(':sId', $result->sId, PDO::PARAM_INT);
        $query->execute();

        // ------------------ Existing Session & Cookie Setup ------------------
        $_SESSION["loginId"] = $result->sId;
        $_SESSION["loginName"] = $result->sFname . " " . $result->sLname;
        $_SESSION["loginEmail"] = $result->sEmail;
        $_SESSION["loginPhone"] = $result->sPhone;

        $loginId = base64_encode($result->sId);
        $loginState = base64_encode($result->sState);
        $loginAccount = base64_encode($result->sType);
        $loginPhone = base64_encode($result->sPhone);
        $loginName = base64_encode($result->sFname);
        setcookie("loginId", $loginId, time() + 2592000 * 30, "/");
        setcookie("loginState", $loginState, time() + 2592000 * 30, "/");
        setcookie("loginAccount", $loginAccount, time() + 2592000 * 30, "/");
        setcookie("loginPhone", $loginPhone, time() + 31540000 * 30, "/");
        setcookie("loginName", $loginName, time() + 31540000 * 30, "/");

        // Generate User Login Token
        $randomToken = substr(str_shuffle("ABCDEFGHIJklmnopqrstvwxyz"), 0, 10);
        $userLoginToken = time() . $randomToken . mt_rand(100, 1000);
        $_SESSION["loginAccToken"] = $userLoginToken;

        if($device != $result->sDevice){
            $this->sendDeviceLogin($result->sId, $device);
        }

        $sqlAc = "INSERT INTO userlogin (user,token) VALUES (:user,:token)";
        $queryAc = $dbh->prepare($sqlAc);
        $queryAc->bindParam(':user', $result->sId, PDO::PARAM_STR);
        $queryAc->bindParam(':token', $userLoginToken, PDO::PARAM_STR);
        $queryAc->execute();

        // Build response
        $response = [];
        $response["status"] = 0;
        $response["Id"] = $result->sId;
        $response["name"] = $result->sFname . " " . $result->sLname;
        $response["phone"] = $result->sPhone;
        $response["email"] = $result->sEmail;
        $response["fname"] = $result->sFname;
        $response["lname"] = $result->sLname;
        $response["pin"] = $result->sPin;
        $response["date"] = $result->sRegDate;
        $response["image"] = $result->sImage;
        $response["address"] = $result->sAddress;
        $response["account_number"] = $result->sRolexBank;
        $response["account_name"] = $result->sFname;
        $response["age"] = $result->sAge;
        $response["sex"] = $result->sSex;
        $response["user_type"] = $result->sType;
        $response["refwallet"] = $result->sRefWallet;
        $response["wallet"] = $result->sWallet;
        $response["vercode"] = $result->sVerCode;
        $response["moniepoint"] = $result->sRolexBank;
        $response["payvessel"] = $result->sPayVessel;
        $response["wema"] = $result->sBankNo;
        $response["charges"] = "1.7%";
        $response["username"] = $result->SUsername;
        $response["isbank_verify"] = "yes";
        $response["apikey"] = $result->sApiKey;
        $response["notif"] =
            "You are welcome, we are your one-stop platform for all\nbills payment, airtime,data plans, and cable tv subscription.\n All our services are available to you at a discount rate.\nOur customer support team is available to you 24/7.";
        $response["vtuaccount"] = "Dann-" . strtoupper(substr($result->sFname, 0, 3));
        $response["pin_set"] = isset($response["pin"]) && $response["pin"] >= 3 ? "yes" : "no";

        return $response;
    } else {
        $response = [];
        $response["status"] = 1;
        return $response;
    }
}

 //Login User Account
    public function loginUserpin($phone, $key)
    {
        $dbh = $this->connect();
        $hash = substr(sha1(md5($key)), 3, 10);

        // Modify query to check if the input is either sPhone or sEmail
        $c = "SELECT * FROM subscribers WHERE (sPhone = :ph OR sEmail = :ph) AND sPin = :p";

        $queryC = $dbh->prepare($c);
        $queryC->bindParam(':ph', $phone, PDO::PARAM_STR);
        $queryC->bindParam(':p', $hash, PDO::PARAM_STR);
        $queryC->execute();

        $result = $queryC->fetch(PDO::FETCH_OBJ);

        if ($queryC->rowCount() > 0) {
            if ($result->sRegStatus == 1) {
                $response = [];
                $response["status"] = 2;
                return $response;
            }
            if ($result->sRegStatus == 4) {
                $response = [];
                $response["status"] = 4;
                return $response;
            }

            $_SESSION["loginId"] = $result->sId;
            $_SESSION["loginName"] = $result->sFname . " " . $result->sLname;
            $_SESSION["loginEmail"] = $result->sEmail;
            $_SESSION["loginPhone"] = $result->sPhone;

            $loginId = base64_encode($result->sId);
            $loginState = base64_encode($result->sState);
            $loginAccount = base64_encode($result->sType);
            $loginPhone = base64_encode($result->sPhone);
            $loginName = base64_encode($result->sFname);
            //Get API Details
            $d = $this->getApiConfiguration();
            $a = $this->getSiteConfiguration();
            $monifyStatus = $this->getConfigValue($d, "monifyStatus");
            $monifyApi = $this->getConfigValue($d, "monifyApi");
            $monifySecrete = $this->getConfigValue($d, "monifySecrete");
            $monifyContract = $this->getConfigValue($d, "monifyContract");
            $adminEmail = $a->email;
            $fname = $result->sFname;
            $lname = $result->sLname;
            $phone = $result->sPhone;
            $email = $result->sEmail;
            $lastInsertId = $result->sId;
            setcookie("loginId", $loginId, time() + 2592000 * 30, "/");
            setcookie("loginState", $loginState, time() + 2592000 * 30, "/");
            setcookie("loginAccount", $loginAccount, time() + 2592000 * 30, "/");
            setcookie("loginPhone", $loginPhone, time() + 31540000 * 30, "/");
            setcookie("loginName", $loginName, time() + 31540000 * 30, "/");

            //Generate User Login Token
            $randomToken = substr(str_shuffle("ABCDEFGHIJklmnopqrstvwxyz"), 0, 10);
            $userLoginToken = time() . $randomToken . mt_rand(100, 1000);

            //Set User Login Token
            $_SESSION["loginAccToken"] = $userLoginToken;

            //Save New User Login Token For One Device Login Check
            //$this->createVirtualBankAccount($lastInsertId,$fname,$lname,$phone,$email,$monifyApi,$monifySecrete,$monifyContract);
            //	$this->createVirtualBankAccount2($lastInsertId,$fname,$lname,$phone,$email,$monifyApi,$monifySecrete,$monifyContract);

            $sqlAc = "INSERT INTO userlogin (user,token) VALUES (:user,:token)";
            $queryAc = $dbh->prepare($sqlAc);
            $queryAc->bindParam(':user', $result->sId, PDO::PARAM_STR);
            $queryAc->bindParam(':token', $userLoginToken, PDO::PARAM_STR);
            $queryAc->execute();
            $response = [];
            $response["status"] = 0;
            $response["Id"] = $result->sId;
            $response["name"] = $result->sFname . " " . $result->sLname;
            $response["phone"] = $result->sPhone;
            $response["email"] = $result->sEmail;
            $response["fname"] = $result->sFname;
            $response["lname"] = $result->sLname;
            $response["pin"] = $result->sPin;
            $response["date"] = $result->sRegDate;
            $response["image"] = $result->sImage;
            $response["address"] = $result->sAddress;
            $response["account_number"] = $result->sRolexBank;
            $response["account_name"] = $result->sFname;
            $response["age"] = $result->sAge;
            $response["sex"] = $result->sSex;
            $response["user_type"] = $result->sType;
            $response["refwallet"] = $result->sRefWallet;
            $response["vercode"] = $result->sVerCode;
            $response["moniepoint"] = $result->sRolexBank;
            $response["payvessel"] = $result->sPayVessel; // Check if this conversion is appropriate
            $response["wema"] = $result->sBankNo; // Removed unnecessary PHP tags
            $response["charges"] = "1.7%";
            $response["username"] = $result->SUsername;
            $response["isbank_verify"] = "yes";
            $response["apikey"] = $result->sApiKey;
            $response["notif"] =
                "You are welcome, we are your one-stop platform for all\nbills payment, airtime,data plans, and cable tv subscription.\n All our services are available to you at a discount rate.\nOur customer support team is available to you 24/7.";
            $response["vtuaccount"] = "Dann-" . strtoupper(substr($result->sFname, 0, 3));

            $response["pin_set"] = isset($response["pin"]) && $response["pin"] >= 3 ? "yes" : "no";

            return $response;
        } else {
            $response = [];
            $response["status"] = 1;
            return $response;
        }
    }
    
 public function registerUserFingerprint($username, $fname, $lname, $email, $phone, $password, $referal, $pin, $dob)
{
    // Verify Registration Details
    $dbh = self::connect();
    $c = "SELECT sEmail, sPhone FROM subscribers WHERE sEmail = :e OR sPhone = :p";
    $queryC = $dbh->prepare($c);
    $queryC->bindParam(':e', $email, PDO::PARAM_STR);
    $queryC->bindParam(':p', $phone, PDO::PARAM_STR);
    $queryC->execute();
    $result = $queryC->fetch(PDO::FETCH_ASSOC);

    // Output Error Message If Data Already Exist
    if ($queryC->rowCount() > 0) {
        if ($result["sPhone"] == $phone) {
            $response = [];
            $response["status"] = "fail";
            $response["msg"] = "Phone Number Already Exists ";
            return $response;
        }
        if ($result["sEmail"] == $email) {
            $response = [];
            $response["status"] = "fail";
            $response["msg"] = "Email Already Exists ";
            return $response;
        }
    }

    // Generate referral code using the same logic as Flutter frontend
    $referralCode = $this->generateReferralCode($phone);

    // Validate referral code if provided
    if (!empty($referal)) {
        $checkReferral = "SELECT sId FROM subscribers WHERE sReferal = :r";
        $queryReferral = $dbh->prepare($checkReferral);
        $queryReferral->bindParam(':r', $referal, PDO::PARAM_STR);
        $queryReferral->execute();
        if ($queryReferral->rowCount() == 0) {
            $response = [];
            $response["status"] = "fail";
            $response["msg"] = "Invalid Referral Code";
            return $response;
        }
    }

    // Generate username (optional, if still needed)
    $username = $fname . "dannvtu" . rand(1000, 9999);

    $hash = substr(sha1(md5($password)), 3, 10);
    $apiKey = substr(str_shuffle("0123456789ABCDEFGHIJklmnopqrstvwxyzAbAcAdAeAfAgAhBaBbBcBdC1C23C3C4C5C6C7C8C9xix2x3"), 0, 60) . time();

    // ✅ UPDATED: Added sDOB to INSERT
    $sql = "INSERT INTO subscribers (SUsername, sFname, sLname, sEmail, sPhone, sPass, sReferal, sApiKey, sRegStatus, sPin, sDOB) VALUES (:username, :fname, :lname, :email, :phone, :pass, :r, :k, 0, :pin, :dob)";

    $query = $dbh->prepare($sql);
    $query->bindParam(':username', $username, PDO::PARAM_STR);
    $query->bindParam(':fname', $fname, PDO::PARAM_STR);
    $query->bindParam(':lname', $lname, PDO::PARAM_STR);
    $query->bindParam(':email', $email, PDO::PARAM_STR);
    $query->bindParam(':phone', $phone, PDO::PARAM_STR);
    $query->bindParam(':pass', $hash, PDO::PARAM_STR);
    $query->bindParam(':r', $referralCode, PDO::PARAM_STR);
    $query->bindParam(':pin', $pin, PDO::PARAM_STR);
    $query->bindParam(':dob', $dob, PDO::PARAM_STR); // ✅ NEW: Bind DOB
    $query->bindParam(':k', $apiKey, PDO::PARAM_STR);

    $result = $query->execute();

    $lastInsertId = $dbh->lastInsertId();

    if ($lastInsertId) {
        $data = 0;

        // Session and cookie handling
        if ($saveCookies) {
            $_SESSION["loginId"] = $lastInsertId;
            $_SESSION["loginName"] = $fname . " " . $lname;
            $_SESSION["loginEmail"] = $email;
            $_SESSION["loginPhone"] = $phone;

            $loginId = base64_encode($lastInsertId);
            $loginState = base64_encode($state);
            $loginPhone = base64_encode($phone);
            $loginAccount = base64_encode("1");
            $loginName = base64_encode($fname);

            $_SESSION["loginName"] = $fname;
            setcookie("loginId", $loginId, time() + 2592000 * 30, "/");
            setcookie("loginState", $loginState, time() + 2592000 * 30, "/");
            setcookie("loginAccount", $loginAccount, time() + 2592000 * 30, "/");
            setcookie("loginPhone", $loginPhone, time() + 31540000 * 30, "/");
            setcookie("loginName", $loginName, time() + 31540000 * 30, "/");

            // Generate User Login Token
            $randomToken = substr(str_shuffle("ABCDEFGHIJklmnopqrstvwxyz"), 0, 10);
            $userLoginToken = time() . $randomToken . mt_rand(100, 1000);

            // Set User Login Token
            $_SESSION["loginAccToken"] = $userLoginToken;

            // Save New User Login Token For One Device Login Check
            $sqlAc = "INSERT INTO userlogin (user,token) VALUES (:user,:token)";
            $queryAc = $dbh->prepare($sqlAc);
            $queryAc->bindParam(':user', $lastInsertId, PDO::PARAM_STR);
            $queryAc->bindParam(':token', $userLoginToken, PDO::PARAM_STR);
            $queryAc->execute();
        }
        

        // Login Notification and API Details
        $da = $this->getApiConfiguration();
        $a = $this->getSiteConfiguration();
        $payvessel = $this->getConfigValue($da, "monifyStatus");
        $payvesselapi = $this->getConfigValue($da, "billstackApi");
        $payvesselsecret = $this->getConfigValue($da, "payvesselSecret");
        $payvesselbusinessid = $this->getConfigValue($da, "payvesselBusinessId");
        $uFname = $fname;
        $uEmail = $email;
        $uLname = $lname;
        $uPhone = $phone;
        $uId = $lastInsertId;
$this->createAccountBillstackPalmpay($uId,$uEmail,$uPhone,$uFname,$uLname, $payvesselapi);
        // Send Email To User (commented out in original code)
        // $this->createpayvessel($uId, $uFname, $uLname, $uPhone, $uEmail, $payvesselapi, $payvesselsecret, $payvesselbusinessid);

        $d = $this->getApiConfiguration();
        $a = $this->getSiteConfiguration();
        $monifyStatus = $this->getConfigValue($d, "monifyStatus");
        $monifyApi = $this->getConfigValue($d, "monifyApi");
        $monifySecrete = $this->getConfigValue($d, "monifySecrete");
        $monifyContract = $this->getConfigValue($d, "monifyContract");
        $adminEmail = $a->email;

        $response = [];
        $response["status"] = "success";
        $response["user_id"] = $lastInsertId;
        $response["api_key"] = $apiKey;
        $response["referral_code"] = $referralCode;
        $response["msg"] = "Account Successfully Registered";
        return $response; // Code 0: Registration successful
    } else {
        $response = [];
        $response["status"] = "fail";
        $response["msg"] = "Registration Failed";
        return $response; // Code 4: Registration failed
    }
}


  
    public function createAccountBillstackPalmpay($id, $email, $phone, $firstName, $lastName, $token) {
    $url = 'https://api.billstack.co/v2/thirdparty/generateVirtualAccount/';
    
    // Generate a unique reference
    $ref = uniqid() . rand(1000, 9000);
    $data = [
        'reference' => $ref,
        'email' => $email,
        'phone' => $phone,
        'firstName' => $firstName,
        'lastName' => $lastName,
        'bank' => 'PALMPAY'
    ];
    
    // Set headers
    $headers = [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $token
    ];

    // Initialize cURL
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    // Execute and get response
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    file_put_contents("data_error_log2.txt", json_encode($response)); // Log the raw response

    // Close cURL session
    curl_close($ch);

    // Check HTTP response code and handle response
    if ($httpCode == 200) {
        $responseData = json_decode($response, true);

        // Check if account information is available
        if (isset($responseData['data']['account'][0]['account_number'])) {
            $accountNumber = $responseData['data']['account'][0]['account_number'];

            // Establish database connection
            $dbh = self::connect();
            if ($dbh) {  // Check if database connection is successful
                $c = "UPDATE subscribers SET sPalmpay = :fb WHERE sId = :id";
                $queryC = $dbh->prepare($c);
                $queryC->bindParam(':fb', $accountNumber, PDO::PARAM_STR);
                $queryC->bindParam(':id', $id, PDO::PARAM_INT);
                
                // Execute the update query and check if successful
                if ($queryC->execute()) {
                    return "Account number successfully updated in the database.";
                } else {
                    return "Failed to update account number in the database.";
                }
            } else {
                return "Database connection failed.";
            }
        } else {
            return "Account number not found in the API response.";
        }
    } else {
        return "Failed API request with HTTP Code: " . $httpCode;
    }
}
// Helper function to generate referral code
private function generateReferralCode($phoneNumber)
{
    // Remove any non-numeric characters
    $cleanPhone = preg_replace('/[^0-9]/', '', $phoneNumber);

    // Create a simple hash using the phone number
    $hash = 0;
    for ($i = 0; $i < strlen($cleanPhone); $i++) {
        $hash = $hash * 31 + ord($cleanPhone[$i]);
        $hash = $hash & 0x7FFFFFFF; // Keep it positive
    }

    // Convert to base 36 (numbers + letters) and pad to 10 characters
    $encoded = strtoupper(base_convert($hash, 10, 36));

    // Ensure exactly 10 characters by padding or truncating
    if (strlen($encoded) < 10) {
        $encoded = str_pad($encoded, 10, '0', STR_PAD_LEFT);
    } elseif (strlen($encoded) > 10) {
        $encoded = substr($encoded, 0, 10);
    }

    // Ensure uniqueness by checking the database
    $dbh = self::connect();
    $checkUnique = "SELECT sReferal FROM subscribers WHERE sReferal = :r";
    $queryUnique = $dbh->prepare($checkUnique);
    $queryUnique->bindParam(':r', $encoded, PDO::PARAM_STR);
    $queryUnique->execute();

    if ($queryUnique->rowCount() > 0) {
        // If code exists, append a random number and recheck
        $encoded = substr($encoded, 0, 8) . rand(10, 99);
        return $this->generateReferralCode($phoneNumber . rand(0, 9)); // Recursive call with modified input
    }

    return $encoded;
}

    //Login User Account
    public function loginUser($phone, $key)
    {
        //Verify Registration Details
        $dbh = self::connect();
        $hash = substr(sha1(md5($key)), 3, 10);
        $c = "SELECT sId,sFname,sLname,sEmail,sPass,sPhone,sState,sType,sRegStatus FROM subscribers WHERE sPhone=:ph AND sPass=:p";
        $queryC = $dbh->prepare($c);
        $queryC->bindParam(':ph', $phone, PDO::PARAM_STR);
        $queryC->bindParam(':p', $hash, PDO::PARAM_STR);
        $queryC->execute();
        $result = $queryC->fetch(PDO::FETCH_OBJ);
        if ($queryC->rowCount() > 0) {
            if ($result->sRegStatus == 1) {
                return 2;
            }

            $_SESSION["loginId"] = $result->sId;

            $_SESSION["loginName"] = $result->sFname . " " . $result->sLname;
            $_SESSION["loginEmail"] = $result->sEmail;
            $_SESSION["loginPhone"] = $result->sPhone;
            $uId = $result->sId;
            $uFname = $result->sFname;
            $uLname = $result->sLname;
            $uPhone = $result->sPhone;
            $uEmail = $result->sEmail;

            $loginId = base64_encode($result->sId);
            $loginState = base64_encode($result->sState);
            $loginAccount = base64_encode($result->sType);
            $loginPhone = base64_encode($result->sPhone);
            $loginName = base64_encode($result->sFname);

            setcookie("loginId", $loginId, time() + 2592000 * 30, "/");
            setcookie("loginState", $loginState, time() + 2592000 * 30, "/");
            setcookie("loginAccount", $loginAccount, time() + 2592000 * 30, "/");
            setcookie("loginPhone", $loginPhone, time() + 31540000 * 30, "/");
            setcookie("loginName", $loginName, time() + 31540000 * 30, "/");

            //Generate User Login Token
            $randomToken = substr(str_shuffle("ABCDEFGHIJklmnopqrstvwxyz"), 0, 10);
            $userLoginToken = time() . $randomToken . mt_rand(100, 1000);

            //Set User Login Token
            $_SESSION["loginAccToken"] = $userLoginToken;

            //Save New User Login Token For One Device Login Check

            $sqlAc = "INSERT INTO userlogin (user,token) VALUES (:user,:token)";
            $queryAc = $dbh->prepare($sqlAc);
            $queryAc->bindParam(':user', $result->sId, PDO::PARAM_STR);
            $queryAc->bindParam(':token', $userLoginToken, PDO::PARAM_STR);
            $queryAc->execute();

            // Send Email To User
            $subjecte = "Login Notification - {$this->sitename}";
            $messagee =
                '
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
            background-color: #ffffff;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        .header {
            text-align: center;
        }
        .logo {
            width: 120px;
            height: auto;
        }
        .message {
            margin-top: 20px;
            padding: 20px;
            background-color: #f0f0f0;
            border-radius: 5px;
        }
        .details {
            margin-top: 20px;
            padding: 10px;
            background-color: #f9f9f9;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <img src="https://i.ibb.co/gdf9B6G/20230815-082511.png" alt="Logo" class="logo">
            <h2>Login Notification</h2>
        </div>
        <div class="message">
            <p>Hello ' .
                $result->sFname .
                ',</p>
            <p>This is a login notification from ' .
                $this->sitename .
                '. We wanted to inform you that your account was recently accessed.</p>
            <p>If you didn\'t initiate this login, please contact our customer support on dannvtu@gmail.com immediately.</p>
        </div>
        <div class="details">
            <h3>Device Information</h3>
            <p><strong>Device:</strong> ' .
                $_SERVER["HTTP_USER_AGENT"] .
                '</p>
            <p><strong>IP Address:</strong> ' .
                $_SERVER["REMOTE_ADDR"] .
                '</p>
            <p><strong>Date and Time:</strong> ' .
                date("Y-m-d H:i:s") .
                '</p>
        </div>
        <p>Thank you for choosing ' .
                $this->sitename .
                '.</p>
        <p>Best regards,<br>The ' .
                $this->sitename .
                ' Team</p>
    </div>
</body>
</html>
';

            //Login Notification
            //Get API Details
            $da = $this->getApiConfiguration();
            $a = $this->getSiteConfiguration();
            $payvessel = $this->getConfigValue($da, "monifyStatus");
            $payvesselapi = $this->getConfigValue($da, "PayvesselApi");
            $payvesselsecret = $this->getConfigValue($da, "PayvesselApiSecret");
            $payvesselbusinessid = $this->getConfigValue($da, "PayvesselWebhookBusinessID");
            $uFname = $result->sFname;
            $uEmail = $result->sEmail;
            $uLname = $result->sLname;
            $uPhone = $result->sPhone;
            $uId = $result->sId;

            //Send Email To User
            $this->createpayvessel($uId, $uFname, $uLname, $uPhone, $uEmail, $payvesselapi, $payvesselsecret, $payvesselbusinessid);

            // Send the notification email to user and admin respectively
            $this->executePaystackAPI($uId, $uFname, $uLname, $uPhone, $uEmail);
            $check = self::sendMail($result->sEmail, $subjecte, $messagee);
            $adminEmails = "dannvtu@gmail.com";
            $check = self::sendMail($adminEmails, $subjecte, $messagee);

            return 0;
        } else {
            return 1;
        }
    }

    //Recover User Account
    public function recoverUserLogin($email)
    {
        //Verify Registration Details
        $dbh = self::connect();
        $c = "SELECT sId,sFname,sLname,sEmail,sPass FROM subscribers WHERE sEmail=:e";
        $queryC = $dbh->prepare($c);
        $queryC->bindParam(':e', $email, PDO::PARAM_STR);
        $queryC->execute();
        $result = $queryC->fetch(PDO::FETCH_OBJ);
        if ($queryC->rowCount() > 0) {
            //Genereate And Update Verification Code
            $varCode = mt_rand(2000, 9000);
            $stmt = "UPDATE subscribers SET sVerCode=$varCode WHERE sId=$result->sId";
            $query = $dbh->prepare($stmt);
            $query->execute();

            //Send Verification Code To User Email
            $email = $result->sEmail;
            $subject = "Account Recovery (" . $this->sitename . ")";
            $message = "<h3>Hi " . $result->sFname . ", You Recently Requested For A Password Recovery. Use The Verification Code \"" . $varCode . "\" To Recover Your Account. Thank You For Using " . $this->sitename . ".</h3>";
            $check = self::sendMail($email, $subject, $message);

            if ($check == 0) {
                return 0;
            } else {
                return 2;
            }
        } else {
            return 1;
        }
    }

    //Recover User Account
    public function recoverUserLogins($email)
    {
        //Verify Registration Details
        $dbh = self::connect();
        $c = "SELECT * FROM subscribers WHERE sEmail=:e";
        $queryC = $dbh->prepare($c);
        $queryC->bindParam(':e', $email, PDO::PARAM_STR);
        $queryC->execute();
        $result = $queryC->fetch(PDO::FETCH_OBJ);
        if ($queryC->rowCount() > 0) {
            //Genereate And Update Verification Code
            $varCode = mt_rand(2000, 9000);
            $stmt = "UPDATE subscribers SET sVerCode=$varCode WHERE sId=$result->sId";
            $query = $dbh->prepare($stmt);
            $query->execute();

            //Send Verification Code To User Email
            $email = $result->sEmail;
            //	$subject="Account Recovery (".$this->sitename.")";
            //	$message="<h3>Hi ".$result->sFname.", Use The Verification Code \"".$varCode."\" To Recover Your Account. Thank You For Using ".$this->sitename.".</h3>";
            $subject = "Verification Code";

            $message =
                "
<!DOCTYPE html>
<html>
<head>
    <title>Account Recovery</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 20px;
        }
        .container {
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
            background-color: #fff;
            text-align: center;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        .header {
            text-align: center;
            margin-bottom: 20px;
        }
        .logo {
            max-width: 60px;
            margin-bottom: 20px;
        }
        .verification-image {
            max-width: 90%;
            margin-bottom: 20px;
             text-align: center;
        }
        .address {
            margin-top: 20px;
            text-align: center;
        }
        .caution {
            color: #f00;
            font-size: 10px;
            
            margin-top: 20px;
            text-align: center;
        }
         .caution1 {
    
            font-size: 15px;
            
            margin-top: 20px;
            text-align: center;
        }
        .social-icons {
            text-align: center;
            margin-top: 20px;
        }
        .social-icons a {
            display: inline-block;
            margin-right: 10px;
        }
    </style>
</head>
<body>
    <div class='container'>
        <div class='header'>
  
            <h1>Account Verification</h1>
        </div>
        <img src='https://mabrooktelecoms.com/assets/images/icons/email-verification.png' alt='Verification Image' class='verification-image'>
        <h2>Hi " .
                $result->sFname .
                ",</h2>
         <div class='caution1'>
      <p>
We're pleased to inform you that a verification code has been generated for your account. This code is required to complete a verification process, ensuring the security of your account.<br><br>
<strong style='font-size: 20px;'>Verification Code: " .
                $varCode .
                "</strong><br><br>
</p>
 </div>
        <div class='address'>
            <p>Mabrook Telecoms, Nigeria</p>
        </div>
        <div class='caution'>
          <p>You received this email because you are a registered user of Mabrook Telecoms. If you think this email was sent to you in error or if you did not create an account with Mabrook Telecoms, please ignore this message.</p>
        </div>
      
    </div>
</body>
</html>";

            $check = self::sendMail($email, $subject, $message);

            if ($check == 0) {
                $response = [];

                $response["status"] = "success";
                $response["status_msg"] = "Verification Code Sent";
                $response["id"] = $result->sId;

                $response["vercode"] = strval($varCode);

                $jsonString = json_encode($response, JSON_UNESCAPED_SLASHES);
                return $jsonString;
            } else {
                $data = [
                    "status" => "fail",
                    "status_msg" => "Account Not Found",
                ];
                $jsonString = json_encode($data, JSON_UNESCAPED_SLASHES);
                return $jsonString;
            }
        } else {
            $data = [
                "status" => "fail",
                "status_msg" => "Unable to process request" . $email,
            ];
            $jsonString = json_encode($data, JSON_UNESCAPED_SLASHES);
            return $jsonString;
        }
    }

    //Recover User Account
    public function verifyRecoveryCode($email, $code)
    {
        //Verify Registration Details
        $dbh = self::connect();
        $c = "SELECT sId FROM subscribers WHERE sEmail=:e AND sVerCode=:c";
        $queryC = $dbh->prepare($c);
        $queryC->bindParam(':e', $email, PDO::PARAM_STR);
        $queryC->bindParam(':c', $code, PDO::PARAM_STR);
        $queryC->execute();
        if ($queryC->rowCount() > 0) {
            return 0;
        } else {
            return 1;
        }
    }

    //Recover Seller Account
    public function updateUserKey($email, $code, $key)
    {
        //Verify Registration Details
        $dbh = self::connect();
        $hash = substr(sha1(md5($key)), 3, 10);
        $verCode = mt_rand(1000, 9999);
        $c = "UPDATE subscribers SET sPass=:k,sVerCode=:v WHERE sEmail=:e AND sVerCode=:c";
        $queryC = $dbh->prepare($c);
        $queryC->bindParam(':e', $email, PDO::PARAM_STR);
        $queryC->bindParam(':c', $code, PDO::PARAM_STR);
        $queryC->bindParam(':k', $hash, PDO::PARAM_STR);
        $queryC->bindParam(':v', $verCode, PDO::PARAM_INT);
        if ($queryC->execute()) {
            return 0;
        } else {
            return 1;
        }
    }

    // Create Virtual Bank Account
    public function executePaystackAPI($uId, $uFname, $uLname, $uPhone, $uEmail)
    {
        // Get Authorization Data
        $authUrl = 'https://services2.vpay.africa/api/service/v1/query/merchant/login';
        $accountUrl = "https://services2.vpay.africa/api/service/v1/query/customer/add";

        // Initialize the first cURL session for authorization
        $authCh = curl_init();
        curl_setopt_array($authCh, [
            CURLOPT_URL => $authUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => json_encode([
                "username" => "dannyshedrack35@gmail.com",
                "password" => "Dannybo55$$",
            ]),
            CURLOPT_HTTPHEADER => ["content-type: application/json", "publicKey: c33c1f94-a466-43ef-bb33-321021e7d7dc", "cache-control: no-cache"],
        ]);

        // Execute the authorization request
        $authJson = curl_exec($authCh);
        $authResult = json_decode($authJson);
        curl_close($authCh);

        // Check if the authorization was successful
        if ($authResult && isset($authResult->token)) {
            $accessToken = $authResult->token;
            $ref = uniqid() . rand(1000, 9000);

            // Request Account Creation
            $accountCh = curl_init();

            curl_setopt_array($accountCh, [
                CURLOPT_URL => $accountUrl,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS =>
                    '{
                    "email": "' .
                    $uEmail .
                    '",
                    "phone": "' .
                    $uPhone .
                    '",
                    "contactlastname": "' .
                    $uLname .
                    '",
                    "contactfirstname": "' .
                    $uFname .
                    '"
                }',
                CURLOPT_HTTPHEADER => ["publicKey: c33c1f94-a466-43ef-bb33-321021e7d7dc", "b-access-token: " . $accessToken, "content-type: application/json", "cache-control: no-cache"],
            ]);

            // Execute the account creation request
            $response = curl_exec($accountCh);
            curl_close($accountCh);

            $data = json_decode($response, true);

            if (isset($data['id'])) {
                $customerId = $data['id'];

                // Use the extracted 'customerId' in the URL for the third GET request
                $thirdUrl = "https://services2.vpay.africa/api/service/v1/query/customer/$customerId/show";

                $thirdCurl = curl_init();
                curl_setopt_array($thirdCurl, [
                    CURLOPT_URL => $thirdUrl,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_HTTPHEADER => ["publicKey: c33c1f94-a466-43ef-bb33-321021e7d7dc", "b-access-token: " . $accessToken, "content-type: application/json", "cache-control: no-cache"],
                ]);

                $thirdResponse = curl_exec($thirdCurl);
                curl_close($thirdCurl);
                $finalData = json_decode($thirdResponse, true);

                $bankName = $finalData['nuban'];

                // Use prepared statements to update the database to prevent SQL injection
                $dbh = self::connect();
                $c = "UPDATE subscribers SET sVBank=:fb WHERE sId=:uId";
                $queryC = $dbh->prepare($c);
                $queryC->bindParam(':fb', $bankName, PDO::PARAM_STR);
                $queryC->bindParam(':uId', $uId, PDO::PARAM_INT);
                $queryC->execute();
            }
        }
    }

    // Call the function to execute the Paystack API

    public function generatevpayaccount($sId, $sFname, $sLname, $sPhone, $sEmail)
    {
        $url = 'https://services2.vpay.africa/api/service/v1/query/merchant/login';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ["content-type: application/json", "publicKey: c33c1f94-a466-43ef-bb33-321021e7d7dc", "cache-control: no-cache"]);

        // Add username and password as POST fields
        $postFields = [
            "username" => "dannyshedrack35@gmail.com",
            "password" => "Dannybo55$$",
        ];
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postFields));

        $json = curl_exec($ch);
        curl_close($ch);

        $result = json_decode($json, true);
        $accessToken = $result['token'];

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => "https://services2.vpay.africa/api/service/v1/query/customer/add",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode([
                "email" => "'.$sEmail.'",
                "phone" => "'.$sPhone.'",
                "contactlastname" => "Dannvtu",
                "contactfirstname" => "'.$sFname.'",
            ]),
            CURLOPT_HTTPHEADER => ["publicKey: c33c1f94-a466-43ef-bb33-321021e7d7dc", "b-access-token: " . $accessToken, "content-type: application/json", "cache-control: no-cache"],
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);

        if ($err) {
            // There was an error contacting the Paystack API
            $theresponse["status"] = "fail";
            $theresponse["msg"] = 'Curl Returned Error: ' . $err;
            file_put_contents("data_error_log2.txt", json_encode($response) . " " . $err . " " . $host);
        } else {
            // Output the response from the API
            // Extract 'customerId' from the second response
            $secondResponseData = json_decode($response, true);
            $customerId = $secondResponseData['id'];

            // Use the extracted 'customerId' in the URL for the third GET request
            $thirdUrl = "https://services2.vpay.africa/api/service/v1/query/customer/$customerId/show";

            $thirdCurl = curl_init();
            curl_setopt_array($thirdCurl, [
                CURLOPT_URL => $thirdUrl,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPHEADER => ["publicKey: c33c1f94-a466-43ef-bb33-321021e7d7dc", "b-access-token: " . $accessToken, "content-type: application/json", "cache-control: no-cache"],
            ]);

            $thirdResponse = curl_exec($thirdCurl);
            $thirdErr = curl_error($thirdCurl);

            if ($thirdErr) {
                // Handle errors for the third GET request...
            } else {
                // Parse the JSON response from the third GET request
                $thirdResponseData = json_decode($thirdResponse, true);

                if (isset($thirdResponseData['virtualaccounts']) && is_array($thirdResponseData['virtualaccounts'])) {
                    // Assuming you want to save the first virtual account's bank and NUBAN
                    if (count($thirdResponseData['virtualaccounts']) > 0) {
                        $firstVirtualAccount = $thirdResponseData['virtualaccounts'][0];
                        $bankName = $firstVirtualAccount['nuban'];

                        // Update the database with the bank name
                        $dbh = self::connect();
                        $c = "UPDATE subscribers SET sVBank=:fb WHERE sId=$sId";
                        $queryC = $dbh->prepare($c);
                        $queryC->bindParam(':fb', $bankName, PDO::PARAM_STR);
                        $queryC->execute();
                    }
                }

                // Output the response from the third GET request...
            }

            curl_close($thirdCurl);
        }

        curl_close($curl);
    }

    // Create Virtual Bank Account
    public function createVirtualBankAccount($id, $fname, $lname, $phone, $email, $nin, $bvn, $monnifyApi, $monnifySecret, $monnifyContract)
    {
        $fullname = $fname . " " . $lname;
        $accessKey = "$monnifyApi:$monnifySecret";
        $apiKey = base64_encode($accessKey);

        $authUrl = 'https://api.monnify.com/api/v1/auth/login';
        $accountCreationUrl = 'https://api.monnify.com/api/v2/bank-transfer/reserved-accounts';

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $authUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_HTTPHEADER => ["Authorization: Basic {$apiKey}"],
        ]);

        $authResponse = curl_exec($ch);
        $authResult = json_decode($authResponse);
        curl_close($ch);

        $accessToken = $authResult->responseBody->accessToken;

        $ref = uniqid() . rand(1000, 9000);
        $accountData = [
            "accountReference" => $ref,
            "accountName" => $fullname,
            "currencyCode" => "NGN",
            "contractCode" => $monnifyContract,
            "customerEmail" => $email,
            "customerName" => $fullname,
            "getAllAvailableBanks" => false,
            "preferredBanks" => ["035"],
        ];
        if (!empty($bvn)) {
            $accountData["bvn"] = $bvn;
        } elseif (!empty($nin)) {
            $accountData["nin"] = $nin;
        }

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $accountCreationUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => json_encode($accountData),
            CURLOPT_HTTPHEADER => ["Authorization: Bearer " . $accessToken, "Content-Type: application/json"],
        ]);

        $accountResponse = curl_exec($curl);
        curl_close($curl);

        $accountResult = json_decode($accountResponse, true);
        file_put_contents('tokne.txt', json_encode($accountResult));
        if (isset($accountResult["requestSuccessful"]) && $accountResult["requestSuccessful"] === true) {
            $account_name = $accountResult["responseBody"]["accountName"];
            $bankDetails = $accountResult["responseBody"]["accounts"][0];

            if ($bankDetails["bankCode"] == "035") {
                $wemaAccountNumber = $bankDetails["accountNumber"];
                $wemaBankName = $bankDetails["bankName"];

                $dbh = self::connect();
                $updateQuery = "UPDATE subscribers SET sBankName=:bn, sBankNo=:bno, sAccountReference=:ref WHERE sId=:id";
                $queryC = $dbh->prepare($updateQuery);
                $queryC->bindParam(':bn', $wemaBankName, PDO::PARAM_STR);
                $queryC->bindParam(':bno', $wemaAccountNumber, PDO::PARAM_STR);
                $queryC->bindParam(':ref', $ref, PDO::PARAM_STR);
                $queryC->bindParam(':id', $id, PDO::PARAM_INT);
                $queryC->execute();
            }
        } else {
            // throw new Exception('Failed to create virtual account: ' . json_encode($accountResult));
        }
    }

    // Create Virtual Bank Account
    public function createVirtualBankAccount2($id, $fname, $lname, $phone, $email, $nin, $bvn, $monnifyApi, $monnifySecret, $monnifyContract)
    {
        $fullname = $fname . " " . $lname;
        $accessKey = "$monnifyApi:$monnifySecret";
        $apiKey = base64_encode($accessKey);

        $authUrl = 'https://api.monnify.com/api/v1/auth/login';
        $accountCreationUrl = 'https://api.monnify.com/api/v2/bank-transfer/reserved-accounts';

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $authUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_HTTPHEADER => ["Authorization: Basic {$apiKey}"],
        ]);

        $authResponse = curl_exec($ch);
        $authResult = json_decode($authResponse);
        curl_close($ch);

        $accessToken = $authResult->responseBody->accessToken;
        $ref = uniqid() . rand(1000, 9000);

        $accountData = [
            "accountReference" => $ref,
            "accountName" => $fullname,
            "currencyCode" => "NGN",
            "contractCode" => $monnifyContract,
            "customerEmail" => $email,
            "customerName" => $fullname,
            "getAllAvailableBanks" => false,
            "preferredBanks" => ["50515", "232"],
        ];

        if (!empty($bvn)) {
            $accountData["bvn"] = $bvn;
        } elseif (!empty($nin)) {
            $accountData["nin"] = $nin;
        }

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $accountCreationUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => json_encode($accountData),
            CURLOPT_HTTPHEADER => ["Authorization: Bearer " . $accessToken, "Content-Type: application/json"],
        ]);

        $accountResponse = curl_exec($curl);
        curl_close($curl);
        $accountResult = json_decode($accountResponse, true);

        if (isset($accountResult["requestSuccessful"]) && $accountResult["requestSuccessful"] === true) {
            $rolex = $sterling = "";

            foreach ($accountResult["responseBody"]["accounts"] as $account) {
                if ($account["bankCode"] == "50515") {
                    $rolex = $account["accountNumber"];
                } elseif ($account["bankCode"] == "232") {
                    $sterling = $account["accountNumber"];
                }
            }

            $dbh = self::connect();
            $queryC = $dbh->prepare("UPDATE subscribers SET sRolexBank=:rb, sSterlingBank=:sb, sAccountReference=:ref WHERE sId=:id");
            $queryC->bindParam(':rb', $rolex, PDO::PARAM_STR);
            $queryC->bindParam(':sb', $sterling, PDO::PARAM_STR);
            $queryC->bindParam(':ref', $ref, PDO::PARAM_STR);
            $queryC->bindParam(':id', $id, PDO::PARAM_INT);
            $queryC->execute();
        } else {
            //   throw new Exception('Failed to create virtual account: ' . json_encode($accountResult));
        }
    }

    // Create Virtual Bank Account (Method 3)
    public function createVirtualBankAccount3($id, $fname, $lname, $phone, $email, $nin, $bvn, $monnifyApi, $monnifySecret, $monnifyContract)
    {
        $fullname = $fname . " " . $lname;
        $accessKey = "$monnifyApi:$monnifySecret";
        $apiKey = base64_encode($accessKey);

        $authUrl = 'https://api.monnify.com/api/v1/auth/login';
        $accountCreationUrl = 'https://api.monnify.com/api/v2/bank-transfer/reserved-accounts';

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $authUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_HTTPHEADER => ["Authorization: Basic {$apiKey}"],
        ]);

        $authResponse = curl_exec($ch);
        $authResult = json_decode($authResponse);
        curl_close($ch);

        $accessToken = $authResult->responseBody->accessToken;
        $ref = uniqid() . rand(1000, 9000);

        $accountData = [
            "accountReference" => $ref,
            "accountName" => $fullname,
            "currencyCode" => "NGN",
            "contractCode" => $monnifyContract,
            "customerEmail" => $email,
            "customerName" => $fullname,
            "getAllAvailableBanks" => false,
            "preferredBanks" => ["070"], // Fidelity Bank
        ];

        if (!empty($bvn)) {
            $accountData["bvn"] = $bvn;
        } elseif (!empty($nin)) {
            $accountData["nin"] = $nin;
        }

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $accountCreationUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => json_encode($accountData),
            CURLOPT_HTTPHEADER => ["Authorization: Bearer " . $accessToken, "Content-Type: application/json"],
        ]);

        $accountResponse = curl_exec($curl);
        curl_close($curl);
        $accountResult = json_decode($accountResponse, true);

        if (isset($accountResult["requestSuccessful"]) && $accountResult["requestSuccessful"] === true) {
            $fidelityBank = "";

            foreach ($accountResult["responseBody"]["accounts"] as $account) {
                if ($account["bankCode"] == "070") {
                    $fidelityBank = $account["accountNumber"];
                }
            }

            $dbh = self::connect();
            $queryC = $dbh->prepare("UPDATE subscribers SET sFidelityBank=:fb WHERE sId=:id");
            $queryC->bindParam(':fb', $fidelityBank, PDO::PARAM_STR);
            $queryC->bindParam(':id', $id, PDO::PARAM_INT);
            $queryC->execute();
        } else {
            //   throw new Exception('Failed to create virtual account: ' . json_encode($accountResult));
        }
    }

    //Create Kuda Virtual Bank Account
    public function generateKudaAccount($id, $fname, $lname, $phone, $email, $verificationType, $value, $type, $kudaApi, $kudaEmail)
    {
        //Get Authorization Data
        $url = 'https://kuda-openapi.kuda.com/v2.1/Account/GetToken/';
        $url2 = "https://kuda-openapi.kuda.com/v2.1/";

        //Get Token

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS =>
                '{
											"email": "' .
                $kudaEmail .
                '",
											"apiKey": "' .
                $kudaApi .
                '"
									}',
            CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
        ]);

        $result = curl_exec($ch);
        curl_close($ch);

        $accessToken = $result;
        $ref = "REQ_" . uniqid() . rand(1000, 9000);

        //Check Is User Have Middle Name
        $secondname = explode(" ", $lname);

        if (isset($secondname[0])):
            $lname = $secondname[0];
        endif;
        if (isset($secondname[1])):
            $mname = $secondname[1];
        else:
            $mname = "";
        endif;
        $fname = str_replace(" ", "", $fname);
        $lname = str_replace(" ", "", $lname);
        $mname = str_replace(" ", "", $mname);
        $fname = trim($fname);
        $lname = trim($lname);
        $mname = trim($mname);
        $phone = trim($phone);
        $email = str_replace(" ", "", $email);

        //Request Account Creation
        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => $url2,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS =>
                '{
                                    	 "ServiceType": "ADMIN_CREATE_VIRTUAL_ACCOUNT",
    "RequestRef": "' .
                $ref .
                '",
    "Data": {
        "email": "' .
                $email .
                '",
        "phoneNumber": "' .
                $phone .
                '",
        "lastName": "' .
                $lname .
                '",
        "firstName": "' .
                $fname .
                '",
        "middleName": "' .
                $mname .
                '",
        "VerificationType": "' .
                $verificationType .
                '",
        "' .
                ($type === "NIN" ? "IdType" : "") .
                '": "' .
                ($type === "NIN" ? "1" : "") .
                '",
        "' .
                $type .
                '": "' .
                $value .
                '",
        "businessName": "",
        "trackingReference": "' .
                $email .
                '"
                                    			}
                                    }
                                ',
            CURLOPT_HTTPHEADER => ["Authorization: Bearer " . $accessToken, "Content-Type: application/json"],
        ]);

        $response = curl_exec($curl);
        curl_close($curl);
        $value = json_decode($response);

        //Check And Save Account Details
        if (isset($value->data->accountNumber)) {
            $accountNumber = $value->data->accountNumber;

            //Save Account Number

            $dbh = $this->connect();
            $c = "UPDATE subscribers SET sKuda=:kb WHERE sId=$id";
            $queryC = $dbh->prepare($c);
            $queryC->bindParam(':kb', $accountNumber, PDO::PARAM_STR);
            $queryC->execute();
        }
        return $value;
    }

    //Complete Kuda Funding And Withdraw Funds From Virtual Account To Main Admin Wallet
    public function completeKudaFundingByWithdrawal($amount, $useremail)
    {
        $dbh = $this->connect();

        //Get API Details
        $d = $this->getApiConfiguration();
        $kudaStatus = $this->getConfigValue($d, "kudaStatus");
        $kudaEmail = $this->getConfigValue($d, "kudaEmail");
        $kudaApi = $this->getConfigValue($d, "kudaApi");

        //Get Authorization Data
        $url = 'https://kuda-openapi.kuda.com/v2.1/Account/GetToken/';
        $url2 = "https://kuda-openapi.kuda.com/v2.1/";

        //Get Token

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS =>
                '{
											"email": "' .
                $kudaEmail .
                '",
											"apiKey": "' .
                $kudaApi .
                '"
									}',
            CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
        ]);

        $result = curl_exec($ch);
        curl_close($ch);

        $accessToken = $result;
        $ref = "REQ_" . uniqid() . rand(1000, 9000);

        //Request Account Creation
        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => $url2,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS =>
                '{
                                    		"ServiceType":"WITHDRAW_VIRTUAL_ACCOUNT",
                                    		"RequestRef":"' .
                $ref .
                '",
                                    		"Data":
                                    			{
                                    				"trackingReference": "' .
                $useremail .
                '",
                                    				"amount": "' .
                $amount .
                '",
                                    				"narration": "Virtual Account Withdrawal",
                                    				"ClientFeeCharge": 0
                                    			}
                                    }
                                ',
            CURLOPT_HTTPHEADER => ["Authorization: Bearer " . $accessToken, "Content-Type: application/json"],
        ]);

        $response = curl_exec($curl);
        curl_close($curl);
        $value = json_decode($response);

        return $value;
    }

    //GET LIST Of BANKS
    public function getFullBankList()
    {
        //Get API Details
        $d = $this->getApiConfiguration();
        $a = $this->getSiteConfiguration();
        $monifyStatus = $this->getConfigValue($d, "monifyStatus");
        $monifyApi = $this->getConfigValue($d, "monifyApi");
        $monifySecrete = $this->getConfigValue($d, "monifySecrete");
        $monifyContract = $this->getConfigValue($d, "monifyContract");
        $adminEmail = $a->email;

        $accessKey = $monifyApi . ":" . $monifySecrete;
        $apiKey = base64_encode($accessKey);

        //Get Authorization Data
        $url = 'https://api.monnify.com/api/v1/auth/login';
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_HTTPHEADER => ["Authorization: Basic {$apiKey}", "Content-Type: application/json"],
        ]);

        $json = curl_exec($ch);
        $result = json_decode($json);
        curl_close($ch);

        $accessToken = $result->responseBody->accessToken;

        //Get Authorization Data
        $url2 = 'https://api.monnify.com/api/v1/banks';
        $ch2 = curl_init();
        curl_setopt_array($ch2, [
            CURLOPT_URL => $url2,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => ["Authorization: Bearer {$accessToken}", "Content-Type: application/json"],
        ]);

        $json2 = curl_exec($ch2);
        $result2 = json_decode($json2);
        curl_close($ch2);

        return $result2;
    }

    // Verify Bank Account Details
    public function sendMoney($amount, $narration, $bankCode, $accountNumber, $accountName)
    {
        // Get API Details
        $d = $this->getApiConfiguration();
        $a = $this->getSiteConfiguration();
        $monifyStatus = $this->getConfigValue($d, "monifyStatus");
        $monifyApi = $this->getConfigValue($d, "monifyApi");
        $monifySecrete = $this->getConfigValue($d, "monifySecrete");
        $monifyContract = $this->getConfigValue($d, "monifyContract");
        $adminEmail = $a->email;

        $accessKey = $monifyApi . ":" . $monifySecrete;
        $apiKey = base64_encode($accessKey);

        // Get Authorization Data
        $url = 'https://api.monnify.com/api/v1/auth/login';
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_HTTPHEADER => ["Authorization: Basic {$apiKey}", "Content-Type: application/json"],
        ]);

        $json = curl_exec($ch);
        $result = json_decode($json);
        curl_close($ch);

        if (!$result || !isset($result->responseBody->accessToken)) {
            // Handle error
            throw new Exception("Failed to get access token");
        }

        $accessToken = $result->responseBody->accessToken;

        // Validate Bank Account
        $url2 = 'https://api.monnify.com/api/v2/disbursements/single';
        $ch2 = curl_init();
        curl_setopt_array($ch2, [
            CURLOPT_URL => $url2,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode([
                "amount" => $amount,
                "reference" => uniqid(), // Add a unique reference
                "narration" => $narration,
                "destinationBankCode" => $bankCode,
                "destinationAccountNumber" => $accountNumber,
                "currency" => "NGN",
                "sourceAccountNumber" => "6277711435",
                "destinationAccountName" => $accountName,
            ]),
            CURLOPT_HTTPHEADER => ["Authorization: Bearer {$accessToken}", "Content-Type: application/json"],
        ]);

        $json2 = curl_exec($ch2);
        $result2 = json_decode($json2);
        curl_close($ch2);

        if (!$result2) {
            // Handle error
            throw new Exception("Failed to validate account");
        }

        return $result2;
    }

    //Verify Bank Account Details
    public function verifyBankAccount($bankcode, $accountno)
    {
        //Get API Details
        $d = $this->getApiConfiguration();
        $a = $this->getSiteConfiguration();
        $monifyStatus = $this->getConfigValue($d, "monifyStatus");
        $monifyApi = $this->getConfigValue($d, "monifyApi");
        $monifySecrete = $this->getConfigValue($d, "monifySecrete");
        $monifyContract = $this->getConfigValue($d, "monifyContract");
        $adminEmail = $a->email;

        $accessKey = $monifyApi . ":" . $monifySecrete;
        $apiKey = base64_encode($accessKey);

        //Get Authorization Data
        $url = 'https://api.monnify.com/api/v1/auth/login';
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_HTTPHEADER => ["Authorization: Basic {$apiKey}", "Content-Type: application/json"],
        ]);

        $json = curl_exec($ch);
        $result = json_decode($json);
        curl_close($ch);

        $accessToken = $result->responseBody->accessToken;

        //Get Authorization Data
        $url2 = 'https://api.monnify.com/api/v1/disbursements/account/validate?accountNumber=' . $accountno . '&bankCode=' . $bankcode;
        $ch2 = curl_init();
        curl_setopt_array($ch2, [
            CURLOPT_URL => $url2,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => ["Authorization: Bearer {$accessToken}", "Content-Type: application/json"],
        ]);

        $json2 = curl_exec($ch2);
        $result2 = json_decode($json2);
        curl_close($ch2);

        return $result2;
    }
}

?>
