<?php
/**
 * GEM ACC v27.50 - Professional Admin Support/Chat Center API
 */
require_once 'config.php';
header('Content-Type: application/json; charset=utf-8');

$input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
$adminId = miniapp_require_admin();

function admin_chats_ok(array $data = []): void {
    echo json_encode(['ok' => true, 'data' => $data], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}
function admin_chats_err(string $error, int $code = 400): void {
    http_response_code($code);
    echo json_encode(['ok' => false, 'error' => $error], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}
function admin_chats_user(PDO $pdo, int $userId): array {
    $st = $pdo->prepare("SELECT id, username, first_name, last_name, is_blocked, balance, created_at FROM users WHERE id=? LIMIT 1");
    $st->execute([$userId]);
    $u = $st->fetch(PDO::FETCH_ASSOC) ?: ['id' => $userId];
    $u['id'] = (int)($u['id'] ?? $userId);
    $u['is_blocked'] = (int)($u['is_blocked'] ?? 0);
    $u['balance'] = (int)($u['balance'] ?? 0);
    $name = trim((string)($u['first_name'] ?? '') . ' ' . (string)($u['last_name'] ?? ''));
    $u['label'] = $name !== '' ? $name : (!empty($u['username']) ? '@' . ltrim((string)$u['username'], '@') : 'کاربر ' . $userId);
    return $u;
}
function admin_chats_current_ticket(PDO $pdo, int $userId): ?array {
    $st = $pdo->prepare("SELECT id, user_id, subject, status, priority, unread_admin_count, unread_user_count, last_message_at, closed_at, created_at, updated_at FROM support_tickets WHERE user_id=? ORDER BY (status='CLOSED') ASC, updated_at DESC, id DESC LIMIT 1");
    $st->execute([$userId]);
    $t = $st->fetch(PDO::FETCH_ASSOC);
    if (!$t) return null;
    $t['id'] = (int)$t['id'];
    $t['user_id'] = (int)$t['user_id'];
    $t['unread_admin_count'] = (int)($t['unread_admin_count'] ?? 0);
    $t['unread_user_count'] = (int)($t['unread_user_count'] ?? 0);
    $t['status_label'] = function_exists('gemaccSupportStatusLabel') ? gemaccSupportStatusLabel((string)$t['status']) : (string)$t['status'];
    return $t;
}

try {
    if (function_exists('gemaccAdminChatEnsureSchema')) gemaccAdminChatEnsureSchema($pdo);
    $action = (string)($input['action'] ?? $_GET['action'] ?? 'list');

    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        if ($action === 'list') {
            $type = (string)($_GET['type'] ?? 'all');
            $q = trim((string)($_GET['q'] ?? ''));
            $limit = max(1, min(100, (int)($_GET['limit'] ?? 50)));
            $items = function_exists('gemaccAdminChatRecent') ? gemaccAdminChatRecent($type, $limit, $q) : [];
            foreach ($items as &$it) {
                $it['user_id'] = (int)($it['user_id'] ?? 0);
                $it['ticket_id'] = isset($it['ticket_id']) ? (int)$it['ticket_id'] : null;
                $it['message_count'] = (int)($it['message_count'] ?? 0);
                $it['incoming_count'] = (int)($it['incoming_count'] ?? 0);
                $it['unread_count'] = (int)($it['unread_count'] ?? $it['incoming_count'] ?? 0);
                $it['is_blocked'] = (int)($it['is_blocked'] ?? 0);
                $it['last_message'] = mb_substr((string)($it['last_message'] ?? ''), 0, 600, 'UTF-8');
            }
            $stats = ['total'=>count($items), 'unread'=>0, 'open'=>0];
            foreach ($items as $x) { $stats['unread'] += (int)($x['unread_count'] ?? 0); if (strtoupper((string)($x['status'] ?? 'OPEN')) !== 'CLOSED') $stats['open']++; }
            admin_chats_ok(['chats' => $items, 'type' => $type, 'q' => $q, 'stats'=>$stats]);
        }

        if ($action === 'messages') {
            $type = (string)($_GET['type'] ?? 'all');
            $userId = (int)($_GET['user_id'] ?? 0);
            if ($userId <= 0) admin_chats_err('شناسه کاربر نامعتبر است');
            $messages = function_exists('gemaccAdminChatMessages') ? gemaccAdminChatMessages($type, $userId, 160) : [];
            foreach ($messages as &$m) {
                $m['id'] = (int)($m['id'] ?? 0);
                $m['user_id'] = (int)($m['user_id'] ?? $userId);
                $m['admin_id'] = isset($m['admin_id']) ? (int)$m['admin_id'] : null;
                $m['ticket_id'] = isset($m['ticket_id']) ? (int)$m['ticket_id'] : null;
                $m['message_text'] = (string)($m['message_text'] ?? '');
                $m['attachment_type'] = (string)($m['attachment_type'] ?? '');
                $m['attachment_name'] = (string)($m['attachment_name'] ?? '');
                $m['attachment_mime'] = (string)($m['attachment_mime'] ?? '');
                if (($m['source'] ?? '') === 'support' && (!empty($m['telegram_file_id']) || !empty($m['attachment_path']))) {
                    $m['attachment_url'] = 'api/support_attachment.php?message_id='.(int)$m['id'];
                } else {
                    $m['attachment_url'] = '';
                }
            }
            admin_chats_ok(['user' => admin_chats_user($pdo, $userId), 'ticket' => admin_chats_current_ticket($pdo, $userId), 'messages' => $messages, 'type' => $type]);
        }

        admin_chats_err('Action نامعتبر است');
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if ($action === 'send') {
            $userId = (int)($input['user_id'] ?? $input['target_user_id'] ?? 0);
            $type = (string)($input['type'] ?? 'private');
            $message = trim((string)($input['message'] ?? ''));
            if ($userId <= 0) admin_chats_err('شناسه کاربر نامعتبر است');
            if ($message === '') admin_chats_err('متن پیام الزامی است');
            $sendType = $type === 'support' ? 'support' : 'private';
            if ($sendType === 'support' && function_exists('gemaccSupportAdminSendReply')) {
                $res = gemaccSupportAdminSendReply($pdo, $adminId, $userId, $message);
            } else {
                $res = function_exists('gemaccAdminChatSendReply') ? gemaccAdminChatSendReply($sendType, $adminId, $userId, $message) : ['ok'=>false, 'error'=>'Chat service unavailable'];
            }
            if (empty($res['ok'])) admin_chats_err((string)($res['error'] ?? 'ارسال پیام ناموفق بود'));
            if (function_exists('gemaccAdminActionNotify')) {
                gemaccAdminActionNotify($sendType === 'support' ? 'پاسخ پشتیبانی از مرکز چت ارسال شد' : 'پیام خصوصی از مرکز چت ارسال شد', [
                    'کاربر' => $userId,
                    'نوع چت' => $sendType === 'support' ? 'پشتیبانی' : 'خصوصی',
                    'متن' => mb_substr($message, 0, 500, 'UTF-8'),
                ], $adminId);
            }
            admin_chats_ok(['message' => 'پیام ارسال شد', 'type' => $sendType, 'ticket_id' => $res['ticket_id'] ?? null]);
        }

        if ($action === 'close') {
            $ticketId = (int)($input['ticket_id'] ?? 0);
            $userId = (int)($input['user_id'] ?? 0);
            if (!function_exists('gemaccSupportCloseTicket')) admin_chats_err('Ticket service unavailable', 500);
            $res = gemaccSupportCloseTicket($pdo, $ticketId, $adminId, $userId);
            if (empty($res['ok'])) admin_chats_err((string)($res['error'] ?? 'بستن تیکت ناموفق بود'));
            if (function_exists('gemaccAdminActionNotify')) gemaccAdminActionNotify('تیکت پشتیبانی بسته شد', ['تیکت'=>$res['ticket_id'] ?? $ticketId, 'کاربر'=>$res['user_id'] ?? $userId], $adminId);
            admin_chats_ok(['message'=>'تیکت بسته شد', 'ticket_id'=>$res['ticket_id'] ?? $ticketId]);
        }

        if ($action === 'mark_read') {
            $userId = (int)($input['user_id'] ?? 0);
            if ($userId <= 0) admin_chats_err('شناسه کاربر نامعتبر است');
            try {
                $pdo->prepare("UPDATE support_messages sm JOIN support_tickets t ON t.id=sm.ticket_id SET sm.is_read=1 WHERE t.user_id=? AND (sm.sender_role='USER' OR COALESCE(sm.is_admin_reply,0)=0)")->execute([$userId]);
                $pdo->prepare("UPDATE support_tickets SET unread_admin_count=0 WHERE user_id=?")->execute([$userId]);
            } catch (Throwable $e) { error_log('[admin_chats_mark_read] '.$e->getMessage()); }
            admin_chats_ok(['message' => 'خوانده شد']);
        }



        if ($action === 'mark_all_read') {
            if (!function_exists('gemaccSupportMarkAllTicketsRead')) admin_chats_err('Ticket service unavailable', 500);
            $res = gemaccSupportMarkAllTicketsRead($pdo, $adminId);
            if (empty($res['ok'])) admin_chats_err((string)($res['error'] ?? 'عملیات ناموفق بود'));
            if (function_exists('gemaccAdminActionNotify')) gemaccAdminActionNotify('همه تیکت‌ها خوانده‌شده شدند', ['پیام‌ها'=>$res['messages'] ?? 0, 'تیکت‌ها'=>$res['tickets'] ?? 0], $adminId);
            admin_chats_ok(['message'=>'همه تیکت‌ها خوانده‌شده شدند', 'messages'=>$res['messages'] ?? 0, 'tickets'=>$res['tickets'] ?? 0]);
        }

        if ($action === 'delete_all_tickets') {
            if (!function_exists('gemaccSupportDeleteAllTickets')) admin_chats_err('Ticket service unavailable', 500);
            $res = gemaccSupportDeleteAllTickets($pdo, $adminId);
            if (empty($res['ok'])) admin_chats_err((string)($res['error'] ?? 'عملیات ناموفق بود'));
            if (function_exists('gemaccAdminActionNotify')) gemaccAdminActionNotify('همه تیکت‌های پشتیبانی پاک شدند', ['پیام‌ها'=>$res['messages'] ?? 0, 'تیکت‌ها'=>$res['tickets'] ?? 0], $adminId);
            admin_chats_ok(['message'=>'همه تیکت‌ها پاک شدند', 'messages'=>$res['messages'] ?? 0, 'tickets'=>$res['tickets'] ?? 0]);
        }

        admin_chats_err('Action نامعتبر است');
    }

    admin_chats_err('Method not allowed', 405);
} catch (Throwable $e) {
    error_log('[admin_chats] '.$e->getMessage());
    admin_chats_err($e->getMessage(), 500);
}
