<?php

$servername = "localhost";
$username = "otatacom_daniel";
$password = "@#Wanji9891";
$dbname = "otatacom_renti";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$api_key = 'c02bf781565217d0';
$secret_key = 'Y2FlZmQzNjllMzg1YmNmZDUyN2Q5MmU5MWQyZGMwMTFjZmYxODBjZTQ2YjYzOTViNjZkYWI5YzAwZWQyMTBmYw';

// Include the QR code library
include '../phpqrcode/qrlib.php';

// Sample data (replace these with your actual form data)
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$full = $fname . ' ' . $lname;
$mtaa = $_POST['mtaa'];
$phone = $_POST['phone'];
$region = $_POST['region'];
$tin = $_POST['tin'];
$pass = $_POST['password'];
$password = password_hash($pass, PASSWORD_BCRYPT); // Hash the password
$tc = $_POST['tc'];

// Generate a unique 8-digit code
$code = generateUniqueCode($conn);

// Function to generate QR code
function generateQRCode($data, $filename)
{
    // Specify the path to the qrcode folder
    $folderPath = '../wakala/qrcodes/';

    $size = 15;
    $ecc = 'L'; // Error correction level (L, M, Q, H)

    // Generate QR code
    QRcode::png($data, $folderPath . $filename, $ecc, $size);

    // Uncomment the line below to see the path where the QR code is saved
    // echo "QR code generated and saved as $folderPath$filename";
}

// Example usage
$qrcode_line = $code;
$data = $qrcode_line . ',' . $full;
$filename = $qrcode_line . ".png"; // Fix: concatenate the file extension

generateQRCode($data, $filename);

// SQL query with a prepared statement
$sql = "INSERT INTO agents (fname, lname, mtaa, phone, region, tin, password, tc, code, qr) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);

if ($stmt === false) {
    die("Prepare failed: " . $conn->error);
}

// Bind parameters
$stmt->bind_param("ssssssssss", $fname, $lname, $mtaa, $phone, $region, $tin, $password, $tc, $code, $filename);

// Execute the statement
if ($stmt->execute()) {
    $link = "https://renti.co.tz/wakala/h/badili/?agentNumber=$code";
    $fullname = $fname . ' ' . $lname;
    $location = $mtaa . ', ' . $region;
    $status = 'active';
    $message = "Usajili wako umekamilika. Namba yako ya wakala ni $code iliyosajiliwa kwa jina la $fullname. Float balance yako ni TSH 0.00 na PIN yako ni $pass. Kubadili PIN hii ingia $link";

    // Format phone number
    $ph = ltrim($phone, '0');
    $phoneNumber = '255' . $ph;

    // Prepare data for the API
    $postData = array(
        'source_addr' => 'RENTI APP',
        'encoding' => 0,
        'schedule_time' => '',
        'message' => $message,
        'recipients' => array(array('recipient_id' => '1', 'dest_addr' => $phoneNumber))
    );

    $url = 'https://apisms.beem.africa/v1/send';

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

    // Set cURL options
    curl_setopt_array($ch, array(
        CURLOPT_POST => TRUE,
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0,
        CURLOPT_HTTPHEADER => array(
            'Authorization: Basic ' . base64_encode("$api_key:$secret_key"),
            'Content-Type: application/json'
        ),
        CURLOPT_POSTFIELDS => json_encode($postData)
    ));

    // Execute cURL request
    $response = curl_exec($ch);
    if ($response === FALSE) {
        echo json_encode(array('success' => false, 'message' => 'Error: ' . curl_error($ch)));
    } else {
        
        
            echo "
            <script type='text/javascript'>
              window.location.href='https://bluespacegrouplimited.com/renti/saveData.php?name=$fullname&wakala_number=$code&password=$pass&tin=$tin&phone=$phone&location=$location&status=$status&time=';
            </script>
          ";
        
    }

} else {
    echo "Error: " . $stmt->error;
}

// Close the statement
$stmt->close();
// Close the connection
$conn->close();

// Function to generate a unique 8-digit code
function generateUniqueCode($conn)
{
    $code = generateCode();

    // Check if the code already exists in the database
    $stmt = $conn->prepare("SELECT COUNT(*) FROM agents WHERE code = ?");
    $stmt->bind_param("s", $code);
    $stmt->execute();
    $stmt->bind_result($count);
    $stmt->fetch();
    $stmt->close();

    // If the code exists, generate a new one
    if ($count > 0) {
        return generateUniqueCode($conn);
    }

    return $code;
}

// Function to generate an 8-digit code
function generateCode()
{
    return str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}
?>
