<?php
header('Content-Type: application/json');

// Enable error logging
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', 'transaction_error.log');
error_log("Transaction.php started at " . date('Y-m-d H:i:s'));

// Database connection
$servername = "localhost";
$username_db = "templesm_longsmm";
$password_db = "templesm_longsmm";
$dbname = "templesm_longsmm";

// Get the transaction ID from the URL parameters or request
$tran_id = isset($_GET['tran_id']) ? $_GET['tran_id'] : null;

if ($tran_id) {
    // Create connection
    $conn = new mysqli($servername, $username_db, $password_db, $dbname);

    // Check connection
    if ($conn->connect_error) {
        echo json_encode(["status" => "ERROR", "message" => "Connection failed: " . $conn->connect_error]);
        exit();
    }

    // Prepare the SQL statement to select the md5 and other details for the given tran_id
    $stmt = $conn->prepare("SELECT md5, username, amount, payment_status FROM payment_qrcode WHERE tran_id = ?");
    $stmt->bind_param("s", $tran_id);

    // Execute the query
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        // Fetch the md5, username, and amount from the result
        $row = $result->fetch_assoc();
        $md5 = $row['md5'];
        $username = $row['username'];
        $amount = $row['amount'];
        $payment_status = $row['payment_status'];

        // Check if the payment status is already SUCCESS
        if ($payment_status === 'SUCCESS') {
            echo json_encode(["status" => "ERROR", "message" => "Payment has already been processed successfully"]);
            exit();
        }

        // API request logic
        $accessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7ImlkIjoiMDYwYjNkYTFjYTJiNDNhNiJ9LCJpYXQiOjE3NDc3NDgzMzcsImV4cCI6MTc1NTUyNDMzN30.nv8PasXDB64Mos3WPu3L62Tfo2_LurtjAcvN4AuFlsY";
        $apiUrl = "https://api-bakong.nbc.gov.kh/v1/check_transaction_by_md5";

        // Initialize cURL
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $apiUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode(["md5" => $md5]),
            CURLOPT_HTTPHEADER => [
                "Authorization: Bearer $accessToken",
                "Content-Type: application/json"
            ],
        ]);

        // Execute the request and get the response
        $response = curl_exec($curl);

        // Check for errors in cURL
        if (curl_errno($curl)) {
            echo json_encode(["status" => "ERROR", "message" => curl_error($curl)]);
            curl_close($curl);
            exit();
        }

        // Decode the API response
        $responseData = json_decode($response, true);

        // Extract bank information from the API response
        $bankSource = 'Unknown';
        if (isset($responseData['data']['fromAccountId'])) {
            $bankSource = $responseData['data']['fromAccountId'];
        } elseif (isset($responseData['data']['senderAccountId'])) {
            $bankSource = $responseData['data']['senderAccountId'];
        }

        // Check if the API responseCode is 0 (successful transaction)
        if (isset($responseData['responseCode']) && $responseData['responseCode'] === 0) {
            // Check if notification was already sent for this transaction
            $alreadyNotified = false;
            $hash = isset($responseData['data']['hash']) ? $responseData['data']['hash'] : '';
            
            // Create notification log directory if it doesn't exist
            $scriptDir = dirname(__FILE__);
            $rootDir = dirname($scriptDir);
            $notificationLogDir = $rootDir . '/notification_logs';
            
            error_log("Notification log directory path: $notificationLogDir");
            
            if (!file_exists($notificationLogDir)) {
                $mkdirResult = @mkdir($notificationLogDir, 0755, true);
                if (!$mkdirResult) {
                    error_log("Failed to create notification log directory: $notificationLogDir");
                    $notificationLogDir = './notification_logs';
                    if (!file_exists($notificationLogDir)) {
                        @mkdir($notificationLogDir, 0755, true);
                    }
                }
            }
            
            $notificationLogFile = $notificationLogDir . '/sent_notifications.log';
            error_log("Notification log file path: $notificationLogFile");
            
            // Check if notification was already sent for this transaction
            $sentNotifications = [];
            if (file_exists($notificationLogFile)) {
                $sentNotifications = @file($notificationLogFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                if ($sentNotifications === false) {
                    error_log("Failed to read notification log file: $notificationLogFile");
                    $sentNotifications = [];
                }
                
                if (in_array($tran_id, $sentNotifications)) {
                    $alreadyNotified = true;
                    error_log("Found existing notification for transaction ID: $tran_id");
                }
                
                if (!$alreadyNotified && !empty($md5) && in_array($md5, $sentNotifications)) {
                    $alreadyNotified = true;
                    error_log("Found existing notification for MD5: $md5");
                }
                
                if (!$alreadyNotified && !empty($hash) && in_array($hash, $sentNotifications)) {
                    $alreadyNotified = true;
                    error_log("Found existing notification for hash: $hash");
                }
                
                if (!$alreadyNotified && !empty($hash)) {
                    $shortHash = substr($hash, 0, 8);
                    if (in_array($shortHash, $sentNotifications)) {
                        $alreadyNotified = true;
                        error_log("Found existing notification for short hash: $shortHash");
                    }
                }
            }

            // Prepare the SQL statement to update the payment_status to SUCCESS
            $updateStmt = $conn->prepare("UPDATE payment_qrcode SET payment_status = 'SUCCESS' WHERE tran_id = ?");
            $updateStmt->bind_param("s", $tran_id);

            // Execute the update statement
            if ($updateStmt->execute()) {
                $notificationSuccess = true;
                
                if (!$alreadyNotified) {
                    // Send Telegram notification
                    $notificationSuccess = sendTelegramNotification($username, $amount, $tran_id, $md5, $bankSource);
                    error_log("Telegram notification sent for tran_id: $tran_id, success: " . ($notificationSuccess ? "Yes" : "No"));
                    
                    if ($notificationSuccess) {
                        $logWriteSuccess = true;
                        
                        if (!empty($tran_id)) {
                            $writeResult = @file_put_contents($notificationLogFile, $tran_id . "\n", FILE_APPEND);
                            if ($writeResult === false) {
                                error_log("Failed to write tran_id to notification log: $tran_id");
                                $logWriteSuccess = false;
                            }
                        }
                        
                        if (!empty($md5)) {
                            $writeResult = @file_put_contents($notificationLogFile, $md5 . "\n", FILE_APPEND);
                            if ($writeResult === false) {
                                error_log("Failed to write md5 to notification log: $md5");
                                $logWriteSuccess = false;
                            }
                        }
                        
                        if (!empty($hash)) {
                            $writeResult = @file_put_contents($notificationLogFile, $hash . "\n", FILE_APPEND);
                            if ($writeResult === false) {
                                error_log("Failed to write hash to notification log: $hash");
                                $logWriteSuccess = false;
                            }
                            
                            $writeResult = @file_put_contents($notificationLogFile, substr($hash, 0, 8) . "\n", FILE_APPEND);
                            if ($writeResult === false) {
                                error_log("Failed to write short hash to notification log: " . substr($hash, 0, 8));
                                $logWriteSuccess = false;
                            }
                        }
                        
                        if (!$logWriteSuccess) {
                            error_log("Warning: Failed to write to notification log file. This might cause duplicate notifications.");
                        }
                    }
                } else {
                    error_log("Notification already sent for this transaction, skipping duplicate notification");
                }
                
                if (!$notificationSuccess) {
                    echo json_encode(["status" => "WARNING", "message" => "Transaction processed successfully but there was an issue with Telegram notification"]);
                } else {
                    echo json_encode(["status" => "SUCCESS"]);
                }
            } else {
                echo json_encode(["status" => "ERROR", "message" => "Failed to update payment status"]);
            }

            // Close the update statement
            $updateStmt->close();
        } else {
            echo json_encode(["status" => "ERROR", "message" => "Transaction check failed", "responseMessage" => $responseData['responseMessage']]);
        }

        // Close cURL session
        curl_close($curl);
    } else {
        echo json_encode(["status" => "ERROR", "message" => "No data found for the provided transaction ID"]);
    }

    // Close the statement and connection
    $stmt->close();
    $conn->close();
} else {
    echo json_encode(["status" => "ERROR", "message" => "Transaction ID not provided"]);
}

function sendTelegramNotification($username, $amount, $tran_id, $md5 = null, $displaySource = 'Unknown') {
    // Array of possible bot tokens
    $botTokens = [
        "7915153806:AAFvwrVnSNwu7cR9L_rQdmxX4jiBgLjK7h4",
        // Add more tokens as needed
    ];

    // Randomly select a bot token
    $botToken = $botTokens[array_rand($botTokens)];
    $chatId = "-1002665620733";

    // Set Cambodia timezone (GMT+7)
    date_default_timezone_set('Asia/Phnom_Penh');
    $cambodia_time = date('Y-m-d H:i:s');
    
    // Build the message with the new format
    $message = "You received " . number_format($amount, 2) . " USD from " . $displaySource;
    $message .= " on " . date('d M, Y H:i:s', strtotime($cambodia_time));
    
    if (!empty($tran_id)) {
        $message .= " by Transaction ID: " . $tran_id;
    }
    
    if (!empty($md5)) {
        $message .= ", Bakong Hash: " . substr($md5, 0, 8);
    }
    
    if (!empty($username)) {
        $message .= ". Remark: payment from user: " . $username;
    }
    
    error_log("Sending Telegram message: " . $message);

    // Initialize cURL for Telegram
    $url = "https://api.telegram.org/bot$botToken/sendMessage";
    $data = [
        'chat_id' => $chatId,
        'text' => $message,
        'parse_mode' => 'HTML'
    ];

    // Initialize cURL
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER , true);

    // Execute the request
    $response = curl_exec($curl);

    // Check for errors
    if ($response === false) {
        error_log('Telegram API error: ' . curl_error($curl));
        curl_close($curl);
        return false;
    }

    // Close cURL session
    curl_close($curl);
    return true;
}