<?php
global $connection, $data, $text, $from_id, $admin, $userInfo, $message_id, $mainValues, $buttonValues, $cancelKey, $removeKeyboard, $fileid, $caption, $filetype;

// لود توابع کمکی تیکت
include_once __DIR__ . '/ticket_helpers.php';


// --- Start of Range 2855 to 2965 ---
if ($data == "ticketsList" and ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $ticketSection = json_encode(['inline_keyboard' => [
        [
            ['text' => "تیکت های باز", 'callback_data' => "openTickets"],
            ['text' => "تیکت های جدید", 'callback_data' => "newTickets"]
        ],
        [
            ['text' => "همه ی تیکت ها", 'callback_data' => "allTickets"],
            ['text' => "دسته بندی تیکت ها", 'callback_data' => "ticketsCategory"]
        ],
        [['text' => $buttonValues['back_button'], 'callback_data' => "managePanel"]]
    ]]);
    editText($message_id, "به بخش تیکت ها خوش اومدید، 
    
🚪 /start
    ", $ticketSection);
}
if ($data == 'ticketsCategory' and ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'TICKETS_CATEGORY'");
    $stmt->execute();
    $ticketCategory = $stmt->get_result();
    $stmt->close();
    $keys = array();
    $keys[] = [['text' => "حذف", 'callback_data' => "NetFreedomVPN"], ['text' => "دسته بندی", 'callback_data' => "NetFreedomVPN"]];

    if ($ticketCategory->num_rows > 0) {
        while ($row = $ticketCategory->fetch_assoc()) {
            $rowId = $row['id'];
            $ticketName = $row['value'];
            $keys[] = [['text' => "❌", 'callback_data' => "delTicketCat_$rowId"], ['text' => $ticketName, 'callback_data' => "NetFreedomVPN"]];
        }
    } else {
        $keys[] = [['text' => "دسته بندی یافت نشد", 'callback_data' => "NetFreedomVPN"]];
    }
    $keys[] = [['text' => "افزودن دسته بندی", 'callback_data' => "addTicketCategory"]];
    $keys[] = [['text' => $buttonValues['back_button'], 'callback_data' => "ticketsList"]];

    $keys = json_encode(['inline_keyboard' => $keys]);
    editText($message_id, "دسته بندی تیکت ها", $keys);
}
if ($data == "addTicketCategory" and ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    setUser('addTicketCategory');
    editText($message_id, "لطفا اسم دسته بندی را وارد کنید");
}
if ($userInfo['step'] == "addTicketCategory" and ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $stmt = $connection->prepare("INSERT INTO `setting` (`type`, `value`) VALUES ('TICKETS_CATEGORY', ?)");
    $stmt->bind_param("s", $text);
    $stmt->execute();
    $stmt->close();
    setUser();
    sendMessage($mainValues['saved_successfuly']);
    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'TICKETS_CATEGORY'");
    $stmt->execute();
    $ticketCategory = $stmt->get_result();
    $stmt->close();

    $keys = array();
    $keys[] = [['text' => "حذف", 'callback_data' => "NetFreedomVPN"], ['text' => "دسته بندی", 'callback_data' => "NetFreedomVPN"]];

    if ($ticketCategory->num_rows > 0) {
        while ($row = $ticketCategory->fetch_assoc()) {

            $rowId = $row['id'];
            $ticketName = $row['value'];
            $keys[] = [['text' => "❌", 'callback_data' => "delTicketCat_$rowId"], ['text' => $ticketName, 'callback_data' => "NetFreedomVPN"]];
        }
    } else {
        $keys[] = [['text' => "دسته بندی یافت نشد", 'callback_data' => "NetFreedomVPN"]];
    }
    $keys[] = [['text' => "افزودن دسته بندی", 'callback_data' => "addTicketCategory"]];
    $keys[] = [['text' => $buttonValues['back_button'], 'callback_data' => "ticketsList"]];

    $keys = json_encode(['inline_keyboard' => $keys]);
    sendMessage("دسته بندی تیکت ها", $keys);
}
if (preg_match("/^delTicketCat_(\d+)/", (string)$data, $match) and ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $stmt = $connection->prepare("DELETE FROM `setting` WHERE `id` = ?");
    $stmt->bind_param("i", $match[1]);
    $stmt->execute();
    $stmt->close();

    alert("با موفقیت حذف شد");


    $stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'TICKETS_CATEGORY'");
    $stmt->execute();
    $ticketCategory = $stmt->get_result();
    $stmt->close();

    $keys = array();
    $keys[] = [['text' => "حذف", 'callback_data' => "NetFreedomVPN"], ['text' => "دسته بندی", 'callback_data' => "NetFreedomVPN"]];

    if ($ticketCategory->num_rows > 0) {
        while ($row = $ticketCategory->fetch_assoc()) {

            $rowId = $row['id'];
            $ticketName = $row['value'];
            $keys[] = [['text' => "❌", 'callback_data' => "delTicketCat_$rowId"], ['text' => $ticketName, 'callback_data' => "NetFreedomVPN"]];
        }
    } else {
        $keys[] = [['text' => "دسته بندی یافت نشد", 'callback_data' => "NetFreedomVPN"]];
    }
    $keys[] = [['text' => "افزودن دسته بندی", 'callback_data' => "addTicketCategory"]];
    $keys[] = [['text' => $buttonValues['back_button'], 'callback_data' => "ticketsList"]];

    $keys = json_encode(['inline_keyboard' => $keys]);
    editText($message_id, "دسته بندی تیکت ها", $keys);
}

// --- Start of Range 2966 to 3141 ---
if ($data == "openTickets" and ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $data = "showTickets_open_1";
} elseif ($data == "newTickets" and ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $data = "showTickets_new_1";
} elseif ($data == "allTickets" and ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $data = "showTickets_all_1";
}

if (preg_match('/^showTickets_(?<type>[^_]+)_(?<page>\d+)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $type = $match['type'];
    $page = intval($match['page']);
    $limit = 8;
    $offset = ($page - 1) * $limit;

    if ($type == "open") {
        $state_cond = "state != 2";
    } elseif ($type == "new") {
        $state_cond = "state = 0";
    } else {
        $state_cond = "1=1";
    }

    $stmt = $connection->prepare("SELECT COUNT(DISTINCT `user_id`) as total FROM `chats` WHERE $state_cond");
    $stmt->execute();
    $total_users = $stmt->get_result()->fetch_assoc()['total'];
    $stmt->close();

    $stmt = $connection->prepare("SELECT `user_id`, MAX(`create_date`) as max_date FROM `chats` WHERE $state_cond GROUP BY `user_id` ORDER BY max_date DESC LIMIT ? OFFSET ?");
    $stmt->bind_param("ii", $limit, $offset);
    $stmt->execute();
    $users_res = $stmt->get_result();
    $stmt->close();

    $keyboard = [];
    while ($row = $users_res->fetch_assoc()) {
        $u_id = $row['user_id'];

        $stmt_u = $connection->prepare("SELECT `name`, `username` FROM `users` WHERE `userid` = ?");
        $stmt_u->bind_param("i", $u_id);
        $stmt_u->execute();
        $u_row = $stmt_u->get_result()->fetch_assoc();
        $stmt_u->close();

        $u_name = $u_row['name'] ?? "کاربر بی نام";
        $u_username = ($u_row['username'] ?? "ندارد") != "ندارد" ? " (@" . $u_row['username'] . ")" : "";
        $btn_text = "👤 $u_name $u_username ($u_id)";

        $keyboard[] = [['text' => $btn_text, 'callback_data' => "userTickets_{$u_id}_{$type}_{$page}"]];
    }

    $pag_row = [];
    if ($page > 1) {
        $prev_page = $page - 1;
        $pag_row[] = ['text' => "◀️ قبلی", 'callback_data' => "showTickets_{$type}_{$prev_page}"];
    }
    $pag_row[] = ['text' => "صفحه $page", 'callback_data' => "NetFreedomVPN"];
    if (($offset + $limit) < $total_users) {
        $next_page = $page + 1;
        $pag_row[] = ['text' => "بعدی ▶️", 'callback_data' => "showTickets_{$type}_{$next_page}"];
    }
    if (!empty($pag_row)) {
        $keyboard[] = $pag_row;
    }

    $keyboard[] = [['text' => "🔙 بازگشت به منوی تیکت‌ها", 'callback_data' => "ticketsList", 'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']];

    $type_fa = ($type == "open") ? "باز" : (($type == "new") ? "جدید" : "همه");
    $text_msg = "📋 <b>لیست کاربران دارای تیکت $type_fa (صفحه $page):</b>\n\nتعداد کل کاربران: $total_users";

    editText($message_id, $text_msg, json_encode(['inline_keyboard' => $keyboard]), "HTML");
    exit();
}

if (preg_match('/^userTickets_(?<user_id>\d+)_(?<type>[^_]+)_(?<page>\d+)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $u_id = $match['user_id'];
    $type = $match['type'];
    $page = intval($match['page']);

    if ($type == "open") {
        $state_cond = "state != 2";
    } elseif ($type == "new") {
        $state_cond = "state = 0";
    } else {
        $state_cond = "1=1";
    }

    $stmt = $connection->prepare("SELECT * FROM `chats` WHERE `user_id` = ? AND $state_cond ORDER BY `create_date` DESC");
    $stmt->bind_param("i", $u_id);
    $stmt->execute();
    $tickets_res = $stmt->get_result();
    $stmt->close();

    $stmt_u = $connection->prepare("SELECT `name`, `username` FROM `users` WHERE `userid` = ?");
    $stmt_u->bind_param("i", $u_id);
    $stmt_u->execute();
    $u_row = $stmt_u->get_result()->fetch_assoc();
    $stmt_u->close();

    $u_name = $u_row['name'] ?? "کاربر بی نام";

    $keyboard = [];
    while ($ticket = $tickets_res->fetch_assoc()) {
        $t_id = $ticket['id'];
        $t_title = $ticket['title'];
        $t_state = $ticket['state'];

        $state_fa = ($t_state == 0) ? "🟡 جدید" : (($t_state == 1) ? "🟢 پاسخ داده شده" : "🔴 بسته شده");
        $btn_text = "🎫 #$t_id | $t_title ($state_fa)";

        $keyboard[] = [['text' => $btn_text, 'callback_data' => "viewTicket_{$t_id}_{$type}_{$page}_{$u_id}"]];
    }

    $keyboard[] = [['text' => "🔙 بازگشت به لیست کاربران", 'callback_data' => "showTickets_{$type}_{$page}", 'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']];

    $text_msg = "🎫 <b>لیست تیکت‌های کاربر $u_name (آیدی: $u_id):</b>\n\nبرای مشاهده جزئیات گفتگو و پاسخ روی تیکت مورد نظر ضربه بزنید.";
    editText($message_id, $text_msg, json_encode(['inline_keyboard' => $keyboard]), "HTML");
    exit();
}

if (preg_match('/^closeTicket_(?<id>\d+)(?:_(?<type>[^_]+)_(?<page>\d+)_(?<user_id>\d+))?/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $chatRowId = $match['id'];

    $stmt = $connection->prepare("SELECT * FROM `chats` WHERE `id` = ?");
    $stmt->bind_param("i", $chatRowId);
    $stmt->execute();
    $ticketInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    $userId = $ticketInfo['user_id'];
    $title = $ticketInfo['title'];
    $category = $ticketInfo['category'];

    $stmt = $connection->prepare("UPDATE `chats` SET `state` = 2 WHERE `id` = ?");
    $stmt->bind_param("i", $chatRowId);
    $stmt->execute();
    $stmt->close();

    $ticketClosed = "[$title] <i>$category</i> \n\n" . "این تیکت بسته شد\n به این تیکت رأی بدهید";
    $keys = json_encode(['inline_keyboard' => [
        [['text' => "بسیار بد 😠", 'callback_data' => "rate_{$chatRowId}_1"]],
        [['text' => "بد 🙁", 'callback_data' => "rate_{$chatRowId}_2"]],
        [['text' => "خوب 😐", 'callback_data' => "rate_{$chatRowId}_3"]],
        [['text' => "بسیار خوب 😃", 'callback_data' => "rate_{$chatRowId}_4"]],
        [['text' => "عالی 🤩", 'callback_data' => "rate_{$chatRowId}_5"]]
    ]]);
    sendMessage($ticketClosed, $keys, 'html', $userId);

    if (isset($match['type'])) {
        $back_cb = "userTickets_{$match['user_id']}_{$match['type']}_{$match['page']}";
        editKeys(json_encode(['inline_keyboard' => [
            [['text' => "🔒 تیکت بسته شد", 'callback_data' => "NetFreedomVPN"]],
            [['text' => "🔙 بازگشت", 'callback_data' => $back_cb, 'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']]
        ]]));
        editKeys(json_encode(['inline_keyboard' => [
            [['text' => "تیکت بسته شد", 'callback_data' => "NetFreedomVPN"]]
        ]]));
    }
    exit();
}

// هندلر لغو شیشه‌ای پاسخ ادمین
if (preg_match('/^cancelAnswer_(?<id>\d+)_(?<type>[^_]+)_(?<page>\d+)_(?<user_id>\d+)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    setUser();
    delMessage();
    $data = "viewTicket_{$match['id']}_{$match['type']}_{$match['page']}_{$match['user_id']}";
}

if (preg_match('/^reply_(?<id>\d+)(?:_(?<type>[^_]+)_(?<page>\d+)_(?<user_id>\d+))?/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $t_id = $match['id'];
    $type = $match['type'] ?? "open";
    $page = $match['page'] ?? "1";
    $u_id = $match['user_id'] ?? "0";

    if ($u_id == "0") {
        $stmt = $connection->prepare("SELECT `user_id` FROM `chats` WHERE `id` = ?");
        $stmt->bind_param("i", $t_id);
        $stmt->execute();
        $ticket_row = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        if ($ticket_row) {
            $u_id = $ticket_row['user_id'];
        }
    }

    $cancelInlineKey = json_encode(['inline_keyboard' => [
        [['text' => "❌ انصراف", 'callback_data' => "cancelAnswer_{$t_id}_{$type}_{$page}_{$u_id}"]]
    ]]);
    $res = sendMessage("لطفا پیام خود را ارسال کنید ✍️", $cancelInlineKey);
    $prompt_msg_id = $res->result->message_id ?? null;

    setUser("answer_" . json_encode([
        'id' => $t_id,
        'type' => $type,
        'page' => $page,
        'user_id' => $u_id,
        'prompt_id' => $message_id,
        'prompt_msg_id' => $prompt_msg_id
    ], JSON_UNESCAPED_UNICODE));
    exit();
}

if ($text == $buttonValues['cancel'] && preg_match('/^answer_/', (string)$userInfo['step'])) {
    setUser();
    sendMessage("عملیات لغو شد ❌", $removeKeyboard);
    exit();
}

if (preg_match('/^answer_(?P<json>.*)/', (string)$userInfo['step'], $match) and $from_id == $admin and $text != $buttonValues['cancel']) {
    $d = json_decode($match['json'], true);
    if (!$d) {
        $d = [
            'id' => $match['json'],
            'type' => 'open',
            'page' => 1,
            'user_id' => 0,
            'prompt_id' => null,
            'prompt_msg_id' => null
        ];
    }

    $chatRowId = $d['id'];
    // حذف پیام ادمین
    bot('deleteMessage', ['chat_id' => $from_id, 'message_id' => $message_id]);
    // حذف پیام prompt
    if (isset($d['prompt_msg_id']) && $d['prompt_msg_id'] !== null) {
        delMessage($d['prompt_msg_id'], $from_id);
    }

    $stmt = $connection->prepare("SELECT * FROM `chats` WHERE `id` = ?");
    $stmt->bind_param("i", $chatRowId);
    $stmt->execute();
    $ticketInfo = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    $userId = $ticketInfo['user_id'];
    $ticketTitle = $ticketInfo['title'];
    $ticketCat = $ticketInfo['category'];
    $time = time();

    // ذخیره پیام ادمین در دیتابیس
    if ($fileid === null) {
        $stmt = $connection->prepare("INSERT INTO `chats_info` (`chat_id`,`sent_date`,`msg_type`,`text`) VALUES (?,?,'ADMIN',?)");
        $stmt->bind_param("iis", $chatRowId, $time, $text);
        $stmt->execute();
        $stmt->close();
    } else {
        $text_val = json_encode(['file_id' => $fileid, 'caption' => $caption, 'file_type' => $filetype], JSON_UNESCAPED_UNICODE);
        $stmt = $connection->prepare("INSERT INTO `chats_info` (`chat_id`,`sent_date`,`msg_type`,`text`) VALUES (?,?,'ADMIN',?)");
        $stmt->bind_param("iis", $chatRowId, $time, $text_val);
        $stmt->execute();
        $stmt->close();
    }

    // بروزرسانی وضعیت تیکت به "پاسخ داده شده"
    $stmt = $connection->prepare("UPDATE `chats` SET `state` = 1 WHERE `id` = ?");
    $stmt->bind_param("i", $chatRowId);
    $stmt->execute();
    $stmt->close();

    // ویرایش مکالمه هر دو طرف (ادمین و کاربر)
    updateConversationMessages($connection, $chatRowId, $admin, true, 'ADMIN');

    setUser();
    alert("پیام شما با موفقیت ارسال شد ✅", true);

    if ($d['prompt_id']) {
        $data = "viewTicket_{$chatRowId}_{$d['type']}_{$d['page']}_{$d['user_id']}";
        $message_id = $d['prompt_id'];
    } else {
        sendMessage("پیام شما با موفقیت ارسال شد ✅", $removeKeyboard);
    }
}


if (preg_match('/^viewTicket_(?<id>\d+)_(?<type>[^_]+)_(?<page>\d+)_(?<user_id>\d+)/', (string)$data, $match) && ($from_id == $admin || $userInfo['isAdmin'] == true)) {
    $t_id = $match['id'];
    $type = $match['type'];
    $page = intval($match['page']);
    $u_id = $match['user_id'];

    $stmt = $connection->prepare("SELECT * FROM `chats` WHERE `id` = ?");
    $stmt->bind_param("i", $t_id);
    $stmt->execute();
    $ticket = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    $stmt_u = $connection->prepare("SELECT `name`, `username` FROM `users` WHERE `userid` = ?");
    $stmt_u->bind_param("i", $u_id);
    $stmt_u->execute();
    $u_row = $stmt_u->get_result()->fetch_assoc();
    $stmt_u->close();

    $u_name = $u_row['name'] ?? "کاربر بی نام";
    $u_username = ($u_row['username'] ?? "ندارد") != "ندارد" ? " (@" . $u_row['username'] . ")" : "";

    $t_title = $ticket['title'];
    $t_category = $ticket['category'];
    $t_state = $ticket['state'];
    $t_rate = ($t_state == 2) ? "\nامتیاز کاربر: " . $ticket['rate'] : "";

    $stmt = $connection->prepare("SELECT * FROM `chats_info` WHERE `chat_id` = ? ORDER BY `sent_date` ASC");
    $stmt->bind_param("i", $t_id);
    $stmt->execute();
    $history_res = $stmt->get_result();
    $stmt->close();

    $transcript = "";
    $isFirst = true;
    while ($msg = $history_res->fetch_assoc()) {
        $sender = ($msg['msg_type'] == "USER") ? "👤 کاربر" : "👮‍♂️ ادمین";
        $text_val = $msg['text'];

        if (strpos($text_val, '{"file_id"') === 0) {
            $photo_data = json_decode($text_val, true);
            $caption_val = htmlspecialchars($photo_data['caption'] ?? "");
            $caption_val = preg_replace('/(vless|vmess|trojan|ss):\/\/[^\s]+/i', '<code>$0</code>', $caption_val);
            $text_val = "[ارسال تصویر] " . $caption_val;
        } else {
            $text_val = htmlspecialchars($text_val);
            $text_val = preg_replace('/(vless|vmess|trojan|ss):\/\/[^\s]+/i', '<code>$0</code>', $text_val);
        }

        if ($isFirst && $msg['msg_type'] == "USER" && trim($text_val) === trim($t_title)) {
            $isFirst = false;
            continue;
        }
        $isFirst = false;

        $date_fa = jdate("Y-m-d H:i", $msg['sent_date']);
        $transcript .= "<b>$sender:</b> $text_val <i>($date_fa)</i>\n";
    }

    $state_fa = ($t_state == 0) ? "🟡 جدید" : (($t_state == 1) ? "🟢 پاسخ داده شده" : "🔴 بسته شده");

    $text_msg = "🎫 <b>تیکت شماره #$t_id</b>\n"
        . "👤 <b>کاربر:</b> $u_name $u_username\n"
        . "🆔 <b>آیدی:</b> <code>$u_id</code>\n"
        . "📂 <b>دسته بندی:</b> $t_category\n"
        . "📌 <b>موضوع:</b> $t_title\n"
        . "🛡 <b>وضعیت:</b> $state_fa$t_rate\n"
        . "━━━━━━━━━━━━━━\n"
        . "💬 <b>تاریخچه گفتگو:</b>\n\n"
        . (empty($transcript) ? "<i>(گفتگویی یافت نشد)</i>" : $transcript);

    $keyboard = [];
    if ($t_state != 2) {
        $keyboard[] = [
            ['text' => "✍️ ادامه", 'callback_data' => "reply_{$t_id}_{$type}_{$page}_{$u_id}"],
            ['text' => "🔒 بستن تیکت", 'callback_data' => "closeTicket_{$t_id}_{$type}_{$page}_{$u_id}"]
        ];
    }
    $keyboard[] = [['text' => "🔙 بازگشت به لیست تیکت‌ها", 'callback_data' => "userTickets_{$u_id}_{$type}_{$page}", 'style' => 'danger', 'icon_custom_emoji_id' => '5352759161945867747']];

    editText($message_id, $text_msg, json_encode(['inline_keyboard' => $keyboard]), "HTML");
    exit();
}
