<?php
include "../config.php";

// Set timezone to East Africa Time (EAT)
date_default_timezone_set('Africa/Nairobi');

// Get the phone number from the request
$phone = $_POST['phone'];

// Ensure phone starts with 255 for sending the SMS
$formatted_phone = preg_replace('/^(0|255)/', '255', $phone);

// Check if the phone number exists in the users table
$sql = "SELECT * FROM users WHERE phone = '$phone'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Generate a random OTP
    $otp = rand(100000, 999999); // Generate 6-digit OTP

    // Store the OTP and OTP expiry in the database
    $expiry_time = date("Y-m-d H:i:s", strtotime("+10 minutes")); // OTP expires in 10 minutes (EAT time)
    $update_sql = "UPDATE users SET otp = '$otp', otp_expiry = '$expiry_time' WHERE phone = '$phone'";

    if ($conn->query($update_sql) === TRUE) {
        // Beem Africa API details
        $api_key = "106de5fd0d63b2de"; // Replace with your actual API key
        $secret_key = "NDY1NGE3NjZjYTgzZmE5MTFkOThkODg1MDZjMmE1NTVmOTc2OGJlMzc1MDRmYjNlMDkxODE1MWFiM2JkY2FlNg=="; // Replace with your actual secret key
        $sender_name = "Bexa Mikopo";
        
        // Prepare message
        $message = "Your OTP for password reset is: $otp. The OTP will expire in 10 minutes. Please keep it confidential. Bexa Microfinance";

        // Prepare and send SMS via Beem Africa API
        $url = "https://apisms.beem.africa/v1/send";  // Beem Africa API endpoint
        $data = [
            'source_addr' => $sender_name,
            'encoding' => 0,  // Adjust encoding as per your requirements
            'message' => $message,
            'recipients' => [
                ['recipient_id' => "1", 'dest_addr' => $formatted_phone]  // Ensure correct recipient format
            ]
        ];
        $payload = json_encode($data);

                // cURL request to send SMS
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: Basic ' . base64_encode("$api_key:$secret_key")
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); // Ongeza timeout ya sekunde 30

        $response = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if (curl_errno($ch)) {
            error_log("SMS sending error: " . curl_error($ch)); // Andika error kwenye log
            echo json_encode(['success' => false, 'message' => 'SMS sending failed, please try again later.']);
        } elseif ($httpcode != 200) {
            error_log("SMS API Response: " . print_r($response, true)); // Andika response kwa debugging
            echo json_encode(['success' => false, 'message' => 'Failed to send OTP.']);
        } else {
            echo json_encode(['success' => true, 'message' => 'OTP sent successfully']);
        }

        curl_close($ch);

    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to update OTP in the database']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Phone number not found']);
}

$conn->close();
?>
