<?php
echo "Cron Started...<br>";

// === DB CONFIG ===
$host = "localhost";
$user = "allrtosh_1221";
$pass = "allrtosh_1221";
$db   = "allrtosh_1221";

$conn = mysqli_connect($host, $user, $pass, $db);
if (!$conn) {
    die("Database Connection Failed: " . mysqli_connect_error());
}

// === MPWA API CONFIG ===
$api_key = "d8b1def6-7651-41d3-9a33-b3b4609cd7c6";
$sender  = "919508740755";  // Your MPWA sender ID

// === SYSTEM SETTINGS ===
$MIN_BALANCE = 100;

// Last 10 min ka time
$tenMinutesAgo = date("Y-m-d H:i:s", time() - 10 * 60);

// === Select users ===
$sql = "
    SELECT id, phone, balance, last_whatsapp_lowbal
    FROM users
    WHERE balance < $MIN_BALANCE
    AND (last_whatsapp_lowbal IS NULL OR last_whatsapp_lowbal < '$tenMinutesAgo')
";

$result = mysqli_query($conn, $sql);

if (!$result) {
    die("SQL Error: " . mysqli_error($conn));
}

// Debug: total users
echo "Users Found: " . mysqli_num_rows($result) . "<br><br>";

// === Loop ===
while ($row = mysqli_fetch_assoc($result)) {

    $id      = $row['id'];
    $phone   = $row['phone'];
    $balance = $row['balance'];

    // ⭐ Auto add 91 in front if missing
    $phone = preg_replace('/\D/', '', $phone); // remove non-numeric chars
    if (substr($phone, 0, 2) !== "91") {
        $phone = "91" . $phone;
    }

    echo "Processing User ID: $id<br>";
    echo "Phone: $phone<br>";
    echo "Balance: $balance<br>";

    // Message
    $message = "⚠️ Wallet Low Balance Alert ⚠️

Hello {name},
Your current wallet balance is: 💰 Rs. {BALANCE}
Maxium 100 Your Account Balance
Please recharge immediately to avoid:
• Service interruption ⚠️
• Permanent account deletion ❌

🔄 Maintain your wallet for uninterrupted services.

Thank you,  
All RTO Service  
🌐 {WEBSITE_URL}
";
    $footer  = "Powered by All RTO Service";

    // API URL
    $url = "https://wa.amusms.in/send-message"
         . "?api_key=" . urlencode($api_key)
         . "&sender="  . urlencode($sender)
         . "&number="  . urlencode($phone)
         . "&message=" . urlencode($message)
         . "&footer="  . urlencode($footer);

    echo "API URL: $url<br>";

    // CURL
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);

    echo "API RESPONSE: $response<br>";
    echo "ERROR: $err<br><br>";

    // Update last sent time only if no error
    if (!$err) {
        $now = date("Y-m-d H:i:s");
        mysqli_query($conn, "
            UPDATE users 
            SET last_whatsapp_lowbal = '$now'
            WHERE id = $id
        ");
        echo "Time Updated: $now<br><br>";
    }
}

mysqli_close($conn);
echo "Cron Completed.";
?>
