<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include "db.php";

// Function to fetch global settings
function getGlobalSettings($conn) {
    $query = "SELECT * FROM global_message_settings WHERE id = 1";
    $result = $conn->query($query);
    return $result->num_rows > 0 ? $result->fetch_assoc() : [];
}

// Function to fetch user-specific settings
function getUserSettings($conn, $userId) {
    $query = "SELECT * FROM user_category_message_settings WHERE user_id = '$userId'";
    $result = $conn->query($query);
    return $result->num_rows > 0 ? $result->fetch_assoc() : [];
}

// Function to calculate notification date
function calculateNotificationDate($creationDate, $expiryDays, $notificationHours) {
    $creationDateObj = new DateTime($creationDate);
    $expirationDate = clone $creationDateObj;
    $expirationDate->modify("+$expiryDays days");
    $notificationDate = clone $expirationDate;
    $notificationDate->modify("-$notificationHours hours");
    return $notificationDate->format('Y-m-d H:i:s');
}

// Check users who are eligible for notification (after 2 hours)
$sql = "
    SELECT * 
    FROM telegram_users 
    WHERE (notification_msg_send_update_time IS NULL OR TIMESTAMPDIFF(HOUR, notification_msg_send_update_time, NOW()) >= 2)
    ORDER BY id DESC LIMIT 1";
$stmt = $conn->prepare($sql);

if ($stmt) {
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        while ($user = $result->fetch_assoc()) {
            $defaultSettings = getGlobalSettings($conn);
            $userSettings = getUserSettings($conn, $user['id']);
            $settings = $userSettings ? $userSettings : $defaultSettings;

            $phonenumber = $user['phonenumber'];
            $username = $user['username'];
            $userId = $user['id'];

            // Ensure at least one of phone number or username exists
            if (!empty($phonenumber) || !empty($username)) {
            // if (!empty($phonenumber)) {
                 // Extract settings values
                $selectedCategories = $settings['category_name'];
                $debtPaymentExpiryPeriod = $settings['debt_payment_expiry_period'];
                $messagePrompt = $settings['message_prompt'];
                $notificationTime = $settings['notification_send_time'];

                // Calculate notification date
                $notificationDate = calculateNotificationDate(
                    $user['date'],
                    $debtPaymentExpiryPeriod,
                    $notificationTime
                );

                // Update last_notification timestamp for the user
                $updateQuery = "UPDATE telegram_users SET notification_msg_send_update_time = NOW() WHERE id = ?";
                $updateStmt = $conn->prepare($updateQuery);
                $updateStmt->bind_param('i', $userId);
                $updateStmt->execute();

                // Display user notification details
                ?>
                <div class="container mt-5">
                    <div class="card">
                        <div class="card-header">User Notification Details</div>
                        <div class="card-body">
                            <div class="form-group">
                                <label>Notification Send Date and Time</label>
                                <input type="text" class="form-control" value="<?= $notificationDate ?>" readonly>
                            </div>
                            <div class="form-group">
                                <label>Phone Number</label>
                                <input type="text" class="form-control" value="<?= $phonenumber ?>" readonly>
                            </div>
                            <div class="form-group">
                                <label>Username</label>
                                <input type="text" class="form-control" value="<?= $username ?>" readonly>
                            </div>
                            <div class="form-group">
                                <label>User ID</label>
                                <input type="text" class="form-control" value="<?= $userId ?>" readonly>
                            </div>
                            <div class="form-group">
                                <label>Message Prompt</label>
                                <textarea class="form-control" readonly><?= $messagePrompt ?></textarea>
                            </div>
                        </div>
                    </div>
                </div>
                <?php
            } else {
                echo "<div class='container mt-5'><div class='alert alert-danger'>No valid user found. Either phone number must be provided.</div></div>";
               
            }
        }
    } else {
        echo "<div class='container mt-5'><div class='alert alert-info'>No user eligible for notification.</div></div>";
    }

    $stmt->close();
} else {
    die("Error preparing statement: " . $conn->error);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>User Notification Details</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.4/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>