<?php

namespace App\Modules\System\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Inertia\Inertia;
use Illuminate\Support\Str;

class ManualController extends Controller
{
    /**
     * Display the user manual page.
     */
    public function index(Request $request, $slug = null)
    {
        $tocPath = resource_path('markdown/manual/toc.json');
        
        if (!File::exists($tocPath)) {
            // Create a default TOC if it doesn't exist
            $this->createDefaultManualStructure();
        }

        $toc = json_decode(File::get($tocPath), true);
        
        // If no slug provided, pick the first one from TOC
        if (!$slug) {
            foreach ($toc as $section) {
                if (!empty($section['pages'])) {
                    $slug = $section['pages'][0]['slug'];
                    break;
                }
            }
        }

        $content = '';
        $filePath = resource_path("markdown/manual/{$slug}.md");
        
        if (File::exists($filePath)) {
            $content = File::get($filePath);
        } else {
            $content = "# 檔案未找到\n\n抱歉，您所要求的「{$slug}」頁面目前不存在。";
        }

        return Inertia::render('System/Manual/Index', [
            'toc' => $toc,
            'currentSlug' => $slug,
            'content' => $content,
        ]);
    }

    /**
     * Helper to initialize the manual structure if empty
     */
    protected function createDefaultManualStructure()
    {
        $dir = resource_path('markdown/manual');
        if (!File::isDirectory($dir)) {
            File::makeDirectory($dir, 0755, true);
        }

        $toc = [
            [
                'title' => '新手上路',
                'pages' => [
                    ['title' => '登入與帳號設定', 'slug' => 'getting-started']
                ]
            ],
            [
                'title' => '核心流程',
                'pages' => [
                    ['title' => '採購流程說明', 'slug' => 'purchasing-workflow'],
                    ['title' => '庫存管理規範', 'slug' => 'inventory-management']
                ]
            ],
            [
                'title' => '其他區域',
                'pages' => [
                    ['title' => '常見問題 (FAQ)', 'slug' => 'faq']
                ]
            ]
        ];

        File::put($dir . '/toc.json', json_encode($toc, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

        // Create dummy files
        $files = [
            'getting-started' => "# 登入與帳號設定\n\n歡迎使用 Star ERP！在本章節中，我們將介紹...",
            'purchasing-workflow' => "# 採購流程說明\n\n完整的採購循環包含以下步驟：\n\n1. 建立請購單\n2. 核准並轉成採購單\n3. 供應商發貨",
            'inventory-management' => "# 庫存管理規範\n\n本系統支援多倉庫管理與即時庫存追蹤...",
            'faq' => "# 常見問題 (FAQ)\n\n### 1. 忘記密碼怎麼辦？\n請聯繫系統管理員進行密碼重設。"
        ];

        foreach ($files as $name => $body) {
            File::put($dir . "/{$name}.md", $body);
        }
    }
}
