<?php
require_once __DIR__ . '/../legacy/web_adapters.php';

class LegacyBotService
{
    private array $config;
    private array $legacyConfig;

    public function __construct()
    {
        $this->config = app_config();
        $this->legacyConfig = legacyLoadBotConfig((string)$this->config['legacy_config_file']);
    }

    public function getAppConfig(): array
    {
        return $this->config;
    }

    public function getLegacyConfig(): array
    {
        return $this->legacyConfig;
    }

    public function getDashboardStats(): array
    {
        $exports = $this->listFiles($this->config['exports_path']);
        $uploads = $this->listFiles($this->config['uploads_path']);
        $panelLog = $this->config['logs_path'] . '/panel.log';
        $legacyLog = $this->config['runtime_path'] . '/polling_log.txt';

        return [
            'exports_count' => count($exports),
            'uploads_count' => count($uploads),
            'runtime_count' => count($this->listFiles($this->config['runtime_path'])),
            'last_legacy_log' => is_file($legacyLog) ? date('Y-m-d H:i:s', filemtime($legacyLog)) : '-',
            'last_panel_log' => is_file($panelLog) ? date('Y-m-d H:i:s', filemtime($panelLog)) : '-',
            'smart_map_exists' => is_file($this->config['runtime_path'] . '/smart_price_map.json'),
            'smart_review_exists' => is_file($this->config['runtime_path'] . '/latest_smart_review_rows.json'),
        ];
    }

    public function getActionCards(): array
    {
        return [
            ['title' => 'کالاهای مپ نشده', 'desc' => 'ساخت فایل کالاهای مپ نشده', 'page' => 'unmapped'],
            ['title' => 'تنظیم مپ قیمت هوشمند', 'desc' => 'دانلود قالب و آپلود فایل مپ', 'page' => 'smart-map'],
            ['title' => 'بررسی قیمت هوشمند', 'desc' => 'ساخت فایل بررسی و اعمال نهایی', 'page' => 'smart-review'],
            ['title' => 'تولید لیست متنی', 'desc' => 'ساخت متن خروجی از داده‌های نهایی', 'page' => 'text-list'],
            ['title' => 'استخراج همه فایل‌ها', 'desc' => 'اجرای هم‌زمان همه استخراج‌ها', 'page' => 'export-all'],
            ['title' => 'ثبت فاکتور', 'desc' => 'ثبت و گزارش فاکتورهای دستی، تلاش مجدد و OTP', 'page' => 'rayan-requests'],
            ['title' => 'تنظیمات فرم', 'desc' => 'تعریف طرح‌های فروش و کالاهای قابل انتخاب در ثبت فاکتور جدید', 'page' => 'rayan-form-settings'],
            ['title' => 'استعلام بازنشسته تامین اجتماعی', 'desc' => 'استعلام اعتبار بازنشسته تامین اجتماعی و گزارش ۲۴ ساعت اخیر', 'page' => 'rayan-inquiry'],
            ['title' => 'لاگ‌ها', 'desc' => 'مشاهده لاگ پنل و لاگ هسته قدیمی', 'page' => 'logs'],
        ];
    }

    public function runAllExports(): array
    {
        $result = webRunAllExports($this->legacyConfig);
        $this->markJob('export_all', json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        return $result;
    }

    public function runUnmappedExport(): array
    {
        $result = webRunUnmappedProductsExport($this->legacyConfig);
        $this->markJob('unmapped_products', $result['file'] ?? '');
        return $result;
    }

    public function generateSmartMapTemplate(): array
    {
        $result = webGenerateSmartMapTemplate($this->legacyConfig);
        $this->markJob('smart_map_template', $result['file'] ?? '');
        return $result;
    }

    public function uploadSmartMap(string $inputName = 'smart_map_file'): array
    {
        $saved = $this->saveUpload($inputName, 'smart_map');
        $result = webSaveUploadedSmartMap($this->legacyConfig, $saved['path']);
        $this->markJob('smart_map_upload', ($saved['name'] ?? '') . ' | rows=' . ($result['rows_count'] ?? 0));
        return array_merge($result, ['upload' => $saved]);
    }

    public function generateSmartReview(string $actorKey = 'admin'): array
    {
        $result = webGenerateSmartReview($this->legacyConfig, $actorKey);
        $this->markJob('smart_review_generate', ($result['file'] ?? '') . ' | rows=' . ($result['rows_count'] ?? 0));
        return $result;
    }

    public function applyUploadedSmartReview(string $inputName = 'smart_review_file', string $actorKey = 'admin'): array
    {
        $saved = $this->saveUpload($inputName, 'smart_review');
        $result = webApplyUploadedSmartReview($this->legacyConfig, $saved['path'], $actorKey);
        $this->markJob('smart_review_upload_apply', ($saved['name'] ?? '') . ' | rows=' . ($result['rows_count'] ?? 0));
        return array_merge($result, ['upload' => $saved]);
    }

    public function applySavedSmartReview(string $actorKey = 'admin'): array
    {
        $result = webApplySavedSmartReviewSnapshot($this->legacyConfig, $actorKey);
        $this->markJob('smart_review_apply_saved', 'rows=' . ($result['rows_count'] ?? 0));
        return $result;
    }

    public function buildTextList(): array
    {
        $result = webBuildTextList($this->legacyConfig);
        file_put_contents($this->config['runtime_path'] . '/text_list_last.txt', $result['text'] ?? '');
        $this->markJob('text_list_build', 'len=' . mb_strlen((string)($result['text'] ?? '')));
        return $result;
    }

    public function getTextListFromFile(): string
    {
        $file = $this->config['runtime_path'] . '/text_list_last.txt';
        if (is_file($file)) {
            return (string)file_get_contents($file);
        }

        $result = $this->buildTextList();
        return (string)($result['text'] ?? '');
    }

    public function getLatestExportByPrefix(string $prefix): ?array
    {
        $files = $this->listFiles($this->config['exports_path']);
        $matched = array_values(array_filter($files, static function (array $file) use ($prefix) {
            return str_starts_with($file['name'], $prefix);
        }));
        usort($matched, static fn($a, $b) => $b['mtime'] <=> $a['mtime']);
        return $matched[0] ?? null;
    }

    public function getLatestRuntimeFile(string $name): ?array
    {
        $path = $this->config['runtime_path'] . '/' . $name;
        return is_file($path) ? $this->fileMeta($path) : null;
    }

    public function listRecentExports(): array
    {
        $files = $this->listFiles($this->config['exports_path']);
        usort($files, static fn($a, $b) => $b['mtime'] <=> $a['mtime']);
        return array_slice($files, 0, 50);
    }

    public function listUploadedFiles(): array
    {
        $files = $this->listFiles($this->config['uploads_path']);
        usort($files, static fn($a, $b) => $b['mtime'] <=> $a['mtime']);
        return array_slice($files, 0, 50);
    }

    public function getPanelLogs(): string
    {
        $file = $this->config['logs_path'] . '/panel.log';
        return is_file($file) ? (string)file_get_contents($file) : '';
    }

    public function getLegacyPollingLogs(): string
    {
        $file = $this->config['runtime_path'] . '/polling_log.txt';
        return is_file($file) ? (string)file_get_contents($file) : '';
    }

    public function downloadFileMeta(string $area, string $name): ?array
    {
        $allowed = [
            'export' => $this->config['exports_path'],
            'upload' => $this->config['uploads_path'],
            'runtime' => $this->config['runtime_path'],
        ];

        if (!isset($allowed[$area])) {
            return null;
        }

        $base = realpath($allowed[$area]);
        if ($base === false) {
            return null;
        }

        $target = realpath($base . '/' . $name);
        if ($target === false || !is_file($target) || !str_starts_with($target, $base . DIRECTORY_SEPARATOR)) {
            return null;
        }

        return $this->fileMeta($target);
    }

    public function markJob(string $jobName, string $notes = ''): void
    {
        $file = $this->config['runtime_path'] . '/jobs.log';
        file_put_contents(
            $file,
            json_encode([
                'time' => date('Y-m-d H:i:s'),
                'job' => $jobName,
                'notes' => $notes,
            ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL,
            FILE_APPEND
        );
        log_app("JOB {$jobName} {$notes}");
    }

    private function saveUpload(string $inputName, string $targetPrefix): array
    {
        if (empty($_FILES[$inputName]['tmp_name']) || !is_uploaded_file($_FILES[$inputName]['tmp_name'])) {
            throw new RuntimeException('فایلی انتخاب نشده بود.');
        }

        $original = $_FILES[$inputName]['name'] ?? 'upload.bin';
        $safeName = preg_replace('/[^a-zA-Z0-9._-]+/u', '_', $original);
        $target = $this->config['uploads_path'] . '/' . time() . '_' . $targetPrefix . '_' . $safeName;

        if (!move_uploaded_file($_FILES[$inputName]['tmp_name'], $target)) {
            throw new RuntimeException('ذخیره فایل آپلودی ممکن نشد.');
        }

        return $this->fileMeta($target);
    }

    private function listFiles(string $dir): array
    {
        if (!is_dir($dir)) {
            return [];
        }

        $items = glob($dir . '/*') ?: [];
        $files = [];
        foreach ($items as $item) {
            if (is_file($item)) {
                $files[] = $this->fileMeta($item);
            }
        }
        return $files;
    }

    private function fileMeta(string $path): array
    {
        return [
            'path' => $path,
            'name' => basename($path),
            'size' => filesize($path) ?: 0,
            'mtime' => filemtime($path) ?: 0,
            'modified_at' => date('Y-m-d H:i:s', filemtime($path) ?: time()),
        ];
    }
}
