<?php
header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');
if($_SERVER['REQUEST_METHOD'] === 'OPTIONS'){ http_response_code(204); exit; }

$root = realpath(__DIR__ . '/../..');
if(!$root){ http_response_code(500); echo json_encode(['ok'=>false,'error'=>'root_not_found'], JSON_UNESCAPED_UNICODE); exit; }
chdir($root);

if(!is_file($root.'/config.php')){ http_response_code(500); echo json_encode(['ok'=>false,'error'=>'config_missing'], JSON_UNESCAPED_UNICODE); exit; }
require_once $root.'/config.php';
if(is_file($root.'/config_db.php')) require_once $root.'/config_db.php';
if(is_file($root.'/lib/db_storage.php')) require_once $root.'/lib/db_storage.php';
foreach([
    '/app/Bootstrap.php',
    '/app/Support/TextFormatting.php',
    '/app/Legacy/CoreApi.php',
    '/app/Services/AdminToolsService.php',
    '/app/Services/CannedReplyService.php',
    '/app/Services/AdvancedToolsService.php',
    '/app/Services/TicketMiniAppService.php',
] as $file){ $p=$root.$file; if(is_file($p)) require_once $p; }

function ticket_api_out($data, $code=200){ http_response_code($code); echo json_encode($data, JSON_UNESCAPED_UNICODE); exit; }
function ticket_api_input(){
    $ct = strtolower((string)($_SERVER['CONTENT_TYPE'] ?? ''));
    if(strpos($ct, 'application/json') !== false){
        $raw = file_get_contents('php://input');
        $j = json_decode((string)$raw, true);
        return is_array($j) ? $j : [];
    }
    return $_POST;
}
function ticket_api_pdo(){
    if(function_exists('bot_adv_install_schema')) bot_adv_install_schema();
    if(!function_exists('bot_sql_pdo')) return null;
    return bot_sql_pdo();
}
function ticket_api_clean_text($s, $max=4000){
    $s = trim((string)$s);
    if(function_exists('mb_substr')) return mb_substr($s, 0, $max, 'UTF-8');
    return substr($s, 0, $max);
}
function ticket_api_upload($ticketId=0){
    if(empty($_FILES['file']) || !is_array($_FILES['file'])) return ['ok'=>true, 'path'=>'', 'name'=>'', 'size'=>0];
    $f = $_FILES['file'];
    if((int)($f['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) return ['ok'=>true, 'path'=>'', 'name'=>'', 'size'=>0];
    if((int)$f['error'] !== UPLOAD_ERR_OK) return ['ok'=>false, 'error'=>'upload_error_'.$f['error']];
    $size = (int)($f['size'] ?? 0);
    $max = 12 * 1024 * 1024;
    if($size <= 0 || $size > $max) return ['ok'=>false, 'error'=>'file_too_large'];
    $orig = (string)($f['name'] ?? 'file');
    $ext = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
    $allowed = ['jpg','jpeg','png','gif','webp','pdf','txt','zip','rar','doc','docx','xls','xlsx','mp3','mp4'];
    if($ext === '' || !in_array($ext, $allowed, true)) return ['ok'=>false, 'error'=>'bad_file_type'];
    $dir = 'ticket_uploads/'.date('Y/m');
    if(!is_dir($dir)) @mkdir($dir, 0775, true);
    $safeName = preg_replace('/[^A-Za-z0-9_.\-]+/', '_', $orig);
    $name = 't'.(int)$ticketId.'_'.date('His').'_'.bin2hex(random_bytes(5)).'.'.$ext;
    $dest = $dir.'/'.$name;
    if(!@move_uploaded_file((string)$f['tmp_name'], $dest)) return ['ok'=>false, 'error'=>'move_failed'];
    return ['ok'=>true, 'path'=>$dest, 'name'=>$safeName, 'size'=>$size, 'mime'=>(string)($f['type'] ?? '')];
}

$input = ticket_api_input();
$action = (string)($_GET['action'] ?? ($input['action'] ?? ''));
$initData = (string)($input['initData'] ?? ($_GET['initData'] ?? ''));
if(!function_exists('bot_ticket_miniapp_validate_init_data')) ticket_api_out(['ok'=>false,'error'=>'miniapp_service_missing'], 500);
$auth = bot_ticket_miniapp_validate_init_data($initData, 86400);
if(empty($auth['ok'])) ticket_api_out(['ok'=>false,'error'=>'unauthorized','reason'=>$auth['error'] ?? 'auth_failed'], 401);
$userId = (string)$auth['user_id'];
$userInfo = is_array($auth['user'] ?? null) ? $auth['user'] : [];
$pdo = ticket_api_pdo();
if(!$pdo) ticket_api_out(['ok'=>false,'error'=>'sql_disabled'], 503);

try{
    if($action === 'list'){
        $st = $pdo->prepare('SELECT id,ticket_code,status,subject,last_message,created_at,updated_at FROM bot_support_tickets WHERE user_id=? ORDER BY id DESC LIMIT 50');
        $st->execute([$userId]);
        $tickets = [];
        foreach($st as $r){
            $tickets[] = [
                'id'=>(int)$r['id'],
                'code'=>(string)$r['ticket_code'],
                'status'=>(string)$r['status'],
                'status_label'=>function_exists('bot_ticket_miniapp_status_label') ? bot_ticket_miniapp_status_label($r['status']) : (string)$r['status'],
                'subject'=>(string)$r['subject'],
                'last_message'=>(string)$r['last_message'],
                'created_at'=>(string)$r['created_at'],
                'updated_at'=>(string)$r['updated_at'],
            ];
        }
        ticket_api_out(['ok'=>true, 'user_id'=>$userId, 'tickets'=>$tickets]);
    }

    if($action === 'detail'){
        $id = (int)($input['ticket_id'] ?? ($_GET['ticket_id'] ?? 0));
        if($id <= 0) ticket_api_out(['ok'=>false,'error'=>'bad_ticket_id'], 400);
        $st = $pdo->prepare('SELECT * FROM bot_support_tickets WHERE id=? AND user_id=? LIMIT 1');
        $st->execute([$id, $userId]);
        $t = $st->fetch(PDO::FETCH_ASSOC);
        if(!$t) ticket_api_out(['ok'=>false,'error'=>'ticket_not_found'], 404);
        $pdo->prepare('UPDATE bot_support_tickets SET last_user_seen_at=CURRENT_TIMESTAMP WHERE id=?')->execute([$id]);
        $ms = $pdo->prepare('SELECT id,sender_id,sender_role,message_text,data_json,created_at FROM bot_support_messages WHERE ticket_id=? ORDER BY id ASC');
        $ms->execute([$id]);
        $messages = [];
        foreach($ms as $m){
            $data = [];
            $raw = (string)($m['data_json'] ?? '');
            if($raw !== ''){ $tmp=json_decode($raw,true); if(is_array($tmp)) $data=$tmp; }
            $messages[] = [
                'id'=>(int)$m['id'],
                'sender_role'=>(string)$m['sender_role'],
                'text'=>(string)$m['message_text'],
                'data'=>$data,
                'created_at'=>(string)$m['created_at'],
            ];
        }
        ticket_api_out(['ok'=>true, 'ticket'=>[
            'id'=>(int)$t['id'], 'code'=>(string)$t['ticket_code'], 'status'=>(string)$t['status'],
            'status_label'=>function_exists('bot_ticket_miniapp_status_label') ? bot_ticket_miniapp_status_label($t['status']) : (string)$t['status'],
            'subject'=>(string)$t['subject'], 'last_message'=>(string)$t['last_message'],
            'created_at'=>(string)$t['created_at'], 'updated_at'=>(string)$t['updated_at'],
        ], 'messages'=>$messages]);
    }

    if($action === 'create'){
        $category = ticket_api_clean_text($input['category'] ?? 'سایر موارد', 80);
        $message = ticket_api_clean_text($input['message'] ?? '', 4000);
        $upload = ticket_api_upload(0);
        if(empty($upload['ok'])) ticket_api_out(['ok'=>false,'error'=>$upload['error']], 400);
        if($message === '' && empty($upload['path'])) ticket_api_out(['ok'=>false,'error'=>'empty_message'], 400);
        $extra = [
            'source'=>'ticket_miniapp',
            'chat_id'=>$userId,
            'category'=>$category,
            'username'=>$userInfo['username'] ?? '',
            'first_name'=>$userInfo['first_name'] ?? '',
            'message_type'=>empty($upload['path']) ? 'text' : 'document',
        ];
        if(!empty($upload['path'])) $extra['attachment'] = $upload;
        $body = "موضوع: {$category}\n".$message;
        if(!empty($upload['name'])) $body .= "\n\n📎 فایل پیوست: ".$upload['name'];
        $res = function_exists('bot_adv_create_ticket') ? bot_adv_create_ticket($userId, $body, $extra) : ['ok'=>false,'error'=>'ticket_service_missing'];
        if(empty($res['ok'])){
            if(($res['error'] ?? '') === 'open_ticket_exists') ticket_api_out(['ok'=>false,'error'=>'open_ticket_exists','ticket'=>$res['ticket']], 409);
            ticket_api_out(['ok'=>false,'error'=>$res['error'] ?? 'create_failed'], 500);
        }
        $ticket = $res['ticket'];
        $ticket['id'] = (int)($res['id'] ?? ($ticket['id'] ?? 0));
        if($category !== ''){
            $pdo->prepare('UPDATE bot_support_tickets SET subject=? WHERE id=?')->execute([$category, (int)$ticket['id']]);
            $ticket['subject']=$category;
        }
        if(function_exists('bot_ticket_miniapp_notify_admins')) bot_ticket_miniapp_notify_admins($ticket, $message, $upload['path'] ?? '', $extra);
        ticket_api_out(['ok'=>true, 'ticket'=>['id'=>(int)$ticket['id'], 'code'=>(string)($ticket['ticket_code'] ?? ''), 'subject'=>$category]]);
    }

    if($action === 'reply'){
        $id = (int)($input['ticket_id'] ?? 0);
        if($id <= 0) ticket_api_out(['ok'=>false,'error'=>'bad_ticket_id'], 400);
        $st=$pdo->prepare('SELECT * FROM bot_support_tickets WHERE id=? AND user_id=? LIMIT 1');
        $st->execute([$id, $userId]);
        $ticket=$st->fetch(PDO::FETCH_ASSOC);
        if(!$ticket) ticket_api_out(['ok'=>false,'error'=>'ticket_not_found'], 404);
        if((string)$ticket['status'] === 'closed') ticket_api_out(['ok'=>false,'error'=>'ticket_closed'], 409);
        $message = ticket_api_clean_text($input['message'] ?? '', 4000);
        $upload = ticket_api_upload($id);
        if(empty($upload['ok'])) ticket_api_out(['ok'=>false,'error'=>$upload['error']], 400);
        if($message === '' && empty($upload['path'])) ticket_api_out(['ok'=>false,'error'=>'empty_message'], 400);
        $extra = ['source'=>'ticket_miniapp_reply','chat_id'=>$userId,'message_type'=>empty($upload['path'])?'text':'document'];
        if(!empty($upload['path'])) $extra['attachment'] = $upload;
        $body = $message;
        if(!empty($upload['name'])) $body .= ($body !== '' ? "\n\n" : '')."📎 فایل پیوست: ".$upload['name'];
        $r = function_exists('bot_adv_append_ticket_message') ? bot_adv_append_ticket_message($id, $userId, 'user', $body, $extra) : ['ok'=>false,'error'=>'ticket_service_missing'];
        if(empty($r['ok'])) ticket_api_out(['ok'=>false,'error'=>$r['error'] ?? 'reply_failed'], 500);
        if(function_exists('bot_ticket_miniapp_notify_admins')) bot_ticket_miniapp_notify_admins($ticket, $message, $upload['path'] ?? '', $extra);
        ticket_api_out(['ok'=>true]);
    }

    ticket_api_out(['ok'=>false,'error'=>'unknown_action'], 404);
}catch(Throwable $e){
    if(function_exists('bot_ticket_miniapp_log')) bot_ticket_miniapp_log('api_error', ['action'=>$action,'user'=>$userId,'error'=>$e->getMessage()]);
    ticket_api_out(['ok'=>false,'error'=>'server_error','message'=>$e->getMessage()], 500);
}
