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

include "db.php";
date_default_timezone_set('Asia/Kuala_Lumpur');

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

// Get current time in 24-hour format
$currentTime = date('H:i'); // 24-hour format
$currentDate = date('Y-m-d');

// Check users who are eligible for notification based on notification_times
$sql = "SELECT * FROM telegram_users";
$stmt = $conn->prepare($sql);

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

    if ($result->num_rows > 0) {
        $foundUsers = false;
        $validUserFound = false;

        while ($user = $result->fetch_assoc()) {
            $phonenumber = $user['phonenumber'];
            $username = $user['username'];
            $userId = $user['id'];

            if (!empty($phonenumber) || !empty($username)) {
                $validUserFound = true;
                $defaultSettings = getGlobalSettings($conn);
                $userSettings = getUserSettings($conn, $user['id']);
                $settings = $userSettings ? $userSettings : $defaultSettings;

                $selectedCategories = $settings['category_name'];
                $debtPaymentExpiryPeriod = $settings['debt_payment_expiry_period'];
                $messagePrompt = $settings['message_prompt'];
                $voiceMessage = $settings['voice_message'];
                $mediafiles = $settings['media_files'];
                $notificationTime = $settings['notification_send_time'];
                

                if (isset($settings['notification_times']) && $settings['notification_times'] != '') {
                    $notification_times = $settings['notification_times'];
                    $notificationTimesArray = explode(',', $notification_times);

                    foreach ($notificationTimesArray as $notificationTimeItem) {
                        $notificationTimeItem = trim($notificationTimeItem);

                        // Check if message was already sent today
                        $lastSentDates = [];
                        if ($settings['last_notification_sent_date'] !== null) {
                            $lastSentDates = json_decode($settings['last_notification_sent_date'], true) ?? [];
                        }
                        $lastSentDate = $lastSentDates[$notificationTimeItem] ?? null;

                        if ($currentTime === $notificationTimeItem && ($lastSentDate === null || $lastSentDate < $currentDate)) {
                            $foundUsers = true;

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

                            // Update last_notification_sent_date
                            $lastSentDates[$notificationTimeItem] = $currentDate;
                            $lastSentDatesJson = json_encode($lastSentDates);

                            $updateSentDateQuery = "UPDATE user_category_message_settings SET last_notification_sent_date = ? WHERE user_id = ?";
                            $updateSentDateStmt = $conn->prepare($updateSentDateQuery);
                            $updateSentDateStmt->bind_param('si', $lastSentDatesJson, $userId);
                            $updateSentDateStmt->execute();

                            ?>
                            <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 class="form-group">
                                            <label>Voice Message</label>
                                            <textarea class="form-control" readonly><?= $voiceMessage ?></textarea>
                                        </div>
                                        <div class="form-group">
                                            <label>Image And Videos</label>
                                            <textarea class="form-control" readonly><?= $mediafiles ?></textarea>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php
                        }
                    }
                }
            }
        }
        if ($validUserFound === false) {
            echo "<div class='container mt-5'><div class='alert alert-danger'>No valid user found. Either phone number or username must be provided.</div></div>";
        }
        if (!$foundUsers) {
            echo "<div class='container mt-5'><div class='alert alert-info'>No user eligible for notification at this time.</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>