ÿØÿà JFIF      ÿÛ „ 	 ( %!1!%)+...383-7(-.+



-%%--------------------------------------------------ÿÀ  ·" ÿÄ               ÿÄ 6     !1AQa"q‘±ð¡ÁÑ2Bá#Rb‚ñr ÿÄ              ÿÄ $         !1A2Qaq‘Ñ"ÿÚ   ? óª4¦ù‡;ýÔ­aH6’
¯ëxòPº°pp-LæsÊÿ DÖ7:,ûž«ðwZÃ›-FÈ¨Øðf:‹ß¦šè¸*¹Û”Énó¯¿Âùó†ñ&¶£AiÌ39Ž‡ÙÛ”Ï.«ÜþÆ6³§PT$‚5ê‹žæçKw±Ñµ£¡û÷©a5¡9tDB„ÀAB B„€Lsá<¨ª±*p|à¹Þ8 ÜÅÿ 
C!sÜK"=Jæòï¾—Æ9í‰ŒÄNl×n¹ü[HÒ;÷W¸…Fîá ¼÷ôÕbbñRH6ëÓªÆZÒ¦*¤´óßÞû,ªµãen«š	ÓQ§—%B¸ßšèÌˆèÃˆ(UK«ù‰õ5L™ Æý#ïeàCˆÍ—cßèµx/Ä_,¹ ÎäLÍï~~¥?ê?1¡Ìs€ {·íÔÿ z—šŠ~sgsV8_þZ•n2‡7ôé•àë¾ ž–^³ð§¡@‡Ó€hÜÄÃB¼9ôCC^Òàóvº\"Ý ºßáßâ˜ÐÆºCt%½¬£c~ž«:Íû_å}ó†ŠV¯8øsãºn
ùà´ÿ ÚÇY]ßâ¬&›ƒ‚Öwß¬ë<]BªÀB€„ !	                                                                                                                                                                       
ÿØÿà JFIF      ÿÛ „ 	 ( %!1!%)+...383-7(-.+



-%%--------------------------------------------------ÿÀ  ·" ÿÄ               ÿÄ 6     !1AQa"q‘±ð¡ÁÑ2Bá#Rb‚ñr ÿÄ              ÿÄ $         !1A2Qaq‘Ñ"ÿÚ   ? óª4¦ù‡;ýÔ­aH6’
¯ëxòPº°pp-LæsÊÿ DÖ7:,ûž«ðwZÃ›-FÈ¨Øðf:‹ß¦šè¸*¹Û”Énó¯¿Âùó†ñ&¶£AiÌ39Ž‡ÙÛ”Ï.«ÜþÆ6³§PT$‚5ê‹žæçKw±Ñµ£¡û÷©a5¡9tDB„ÀAB B„€Lsá<¨ª±*p|à¹Þ8 ÜÅÿ 
C!sÜK"=Jæòï¾—Æ9í‰ŒÄNl×n¹ü[HÒ;÷W¸…Fîá ¼÷ôÕbbñRH6ëÓªÆZÒ¦*¤´óßÞû,ªµãen«š	ÓQ§—%B¸ßšèÌˆèÃˆ(UK«ù‰õ5L™ Æý#ïeàCˆÍ—cßèµx/Ä_,¹ ÎäLÍï~~¥?ê?1¡Ìs€ {·íÔÿ z—šŠ~sgsV8_þZ•n2‡7ôé•àë¾ ž–^³ð§¡@‡Ó€hÜÄÃB¼9ôCC^Òàóvº\"Ý ºßáßâ˜ÐÆºCt%½¬£c~ž«:Íû_å}ó†ŠV¯8øsãºn
ùà´ÿ ÚÇY]ßâ¬&›ƒ‚Öwß¬ë<]BªÀB€„ !	                                                                                                                                                                       
<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', '/www/wwwroot/mycarthage.com/cron/order_notifications.log');

define('DB_HOST', 'localhost');
define('DB_NAME', 'yopcwlcc_card');
define('DB_USER', 'yopcwlcc_card');
define('DB_PASS', 'aduadu123Ms');
define('TELEGRAM_BOT_TOKEN', '8336882275:AAH3yNgFUAlQhBHyQgZbL5trILP5_WRcXUM');
define('TELEGRAM_CHAT_ID', '-4864691253');

// Database connection
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (!$conn) {
    error_log("DB connection failed: " . mysqli_connect_error());
    exit;
}

// Create payment_notifications table if not exists
$q = "CREATE TABLE IF NOT EXISTS `payment_notifications` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    `entity_type` VARCHAR(50) NOT NULL,
    `entity_id` BIGINT UNSIGNED NOT NULL,
    `telegram_message_id` BIGINT NOT NULL,
    `sent_status` TINYINT(1) NOT NULL DEFAULT 0,
    `feedback` TEXT DEFAULT NULL,
    `created_at` TIMESTAMP NULL DEFAULT NULL,
    `updated_at` TIMESTAMP NULL DEFAULT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `entity_unique` (`entity_type`, `entity_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;";
if (!mysqli_query($conn, $q)) {
    error_log("Failed to create payment_notifications table: " . mysqli_error($conn));
}

// Check if feedback column exists before adding
$q = "SHOW COLUMNS FROM `payment_notifications` LIKE 'feedback'";
$r = mysqli_query($conn, $q);
if ($r && mysqli_num_rows($r) == 0) {
    $q = "ALTER TABLE `payment_notifications` ADD COLUMN `feedback` TEXT DEFAULT NULL AFTER `sent_status`";
    if (!mysqli_query($conn, $q)) {
        error_log("Failed to add feedback column: " . mysqli_error($conn));
    }
}

// Helper Functions
function get_user_name($user_id, $conn) {
    $user_id = mysqli_real_escape_string($conn, $user_id);
    $q = "SELECT CONCAT(COALESCE(firstname, ''), ' ', COALESCE(lastname, '')) AS user_name, phone, username FROM users WHERE id='$user_id'";
    $r = mysqli_query($conn, $q);
    if ($r && mysqli_num_rows($r) > 0) {
        $row = mysqli_fetch_assoc($r);
        return [
            'name' => trim($row['user_name']) ?: ($row['username'] ?: "User ID: $user_id"),
            'phone' => $row['phone'] ?: "N/A"
        ];
    }
    error_log("No user found for ID $user_id");
    return ['name' => "User ID: $user_id", 'phone' => "N/A"];
}

function get_gateway_name($pmid, $conn) {
    if ($pmid == -1 || is_null($pmid)) return "Wallet";
    $pmid = mysqli_real_escape_string($conn, $pmid);
    $g = mysqli_query($conn, "SELECT name FROM gateways WHERE id='$pmid'");
    if ($g && mysqli_num_rows($g) > 0) return mysqli_fetch_assoc($g)['name'];
    error_log("No gateway found for ID $pmid");
    return "Unknown";
}

function get_phone_number($info, $conn) {
    if (!$info) return "N/A";
    $info_data = json_decode($info, true);
    if (json_last_error() === JSON_ERROR_NONE && is_array($info_data)) {
        $first_key = array_key_first($info_data);
        if ($first_key && isset($info_data[$first_key]['value'])) {
            return $info_data[$first_key]['value'];
        }
    }
    error_log("Failed to parse info JSON or no phone number found: " . json_last_error_msg());
    return "N/A";
}

function get_category_name($detailable_id, $conn) {
    $detailable_id = mysqli_real_escape_string($conn, $detailable_id);
    $q = "SELECT c.name 
          FROM categories c 
          JOIN top_ups t ON c.id = t.category_id 
          JOIN top_up_services tus ON t.id = tus.top_up_id 
          WHERE tus.id = '$detailable_id'";
    $r = mysqli_query($conn, $q);
    if ($r && mysqli_num_rows($r) > 0) {
        return mysqli_fetch_assoc($r)['name'];
    }
    error_log("No category found for detailable_id: $detailable_id");
    return "N/A";
}

function send_telegram_with_keyboard($msg, $entity_id, $entity_type, $conn) {
    $keyboard = [
        'inline_keyboard' => [
            [
                ['text' => '✅ موافقة', 'callback_data' => "approve_{$entity_type}_{$entity_id}"],
                ['text' => '❌ إلغاء', 'callback_data' => "cancel_{$entity_type}_{$entity_id}"]
            ]
        ]
    ];
    $encoded_keyboard = json_encode($keyboard);

    $url = "https://api.telegram.org/bot" . TELEGRAM_BOT_TOKEN . "/sendMessage";
    $payload = [
        'chat_id' => TELEGRAM_CHAT_ID,
        'text' => $msg,
        'parse_mode' => 'Markdown',
        'reply_markup' => $encoded_keyboard
    ];
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $res = curl_exec($ch);
    if ($res === false) {
        error_log("Telegram sendMessage failed for $entity_type ID $entity_id: " . curl_error($ch));
        return false;
    }
    $response = json_decode($res, true);
    if (isset($response['ok']) && $response['ok'] && isset($response['result']['message_id'])) {
        $q = "INSERT INTO payment_notifications (entity_type, entity_id, telegram_message_id, sent_status, created_at, updated_at) 
              VALUES ('$entity_type', $entity_id, " . $response['result']['message_id'] . ", 1, NOW(), NOW())
              ON DUPLICATE KEY UPDATE telegram_message_id = " . $response['result']['message_id'] . ", sent_status = 1, updated_at = NOW()";
        if (!mysqli_query($conn, $q)) {
            error_log("Failed to save payment notification for $entity_type ID $entity_id: " . mysqli_error($conn));
        }
        curl_close($ch);
        return true;
    }
    error_log("Telegram sendMessage response error for $entity_type ID $entity_id: " . json_encode($response));
    curl_close($ch);
    return false;
}

// Process new orders
$q = "SELECT o.id, o.user_id, o.amount, o.payment_method_id, o.created_at, o.info 
      FROM orders o 
      LEFT JOIN payment_notifications pn ON pn.entity_type = 'order' AND pn.entity_id = o.id 
      WHERE o.payment_status = 1 AND o.status = 0 AND (pn.sent_status IS NULL OR pn.sent_status = 0) 
      AND o.created_at >= NOW() - INTERVAL 1 DAY 
      ORDER BY o.created_at DESC LIMIT 10";
$r = mysqli_query($conn, $q);
if ($r && mysqli_num_rows($r) > 0) {
    error_log("Found " . mysqli_num_rows($r) . " new orders to notify");
    while ($row = mysqli_fetch_assoc($r)) {
        $order_id = $row['id'];
        $q = "SELECT od.name as product_name, od.price, od.qty, od.detailable_id 
              FROM order_details od 
              WHERE od.order_id = '$order_id'";
        $r_details = mysqli_query($conn, $q);
        if ($r_details && mysqli_num_rows($r_details) > 0) {
            $details = mysqli_fetch_assoc($r_details);
            $user_info = get_user_name($row['user_id'], $conn);
            $user_name = $user_info['name'];
            $gateway = get_gateway_name($row['payment_method_id'], $conn);
            $phone = get_phone_number($row['info'], $conn);
            $category = get_category_name($details['detailable_id'], $conn);
            $amount = number_format($row['amount'], 2);
            $price = number_format($details['price'], 2);
            $formatted_time = date('Y-m-d H:i:s', strtotime($row['created_at']));

            $msg = "🔔 *طلب جديد!*\n\n";
            $msg .= "🛒 *رقم الطلب*: $order_id\n";
            $msg .= "👤 *العميل*: $user_name\n";
            $msg .= "📞 *رقم الهاتف*: [$phone](tel:$phone)\n";
            $msg .= "🏷️ *الفئة*: $category\n";
            $msg .= "📦 *المنتج*: {$details['product_name']}\n";
            $msg .= "💰 *السعر*: $price TND\n";
            $msg .= "📏 *الكمية*: {$details['qty']}\n";
            $msg .= "💵 *الإجمالي*: $amount TND\n";
            $msg .= "📅 *التاريخ*: $formatted_time\n";
            $msg .= "💳 *طريقة الدفع*: $gateway\n";

            if (send_telegram_with_keyboard($msg, $order_id, 'order', $conn)) {
                error_log("Successfully sent Telegram notification for order ID $order_id");
            } else {
                error_log("Failed to send Telegram notification for order ID $order_id");
            }
        } else {
            error_log("No order details found for order ID $order_id");
        }
    }
} elseif ($r === false) {
    error_log("New orders query failed: " . mysqli_error($conn));
} else {
    error_log("No new orders found");
}

mysqli_close($conn);
?>