<?php
if($text == '📩 تیکت‌ها' && ($user->is_owner || $user->is_admin)) {
    adminShowTicketsPanel($chat_id);
    die;
}


if($data == 'admin_tickets_panel' && ($user->is_owner || $user->is_admin)) {
    adminShowTicketsPanel($chat_id, $message_id);
    answerCallbackQuery($query_id);
    die;
}


function adminShowTicketsPanel($chat_id, $message_id = null)
{
    global $pdo;
    $stmt = $pdo->query("SELECT COUNT(DISTINCT tracking_code) FROM `support_tickets` WHERE `status` IN ('pending', 'seen')");
    $countPending = $stmt->fetchColumn();
    $stmt        = $pdo->query("SELECT COUNT(DISTINCT tracking_code) FROM `support_tickets` WHERE `status` = 'closed'");
    $countClosed = $stmt->fetchColumn();
    $stmt  = $pdo->query("SELECT COUNT(DISTINCT tracking_code) FROM `support_tickets`");
    $total = $stmt->fetchColumn();
    $countReplied = $total - $countPending - $countClosed;

if($countReplied < 0)
        $countReplied = 0;
    $text = "🛡 *مدیریت تیکت‌های پشتیبانی*\n\n" .
        "📊 *آمار کلی:*\n" .
        "🔸 در انتظار پاسخ: *$countPending*\n" .
        "✅ پاسخ داده شده: *$countReplied*\n" .
        "🔒 بسته شده: *$countClosed*\n\n" .
        "👇 جهت مدیریت، یک بخش را انتخاب کنید:";
    $keyboard = json_encode([
        'inline_keyboard' => [
            [
                ['text' => "📩 در انتظار پاسخ ($countPending)", 'callback_data' => 'admin_tickets_list:pending:1']
            ],
            [
                ['text' => "✅ پاسخ داده شده ($countReplied)", 'callback_data' => 'admin_tickets_list:replied:1'],
                ['text' => "🔒 بسته شده ($countClosed)", 'callback_data' => 'admin_tickets_list:closed:1']
            ]
        ]
    ]);

if($message_id) {
        editMessage($chat_id, $message_id, $text, $keyboard);
} else {
        sendMessage($chat_id, $text, $keyboard);
}

}


if(strpos($data, 'admin_tickets_list:') === 0 && ($user->is_owner || $user->is_admin)) {
    $parts  = explode(':', $data);
    $type   = $parts[1];
    $page   = intval($parts[2]);
    $limit  = 10;
    $offset = ($page - 1) * $limit;

if($type == 'pending') {
        $sql = "SELECT tracking_code, ANY_VALUE(user_id) as user_id, ANY_VALUE(subject) as subject, MAX(created_at) as last_activity FROM support_tickets WHERE status IN ('pending', 'seen') GROUP BY tracking_code ORDER BY last_activity ASC LIMIT $limit OFFSET $offset";
        $countSql = "SELECT COUNT(DISTINCT tracking_code) FROM support_tickets WHERE status IN ('pending', 'seen')";
        $title = "📩 تیکت‌های در انتظار پاسخ";
} elseif ($type == 'closed') {
        $sql      = "SELECT tracking_code, ANY_VALUE(user_id) as user_id, ANY_VALUE(subject) as subject, MAX(created_at) as last_activity FROM support_tickets WHERE status = 'closed' GROUP BY tracking_code ORDER BY last_activity DESC LIMIT $limit OFFSET $offset";
        $countSql = "SELECT COUNT(DISTINCT tracking_code) FROM support_tickets WHERE status = 'closed'";
        $title    = "🔒 تیکت‌های بسته شده";
} else {
        $sql = "SELECT tracking_code, ANY_VALUE(user_id) as user_id, ANY_VALUE(subject) as subject, MAX(created_at) as last_activity FROM support_tickets GROUP BY tracking_code HAVING SUM(CASE WHEN status IN ('pending', 'seen') THEN 1 ELSE 0 END) = 0 AND MAX(status) != 'closed' ORDER BY last_activity DESC LIMIT $limit OFFSET $offset";
        $stmtTotal = $pdo->query("SELECT COUNT(DISTINCT tracking_code) FROM support_tickets");
        $total = $stmtTotal->fetchColumn();
        $stmtP = $pdo->query("SELECT COUNT(DISTINCT tracking_code) FROM support_tickets WHERE status IN ('pending', 'seen')");
        $cP = $stmtP->fetchColumn();
        $stmtC      = $pdo->query("SELECT COUNT(DISTINCT tracking_code) FROM support_tickets WHERE status = 'closed'");
        $cC         = $stmtC->fetchColumn();
        $totalCount = $total - $cP - $cC;
        $title      = "✅ تیکت‌های پاسخ داده شده";
}


if(!isset($totalCount)) {
        $stmt       = $pdo->query($countSql);
        $totalCount = $stmt->fetchColumn();
}

    try {
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
        $tickets = $stmt->fetchAll();
} catch (Exception $e) {
        $sql = str_replace("ANY_VALUE(", "", str_replace(") as", " as", $sql));
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
        $tickets = $stmt->fetchAll();
}


if(empty($tickets) && $page == 1) {
        answerCallbackQuery($query_id, "📭 لیست خالی است.", true);
        return;
}

    $buttons = [];

foreach($tickets as $t) {
        $buttons[] = [['text' => "{$t->subject} (#{$t->tracking_code})", 'callback_data' => "admin_view_ticket:{$t->tracking_code}:{$type}"]];
}

    $nav = [];

if($page > 1) {
        $nav[] = ['text' => '➡️ قبلی', 'callback_data' => "admin_tickets_list:$type:" . ($page - 1)];
}


if($page * $limit < $totalCount) {
        $nav[] = ['text' => 'بعدی ⬅️', 'callback_data' => "admin_tickets_list:$type:" . ($page + 1)];
}


if(!empty($nav))
        $buttons[] = $nav;
    $buttons[] = [['text' => '🔙 بازگشت', 'callback_data' => 'admin_tickets_panel']];
    $keyboard = json_encode(['inline_keyboard' => $buttons]);
    editMessage($chat_id, $message_id, "$title\n\nتعداد کل: $totalCount", $keyboard);
    answerCallbackQuery($query_id);
    die;
}


if(strpos($data, 'admin_view_ticket:') === 0 && ($user->is_owner || $user->is_admin)) {
    $parts    = explode(':', $data);
    $code     = $parts[1];
    $backType = $parts[2] ?? 'pending';
    $stmt = $pdo->prepare("UPDATE `support_tickets` SET `status` = 'seen' WHERE `tracking_code` = ? AND `status` = 'pending'");
    $stmt->execute([$code]);
    $updatedCount = $stmt->rowCount();
    $stmt = $pdo->prepare("SELECT * FROM `support_tickets` WHERE `tracking_code` = ? ORDER BY `created_at` ASC");
    $stmt->execute([$code]);
    $msgs = $stmt->fetchAll();

if($updatedCount > 0 && !empty($msgs)) {
        $firstMsg = $msgs[0]; 
        sendMessage($firstMsg->user_id, "👁 *تیکت شما دیده شد!*\n\n" .
                                        "🔖 کد تیکت: $code\n" .
                                        "📌 موضوع: {$firstMsg->subject}\n\n" .
                                        "ادمین تیکت شما را مشاهده کرد. لطفاً منتظر پاسخ بمانید.");
}


if(!$msgs) {
        answerCallbackQuery($query_id, "❌ تیکت یافت نشد.", true);
        return;
}

    $first   = $msgs[0];
    $subject = $first->subject;
    $userId  = $first->user_id;
    $stmtStatus = $pdo->prepare("SELECT status FROM `support_tickets` WHERE `tracking_code` = ? ORDER BY `created_at` DESC LIMIT 1");
    $stmtStatus->execute([$code]);
    $currentStatus = $stmtStatus->fetch()->status;
    $statusText = match ($currentStatus) {
        'pending'  => 'در انتظار پاسخ',
        'seen'     => 'مشاهده شده',
        'answered' => 'پاسخ داده شده',
        'closed'   => 'بسته شده',
        default    => $currentStatus
};
    $text = "🔖 *مدیریت تیکت #$code*\n" .
        "👤 *کاربر:* [$userId](bale://user?id=$userId)\n" .
        "📌 *موضوع:* $subject\n" .
        "⏳ *وضعیت:* $statusText\n\n" .
        "➖➖➖➖➖➖➖➖➖➖\n\n";

foreach($msgs as $m) {
        $text .= "👤 *کاربر:*\n{$m->question}\n" .
            "📅 " . jdate("H:i Y/m/d", strtotime($m->created_at)) . "\n";

if($m->answer) {
            $text .= "\n🗣 *پشتیبانی:*\n{$m->answer}\n" .
                "📅 " . jdate("H:i Y/m/d", strtotime($m->answered_at)) . "\n";
}

        $text .= "\n──────────────────\n\n";
}


if(mb_strlen($text) > 4000) {
        $text = mb_substr($text, -4000);
        $text = "...\n" . $text;
}

    $keyboard   = [];
    $rowActions = [];

if($currentStatus != 'closed') {
        $rowActions[] = ['text' => '✍️ پاسخ دادن', 'callback_data' => "admin_reply_ticket:$code"];
        $rowActions[] = ['text' => '❌ بستن تیکت', 'callback_data' => "admin_close_ticket:$code"];
} else {
        $rowActions[] = ['text' => '🔓 بازگشایی مجدد', 'callback_data' => "admin_open_ticket:$code"];
}


if(!empty($rowActions))
        $keyboard[] = $rowActions;
    $keyboard[] = [['text' => '👤 مشاهده پروفایل کاربر', 'callback_data' => "admin_ticket_view_user_profile:$userId:$code:$backType"]];
    $keyboard[] = [['text' => '🔙 بازگشت به لیست', 'callback_data' => "admin_tickets_list:$backType:1"]];
    editMessage($chat_id, $message_id, $text, json_encode(['inline_keyboard' => $keyboard]));
    answerCallbackQuery($query_id);
    die;
}


if(strpos($data, 'admin_ticket_view_user_profile:') === 0 && ($user->is_owner || $user->is_admin)) {
    $parts        = explode(':', $data);
    $targetUserId = $parts[1] ?? null;
    $ticketCode   = $parts[2] ?? null;
    $backType     = $parts[3] ?? 'pending';

if(!$targetUserId || !$ticketCode) {
        answerCallbackQuery($query_id, "❌ داده‌های ناقص.", true);
        die;
}

    $stmt = $pdo->prepare("SELECT * FROM `users` WHERE `user_id` = ? LIMIT 1");
    $stmt->execute([$targetUserId]);
    $u = $stmt->fetch();

if(!$u) {
        answerCallbackQuery($query_id, "❌ کاربر یافت نشد.", true);
        die;
}

    $vipStatus   = $u->is_vip ? "فعال تا " . ($u->vip_expire ? jdate("H:i  Y/m/d", strtotime($u->vip_expire)) : "—") : "غیرفعال";
    $statusFlags = [];

if($u->is_owner)
        $statusFlags[] = "Owner";

if($u->is_admin)
        $statusFlags[] = "Admin";

if($u->is_blocked)
        $statusFlags[] = "Blocked";
    $profileText =
        "👤 *پروفایل کاربر*\n\n" .
        "🆔 کاربر: [$u->user_id](bale://user?id=$u->user_id)\n" .
        "📛 نام: " . ($u->full_name ?: "—") . "\n" .
        "🔖 یوزرنیم: " . ($u->username ? "@$u->username" : "—") . "\n" .
        "💰 موجودی: " . intval($u->coins) . " سکه\n" .
        "💎 وضعیت VIP: $vipStatus\n" .
        "📅 تاریخ عضویت: " . jdate("H:i  Y/m/d", strtotime($u->created_at)) . "\n";
    $kb = [
        [['text' => '🔙 برگشت به تیکت', 'callback_data' => "admin_view_ticket:$ticketCode:$backType"]],
    ];
    editMessage($chat_id, $message_id, $profileText, json_encode(['inline_keyboard' => $kb]));
    answerCallbackQuery($query_id);
    die;
}


if(strpos($data, 'admin_reply_ticket:') === 0 && ($user->is_owner || $user->is_admin)) {
    $code = explode(':', $data)[1];
    setStep($chat_id, "admin_reply_ticket:$code");
    $cancel = json_encode(['keyboard' => [[['text' => '🔙 بازگشت به مدیریت']]], 'resize_keyboard' => true]);
    sendMessage($chat_id, "✍️ لطفا متن پاسخ خود را بنویسید:", $cancel);
    answerCallbackQuery($query_id);
    die;
}


if(strpos($user->step, 'admin_reply_ticket:') === 0 && ($user->is_owner || $user->is_admin)) {

if($text == '🔙 بازگشت به مدیریت') {
        setStep($chat_id, 'none');
        sendMessage($chat_id, "عملیات لغو شد.", $admin_keyboard);
        die;
}

    $code = explode(':', $user->step)[1];
    $stmt = $pdo->prepare("UPDATE `support_tickets` SET `answer` = ?, `status` = 'answered', `answered_at` = NOW() WHERE `tracking_code` = ? AND `answer` IS NULL ORDER BY `created_at` DESC LIMIT 1");
    $stmt->execute([$text, $code]);

if($stmt->rowCount() == 0) {
        sendMessage($chat_id, "⚠️ پیامی برای پاسخگویی یافت نشد (همه پیام‌ها پاسخ داده شده‌اند).", $admin_keyboard);
} else {
        $stmtU = $pdo->prepare("SELECT user_id, subject FROM `support_tickets` WHERE `tracking_code` = ? LIMIT 1");
        $stmtU->execute([$code]);
        $tData = $stmtU->fetch();

if($tData) {
            $msg = "📨 *پاسخ جدید از پشتیبانی*\n\n" .
                "🔖 کد تیکت: $code\n" .
                "📌 موضوع: {$tData->subject}\n\n" .
                "🗣 پاسخ:\n$text";
            $userKb = json_encode([
                "inline_keyboard" => [
                    [['text' => '✍️ پاسخ دادن', 'callback_data' => "user_reply_ticket:$code"]],
                    [['text' => '📂 مشاهده گفتگو', 'callback_data' => "view_ticket:$code"]]
                ]
            ]);
            sendMessage($tData->user_id, $msg, $userKb);
}

        $stmtInfo = $pdo->prepare("SELECT * FROM `support_tickets` WHERE `tracking_code` = ? AND `answer` = ? ORDER BY `answered_at` DESC LIMIT 1");
        $stmtInfo->execute([$code, $text]);
        $ticketInfo = $stmtInfo->fetch();

if($ticketInfo) {
            $feedbackMsg = "✅ *پاسخ ثبت شد*\n\n" .
                "👤 کاربر: [{$ticketInfo->user_id}](bale://user?id={$ticketInfo->user_id})\n" .
                "🔖 کد: {$code}\n" .
                "📌 موضوع: {$ticketInfo->subject}\n\n" .
                "❓ پرسش کاربر:\n{$ticketInfo->question}\n\n" .
                "🗣 پاسخ شما:\n{$text}\n\n" .
                "📅 تاریخ: " . jdate("H:i  Y/m/d", time());
            $stmtStatus  = $pdo->prepare("SELECT status FROM `support_tickets` WHERE `tracking_code` = ? ORDER BY `created_at` DESC LIMIT 1");
            $stmtStatus->execute([$code]);
            $st       = $stmtStatus->fetch()->status ?? 'answered';
            $backType = 'pending'; 
            $admKb    = json_encode([
                "inline_keyboard" => [
                    [['text' => '📂 مشاهده گفتگو', 'callback_data' => "admin_view_ticket:$code:$backType"]],
                    [['text' => '🔙 بازگشت به لیست تیکت‌ها', 'callback_data' => "admin_tickets_list:$backType:1"]]
                ]
            ]);
            sendMessage($chat_id, $feedbackMsg, $admKb);
} else {
            $stmtStatus = $pdo->prepare("SELECT status FROM `support_tickets` WHERE `tracking_code` = ? ORDER BY `created_at` DESC LIMIT 1");
            $stmtStatus->execute([$code]);
            $st       = $stmtStatus->fetch()->status ?? 'answered';
            $backType = 'pending';
            $admKb    = json_encode([
                "inline_keyboard" => [
                    [['text' => '📂 مشاهده گفتگو', 'callback_data' => "admin_view_ticket:$code:$backType"]],
                    [['text' => '🔙 بازگشت به لیست تیکت‌ها', 'callback_data' => "admin_tickets_list:$backType:1"]]
                ]
            ]);
            sendMessage($chat_id, "✅ پاسخ با موفقیت ارسال شد.", $admKb);
}

}

    setStep($chat_id, 'none');
    die;
}


if(strpos($data, 'admin_close_ticket:') === 0 && ($user->is_owner || $user->is_admin)) {
    $code = explode(':', $data)[1];
    $stmt = $pdo->prepare("UPDATE `support_tickets` SET `status` = 'closed' WHERE `tracking_code` = ?");
    $stmt->execute([$code]);
    answerCallbackQuery($query_id, "✅ تیکت بسته شد.", true);
    adminShowTicketsPanel($chat_id, $message_id);
    $stmtU = $pdo->prepare("SELECT user_id FROM `support_tickets` WHERE `tracking_code` = ? LIMIT 1");
    $stmtU->execute([$code]);
    $uid = $stmtU->fetch()->user_id ?? null;

if($uid) {
        sendMessage($uid, "🔒 تیکت #$code توسط پشتیبانی بسته شد.");
}

    die;
}


if(strpos($data, 'admin_open_ticket:') === 0 && ($user->is_owner || $user->is_admin)) {
    $code = explode(':', $data)[1];
    $stmt = $pdo->prepare("UPDATE `support_tickets` SET `status` = 'answered' WHERE `tracking_code` = ?");
    $stmt->execute([$code]);
    answerCallbackQuery($query_id, "✅ تیکت بازگشایی شد.", true);
    adminShowTicketsPanel($chat_id, $message_id);
    die;
}

