<?php
// Database connection
$servername = "localhost"; // assuming your database is hosted on localhost

// Connect to your database
$mysqli = new mysqli("localhost", "venmobdc_OnlineClassuser", "EuN&(VkTztyS", "venmobdc_OnlineClass");

// Assuming you're receiving user_id and book_id from your Android app
$user_id = $_GET['user_id'];
$book_id = $_GET['book_id'];

// Get current timestamp in UTC
$current_timestamp = gmdate("Y-m-d H:i:s");

// Check if the user already purchased the book
$query = "SELECT * FROM user_purchases WHERE user_id = ? AND book_id = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ii", $user_id, $book_id);
$stmt->execute();
$result = $stmt->get_result();

$response = array();

if ($result->num_rows > 0) {
    // User already purchased the book
    $row = $result->fetch_assoc();
    $expiration_date = $row['expiration_date'];
    $purchase_date = $row['purchase_date']; // Retrieve purchase date from the database

    // Calculate time remaining
    $expiration_time = strtotime($expiration_date);
    $time_left_seconds = $expiration_time - strtotime($current_timestamp);

    if ($time_left_seconds > 0) {
        // Calculate remaining time in minutes and days
        $time_left_minutes = floor($time_left_seconds / 60);
        $time_left_days = floor($time_left_seconds / (60 * 60 * 24));

        // Send success response with time remaining
        $response = array(
            "success" => true,
            "isPurchased" => true,
            "isValid" => true,
            "expiration_date" => $expiration_date,
            "purchase_date" => $purchase_date,
            "time_left_seconds" => $time_left_seconds,
            "time_left_minutes" => $time_left_minutes,
            "time_left_days" => $time_left_days
        );
    } else {
        // Purchase has expired
        $response = array(
            "success" => true,
            "isPurchased" => true,
            "isValid" => false,
            "message" => "Purchase expired"
        );
    }
} else {
    // User has not purchased the book before
    $response = array(
        "success" => false,
        "message" => "User has not purchased this book"
    );
}

// Send response to Android app
echo json_encode($response);
?>
