<?php
require_once '../db/config.php'; // $con is mysqli connection

/**
 * Check if user subscription expired, update to Free if so
 *
 * @param mysqli $con
 * @param int $user_id
 * @return bool true if updated to Free, false otherwise
 */
function checkAndUpdateSubscription($con, $user_id) {
    // Fetch user package and expiry
    $stmt = $con->prepare("SELECT package, package_expiry FROM users WHERE user_id = ? LIMIT 1");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    $stmt->close();

    if (!$user) {
        return false; // user not found
    }

    $currentPackage = $user['package'];
    $expiryDate     = $user['package_expiry'];

    // If expiry date exists and has passed
    if ($expiryDate && strtotime($expiryDate) < time()) {
        // Update user to Free package
        $update = $con->prepare("UPDATE users SET package = 'Free', package_expiry = NULL WHERE user_id = ?");
        $update->bind_param("i", $user_id);
        $update->execute();
        $update->close();

        return true; // expired and downgraded
    }

    return false; // not expired
}




$user_id = 123; // Example user_id

if (checkAndUpdateSubscription($con, $user_id)) {
    echo "User subscription expired. Downgraded to Free.";
} else {
    echo "User subscription still active.";
}

?>