<?php
session_start();
require 'db.php'; // Include your database connection file

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $phone = $_POST['phone'];
    $pin = $_POST['pin'];
    $name = $_POST['name'];

    // Generate a random OTP
    $otp = rand(100000, 999999); // Generate a 6-digit OTP

    // Send OTP via Wablas using cURL
    $token = 'uWzy4b39nOywBtLBwp6OwZRX0ARBXswLd0FXryqDDvIsmnQKNynW9c1jlfx4oJB6'; // Replace with your actual API key
    $message = urlencode("Your OTP for signup is: $otp");

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, "https://kudus.wablas.com/api/send-message?phone=$phone&message=$message&token=$token");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Return the response as a string
    $result = curl_exec($curl);

    // Check for cURL errors
    if (curl_errno($curl)) {
        // You can log the error or handle it here if needed
        // For now, we just ignore the cURL error
    }

    curl_close($curl);

    // Decode JSON response
    $response = json_decode($result, true);

    // Store the OTP and user data in session for later verification
    $_SESSION['otp'] = $otp;
    $_SESSION['user_data'] = [
        'phone' => $phone,
        'pin' => $pin,
        'name' => $name,
    ];

    // Redirect to the OTP verification page regardless of the API response
    header("Location: verify_otp.php");
    exit(); // Ensure to exit after redirection
}
