<?php

declare(strict_types=1);

/**
 * emoji_packs.php — panel-side manager for admin custom-emoji packs (T46-ba).
 *
 * Owner directive: «کنار پیام فرستادن‌ها دکمه ایموجی … کل فایل‌های tgs داخل
 * پک دانلود و به ترتیب اضافه شوند و داخل پنل به شکل واقعی‌شان نمایش داده
 * شوند» — the panel emoji picker's data + management API.
 *
 * All actions require a logged-in admin SESSION (panel-only; API keys are
 * rejected — packs are an interactive admin feature). Session POSTs are
 * CSRF-checked inside ApiAuth::requireSession().
 *
 *   GET  ?action=list                 → packs + download progress
 *   GET  ?action=items&pack=ID        → one pack's items in PACK ORDER
 *   GET  ?action=asset&item=ID        → real file: Lottie JSON (.tgs) / image
 *   POST ?action=add                  → link=...   resolves getStickerSet,
 *                                       stores the WHOLE pack permanently
 *   POST ?action=download_chunk       → pack=ID    downloads up to 12 real
 *                                       .tgs/.webp files per call (the
 *                                       picker loops this with progress)
 *   POST ?action=delete               → pack=ID    deletes pack + files
 */

require __DIR__ . '/bootstrap.php';
ApiResponse::startTiming();

ApiAuth::requireSession();

global $config;

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$action = $_GET['action'] ?? '';
$adminId = ApiAuth::$currentAdminId ?? 0;
$bot = new TelegramBot((string)($config['telegram_bot_token'] ?? ''));

// ── GET ────────────────────────────────────────────────────────────────
if ($method === 'GET') {
    if ($action === 'list') {
        ApiResponse::success([
            'packs' => CustomEmoji::panelPacks(),
            'total_emojis' => CustomEmoji::countEmojis(),
        ]);
    }

    if ($action === 'items') {
        $packId = ApiInput::requireInt('pack');
        $packs = CustomEmoji::panelPacks();
        $found = null;
        foreach ($packs as $p) {
            if ((int)$p['id'] === $packId) {
                $found = $p;
                break;
            }
        }
        if ($found === null) {
            ApiResponse::error(404, 'pack_not_found', 'پک پیدا نشد — شاید حذف شده باشد.');
        }
        ApiResponse::success([
            'pack' => $found,
            'items' => CustomEmoji::packItems($packId), // pack order (pos)
        ]);
    }

    if ($action === 'asset') {
        $itemId = ApiInput::requireInt('item');
        $prev = CustomEmoji::preview($itemId);
        if ($prev === null) {
            ApiResponse::error(404, 'asset_not_found', 'فایل پیش‌نمایش آماده نیست.');
        }
        header('Content-Type: ' . $prev['mime']);
        header('Cache-Control: private, max-age=86400');
        header('Content-Length: ' . (string)strlen($prev['body']));
        echo $prev['body'];
        exit;
    }

    ApiResponse::error(400, 'invalid_action', 'Action نامعتبر است.');
}

// ── POST ───────────────────────────────────────────────────────────────
if ($method === 'POST') {
    if ($action === 'add') {
        $link = trim(ApiInput::string('link', ''));
        if ($link === '') {
            ApiResponse::error(400, 'link_required', 'لینک پک را وارد کنید (مثل https://t.me/addemoji/Name).');
        }
        $res = CustomEmoji::addPackFromLink($bot, $link, $adminId);
        if (!$res['ok']) {
            $msg = match ((string)($res['error'] ?? '')) {
                'bad_link' => 'لینک نامعتبر است. لینک را مثل https://t.me/addemoji/Name بفرستید.',
                'not_found' => 'پک پیدا نشد یا خصوصی است. لینک را چک کنید.',
                'not_emoji_pack' => 'این پک استیکر است، نه پک ایموجی کاستوم (addemoji).',
                default => 'ذخیره‌سازی پک ناموفق بود. دوباره تلاش کنید.',
            };
            ApiResponse::error(400, (string)($res['error'] ?? 'db'), $msg);
        }
        AdminDB::logAction($adminId, 'emoji_pack_add', 'emoji_pack', (string)($res['pack_id'] ?? 0));
        ApiResponse::success([
            'ok' => true,
            'pack_id' => (int)($res['pack_id'] ?? 0),
            'title' => (string)($res['title'] ?? ''),
            'count' => (int)($res['count'] ?? 0),
            'updated' => (bool)($res['updated'] ?? false),
        ]);
    }

    if ($action === 'download_chunk') {
        $packId = ApiInput::requireInt('pack');
        $r = CustomEmoji::downloadPendingChunk($bot, $packId);
        ApiResponse::success(['ok' => true] + $r);
    }

    if ($action === 'delete') {
        $packId = ApiInput::requireInt('pack');
        $ok = CustomEmoji::deletePack($packId);
        if (!$ok) {
            ApiResponse::error(404, 'pack_not_found', 'پک پیدا نشد — شاید قبلا حذف شده باشد.');
        }
        AdminDB::logAction($adminId, 'emoji_pack_delete', 'emoji_pack', (string)$packId);
        ApiResponse::success(['ok' => true, 'deleted' => $packId]);
    }

    ApiResponse::error(400, 'invalid_action', 'Action نامعتبر است.');
}

ApiResponse::error(405, 'method_not_allowed', 'Method not allowed.');
