<?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);

// 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());
}

// Calculate date 2 days from now
$reminderDate = date('Y-m-d', strtotime('+2 days'));

// Query to fetch users whose subscription expires in exactly 2 days
$query = "SELECT username, mobile_no, owner_name, subscription_date 
  FROM loginusers 
  WHERE subscription_date IS NOT NULL 
  AND subscription_date = :reminderDate";
  
$stmt = $pdo->prepare($query);
$stmt->bindParam(':reminderDate', $reminderDate);
$stmt->execute();

$totalReminders = $stmt->rowCount();

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

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

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

// Prepare SMS message
$message = "Dear $owner_name,\n\nYour Subscription will expire in 2 days (on $expiryDate). 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:* Expiring soon\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
$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
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 reminder (2 days before expiry) completed.\n";
$report .= "Date checked: $reminderDate (expiry date)\n";
$report .= "Total reminders to send: $totalReminders\n";
$report .= "Successfully sent: $sentCount\n";
$report .= "Failed to send: $failedCount\n";

echo $report;
?>