<?php
/**
 * Telegram Mini App support-ticket helpers.
 * This file is safe to include from webhook, web panel, and miniapp API.
 */

if(!function_exists('bot_ticket_miniapp_base_url')){
function bot_ticket_miniapp_base_url(){
    if(defined('BOT_PUBLIC_BASE_URL') && trim((string)BOT_PUBLIC_BASE_URL) !== ''){
        return rtrim((string)BOT_PUBLIC_BASE_URL, '/');
    }
    if(function_exists('bot_admin_tools_base_url')){
        $base = bot_admin_tools_base_url();
        if($base !== '') return rtrim($base, '/');
    }
    $host = $_SERVER['HTTP_HOST'] ?? '';
    if($host === '') return '';
    $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (isset($_SERVER['SERVER_PORT']) && (int)$_SERVER['SERVER_PORT'] === 443);
    $scheme = $https ? 'https' : 'http';
    $script = str_replace('\\','/', (string)($_SERVER['SCRIPT_NAME'] ?? ''));
    $dir = rtrim(dirname($script), '/');
    if(preg_match('~/miniapp/tickets$~', $dir)) $dir = rtrim(dirname(dirname($dir)), '/');
    elseif(preg_match('~/admin$~', $dir)) $dir = rtrim(dirname($dir), '/');
    if($dir === '/' || $dir === '.') $dir = '';
    return $scheme.'://'.$host.$dir;
}}

if(!function_exists('bot_ticket_miniapp_url')){
function bot_ticket_miniapp_url($ticketId=0){
    $base = bot_ticket_miniapp_base_url();
    if($base === '') return '';
    $url = rtrim($base, '/').'/miniapp/tickets/index.php';
    $ticketId = (int)$ticketId;
    if($ticketId > 0) $url .= '?ticket_id='.$ticketId;
    return $url;
}}

if(!function_exists('bot_ticket_miniapp_inline_keyboard')){
function bot_ticket_miniapp_inline_keyboard($ticketId=0, $includeLegacy=false){
    // Mini App only: no direct URL button and no legacy chat-ticket button in the user entry.
    // The $includeLegacy argument is kept only for backward compatibility with older calls.
    $url = bot_ticket_miniapp_url($ticketId);
    $rows = [];
    if($url !== ''){
        $rows[] = [[
            'text' => '🎫 باز کردن مینی‌اپ پشتیبانی',
            'web_app' => ['url' => $url]
        ]];
    }else{
        $rows[] = [[
            'text' => '⚠️ مینی‌اپ پشتیبانی تنظیم نشده',
            'callback_data' => 'ticket_miniapp_missing'
        ]];
    }
    return json_encode(['inline_keyboard'=>$rows], JSON_UNESCAPED_UNICODE);
}}

if(!function_exists('bot_ticket_miniapp_send_entry')){
function bot_ticket_miniapp_send_entry($chatId, $userId='', $replyToMessageId=null){
    $text = "🎫 <b>پشتیبانی کاربران</b>\n\n".
            "برای ثبت تیکت، مشاهده پاسخ ادمین و ادامه گفتگو، فقط از مینی‌اپ پشتیبانی استفاده کن.\n\n".
            "روی دکمه زیر بزن تا پنل تیکت داخل تلگرام باز شود.";
    if(function_exists('SM')){
        return SM($chatId, $text, 'html', $replyToMessageId, bot_ticket_miniapp_inline_keyboard(0, false));
    }
    if(function_exists('bot')){
        return bot('sendMessage', ['chat_id'=>$chatId, 'text'=>$text, 'parse_mode'=>'HTML', 'reply_markup'=>bot_ticket_miniapp_inline_keyboard(0, false)]);
    }
    return false;
}}

if(!function_exists('bot_ticket_miniapp_parse_init_data')){
function bot_ticket_miniapp_parse_init_data($initData){
    $initData = (string)$initData;
    $pairs = [];
    parse_str($initData, $pairs);
    return is_array($pairs) ? $pairs : [];
}}

if(!function_exists('bot_ticket_miniapp_validate_init_data')){
function bot_ticket_miniapp_validate_init_data($initData, $maxAgeSeconds=86400){
    if(!defined('API_KEY') || trim((string)API_KEY) === '' || (string)API_KEY === 'BOT_TOKEN_HERE'){
        return ['ok'=>false, 'error'=>'bot_token_missing'];
    }
    $pairs = bot_ticket_miniapp_parse_init_data($initData);
    if(empty($pairs['hash'])) return ['ok'=>false, 'error'=>'hash_missing'];
    $hash = (string)$pairs['hash'];
    unset($pairs['hash']);
    ksort($pairs, SORT_STRING);
    $check = [];
    foreach($pairs as $k=>$v){
        if(is_array($v)) continue;
        $check[] = $k.'='.$v;
    }
    $dataCheckString = implode("\n", $check);
    $secretKey = hash_hmac('sha256', (string)API_KEY, 'WebAppData', true);
    $calculated = hash_hmac('sha256', $dataCheckString, $secretKey);
    if(!hash_equals($calculated, $hash)) return ['ok'=>false, 'error'=>'bad_hash'];
    $authDate = (int)($pairs['auth_date'] ?? 0);
    if($maxAgeSeconds > 0 && $authDate > 0 && (time() - $authDate) > $maxAgeSeconds){
        return ['ok'=>false, 'error'=>'expired'];
    }
    $user = [];
    if(!empty($pairs['user'])){
        $u = json_decode((string)$pairs['user'], true);
        if(is_array($u)) $user = $u;
    }
    $uid = preg_replace('/[^0-9]/', '', (string)($user['id'] ?? ''));
    if($uid === '') return ['ok'=>false, 'error'=>'user_missing'];
    return ['ok'=>true, 'user_id'=>$uid, 'user'=>$user, 'raw'=>$pairs];
}}

if(!function_exists('bot_ticket_miniapp_status_label')){
function bot_ticket_miniapp_status_label($status){
    $map = [
        'open'=>'باز',
        'pending'=>'در انتظار بررسی',
        'answered_user'=>'در انتظار پاسخ ادمین',
        'answered_admin'=>'پاسخ داده‌شده',
        'answered'=>'پاسخ داده‌شده',
        'closed'=>'بسته‌شده',
    ];
    return $map[(string)$status] ?? (string)$status;
}}

if(!function_exists('bot_ticket_miniapp_log')){
function bot_ticket_miniapp_log($line, array $ctx=[]){
    if(!is_dir('cache')) @mkdir('cache', 0775, true);
    $out = date('c').' | '.$line;
    if($ctx) $out .= ' | '.json_encode($ctx, JSON_UNESCAPED_UNICODE);
    @file_put_contents('cache/ticket_miniapp.log', $out."\n", FILE_APPEND);
}}

if(!function_exists('bot_ticket_miniapp_notify_admins')){
function bot_ticket_miniapp_notify_admins(array $ticket, $messageText='', $attachmentPath='', array $extra=[]){
    if(!function_exists('bot_adv_ticket_admin_ids')) return 0;
    $ids = bot_adv_ticket_admin_ids();
    $ticketId = (int)($ticket['id'] ?? 0);
    $code = (string)($ticket['ticket_code'] ?? '');
    $uid = (string)($ticket['user_id'] ?? '');
    $kb = function_exists('bot_adv_ticket_action_keyboard') ? bot_adv_ticket_action_keyboard($ticketId, $uid) : null;
    $safeMessage = trim((string)$messageText);
    if($safeMessage === '') $safeMessage = '[پیام غیرمتنی]';
    $meta = "🎫 <b>تیکت از مینی‌اپ</b>\n".
            "🆔 کد: <code>".htmlspecialchars($code, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')."</code>\n".
            "#️⃣ شماره: <code>{$ticketId}</code>\n".
            "👤 کاربر: <code>".htmlspecialchars($uid, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')."</code>";
    if(!empty($extra['category'])) $meta .= "\n📌 موضوع: <b>".htmlspecialchars((string)$extra['category'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')."</b>";
    $meta .= "\n\n📝 پیام:\n".htmlspecialchars($safeMessage, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    $sent = 0;
    foreach($ids as $aid){
        $res = function_exists('bot') ? bot('sendMessage', ['chat_id'=>$aid, 'text'=>$meta, 'parse_mode'=>'HTML', 'reply_markup'=>$kb]) : null;
        if(is_object($res) && !empty($res->ok)) $sent++;
        if($attachmentPath !== '' && is_file($attachmentPath) && function_exists('bot')){
            if(class_exists('CURLFile', false)){
                @bot('sendDocument', ['chat_id'=>$aid, 'document'=>new CURLFile($attachmentPath), 'caption'=>'📎 پیوست تیکت '.$code]);
            }
        }
    }
    return $sent;
}}
?>
