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

include 'admin_panel/db.php'; // Include your database connection

date_default_timezone_set('Asia/Kuala_Lumpur');

try {
    // Fetch users with status 0
    $usersSql = "SELECT * FROM telegram_users";
    $usersResult = $conn->query($usersSql);

    if ($usersResult->num_rows > 0) {
        // Fetch all bot tokens from the database
        $tokensSql = "SELECT token FROM telegram_bot_tokens";
        $tokensResult = $conn->query($tokensSql);

        if ($tokensResult->num_rows > 0) {
            $users = [];
            while ($user = $usersResult->fetch_assoc()) {
                $users[] = $user;
            }

            $botIndex = 0;
            $totalBots = $tokensResult->num_rows;

            $defaultSettingsQuery = "SELECT * FROM global_message_settings WHERE id = 1";
            $defaultSettingsResult = $conn->query($defaultSettingsQuery);
            $defaultSettings = $defaultSettingsResult->num_rows > 0 ? $defaultSettingsResult->fetch_assoc() : [];
            
            $currentTime = date('H:i');

            foreach ($users as $user) {
                $chatId = $user['chat_id'];
                $userSettingsQuery = "SELECT * FROM user_category_message_settings WHERE user_id = '{$user['id']}'";
                $userSettingsResult = $conn->query($userSettingsQuery);
                
                $settings = $userSettingsResult->num_rows > 0 ? $userSettingsResult->fetch_assoc() : $defaultSettings;
                
                $debtPaymentExpiryPeriod = $settings['debt_payment_expiry_period'] ?? 0;
                $notificationTimes = isset($settings['notification_times']) ? explode(',', $settings['notification_times']) : [];
                $notificationTimes = array_map('trim', $notificationTimes);
                
                $messagePrompt = $settings['message_prompt'] ?? '';
                $voiceMessages = isset($settings['voice_message']) ? explode(',', $settings['voice_message']) : [];
                $voiceMessages = array_map('trim', $voiceMessages);
                $voiceMessages = array_filter($voiceMessages);
                $mediaFiles = isset($settings['media_files']) ? explode(',', $settings['media_files']) : [];

                if (in_array($currentTime, $notificationTimes)) {
                    $tokensResult->data_seek($botIndex);
                    $bot = $tokensResult->fetch_assoc();
                    $botToken = $bot['token'];

                    $fullMessage = "Hello! 👋\n\n";
                    $fullMessage .= "Your debt payment is due in: " . $debtPaymentExpiryPeriod . " days.\n\n";
                    $fullMessage .= "Message: " . $messagePrompt . "\n\n";
                    $fullMessage .= "Thank you for your attention. If you have any questions, feel free to contact us.\n\n";
                    $fullMessage .= "Best regards,\nYour Support Team";
                    
                    // Send media files (photos/videos) in one message
                    if (!empty($mediaFiles) && is_array($mediaFiles)) {
                        $validMedia = [];
                    
                        foreach ($mediaFiles as $file) {
                            $file = trim($file);
                            if (!empty($file)) { // Ensure it's not an empty string
                                $filePath = "/home/aliadmin/public_html/tele1.ali1.work/admin_panel/" . $file;
                                if (file_exists($filePath)) {
                                    $validMedia[] = $filePath;
                                } else {
                                    error_log("Media file not found: " . $filePath);
                                }
                            }
                        }
                    
                        if (!empty($validMedia)) {
                            sendMediaGroupToTelegram($botToken, $chatId, $validMedia);
                        }
                    }
                    
                    sendMessageToTelegramByChatId($botToken, $chatId, $fullMessage, $conn);
                    
                    if (!empty($voiceMessages)) {
                        foreach ($voiceMessages as $voiceFile) {
                            $voicePath = "/home/aliadmin/public_html/tele1.ali1.work/admin_panel/" . $voiceFile;
                            
                            if (file_exists($voicePath)) {
                                sendAudioToTelegramByChatId($botToken, $chatId, $voicePath);
                            } else {
                                error_log("Audio file not found: " . $voicePath);
                            }
                        }
                    }

                    logMessageStatus($conn, $chatId, $botToken, $fullMessage, true);
                    $botIndex = ($botIndex + 1) % $totalBots;
                    sleep(1);
                }
            }
        } else {
            echo "No bot tokens found in the database.\n";
        }
    } else {
        echo "No users found in the database.\n";
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

function sendAudioToTelegramByChatId($botToken, $chatId, $audioPath) {
    if (!file_exists($audioPath)) {
        error_log("Audio file not found: " . $audioPath);
        return false;
    }
    
    $url = "https://api.telegram.org/bot" . $botToken . "/sendAudio";
    $postData = ['chat_id' => $chatId, 'audio' => curl_file_create($audioPath)];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    return $httpCode === 200;
}

// Function to send multiple images/videos in one message
function sendMediaGroupToTelegram($botToken, $chatId, $filePaths) {
    $mediaArray = [];
    $attachments = [];

    foreach ($filePaths as $filePath) {
        $fileExt = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
        $fileName = basename($filePath);

        if (in_array($fileExt, ['jpg', 'jpeg', 'png', 'gif'])) {
            $mediaArray[] = ['type' => 'photo', 'media' => "attach://$fileName"];
        } elseif (in_array($fileExt, ['mp4', 'mov', 'avi'])) {
            $mediaArray[] = ['type' => 'video', 'media' => "attach://$fileName"];
        } else {
            continue; // Skip unsupported files
        }

        $attachments[$fileName] = curl_file_create($filePath);
    }

    if (empty($mediaArray)) {
        return false;
    }

    $url = "https://api.telegram.org/bot" . $botToken . "/sendMediaGroup";
    $postData = ['chat_id' => $chatId, 'media' => json_encode($mediaArray)];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData + $attachments);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
}

function sendMessageToTelegramByChatId($botToken, $chatId, $message, $conn) {
    $url = "https://api.telegram.org/bot" . $botToken . "/sendMessage";
    $data = ['chat_id' => $chatId, 'text' => $message];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    $responseData = json_decode($response, true);
    
    if (isset($responseData['ok']) && $responseData['ok'] === true) {
        $botStatus = 'Active';
    } elseif (isset($responseData['error_code']) && $responseData['error_code'] === 403) {
        $botStatus = 'Blocked';
    } else {
        $botStatus = 'Unknown';
    }
    
    $updateSql = "UPDATE telegram_users SET bot_status = '$botStatus' WHERE chat_id = '$chatId'";
    $conn->query($updateSql);
    
    return $httpCode === 200;
}


function logMessageStatus($conn, $chatId, $botToken, $message, $messageSent) {
    $status = $messageSent ? 'sent' : 'failed';
    
    $insertSql = "INSERT INTO message_logs (chat_id, bot_token, message, status, timestamp) 
                  VALUES ('$chatId', '$botToken', '$message', '$status', NOW())";
    $conn->query($insertSql);
}
