<?php
// Set default timezone
date_default_timezone_set('Asia/Kolkata');

// Enable error reporting but disable logging
// error_reporting(E_ALL);
// ini_set('display_errors', 1);
// ini_set('log_errors', 0);  // This disables error logging

// Database configuration
require_once('../database/dbconfig.php');

// Database connection
try {
$pdo = new PDO("mysql:host=$db_host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Database connection failed: " . $e->getMessage());
}

// Get current date
$currentDate = date('Y-m-d');

// Query to fetch all users with expired subscriptions
$query = "SELECT username, mobile_no, owner_name, subscription_date 
  FROM loginusers 
  WHERE subscription_date IS NOT NULL 
  AND subscription_date <= :currentDate";
  
$stmt = $pdo->prepare($query);
$stmt->bindParam(':currentDate', $currentDate);
$stmt->execute();

$totalExpired = $stmt->rowCount();

// Counter for sent messages
$sentCount = 0;
$failedCount = 0;

// Process each expired user
while ($userdata = $stmt->fetch(PDO::FETCH_ASSOC)) {
$username = $userdata['username'];
$mobile_no = trim($userdata['mobile_no']);
$owner_name = $userdata['owner_name'];

// Validate mobile number
if (empty($mobile_no) || !preg_match('/^[0-9]{10}$/', $mobile_no)) {
$failedCount++;
continue;
}

// Prepare SMS message with proper newlines
$message = "Dear $owner_name,\n\n Your Subscription Has Expired. To Continue Enjoying Our Services Without Interruption, Please Renew Your Subscription.\n\n*Account Details:*\n*Username:* $username\n*Login URL:* fastpay.us.cc\n*Status:* Expired\n\n*Renew Now:* fastpay.us.cc\n\nIf you need help, feel free to contact our support team.\n\n*Regards,*\n*Customer Support Webupi*";

// Prepare API URL - using rawurlencode for proper %20 space encoding
$api_url = "https://bulk.quickbulksms.in.net/send-message?" . http_build_query([
'api_key' => 'HRM2n3B25y2lzu6bsZAxVzwwsj8Het',
'sender' => '919157455623',
'number' => '91' . $mobile_no,
'message' => $message
]);

// Send SMS using file_get_contents (simpler alternative)
try {
$response = file_get_contents($api_url);

if ($response === FALSE) {
throw new Exception("Failed to call API");
}

$sentCount++;
} catch (Exception $e) {
$failedCount++;
}
}

// Close connection
$pdo = null;

// Detailed report
$report = "Subscription check completed.\n";
$report .= "Total expired: $totalExpired\n";
$report .= "Successfully sent: $sentCount\n";
$report .= "Failed to send: $failedCount\n";

echo $report;
?>