<?php

namespace app\controllers;

use yii\web\Controller;
use yii\web\Response;
use Yii;

class SiteController extends Controller
{
    public function behaviors()
    {
        return [
            [
                'class' => 'yii\filters\ContentNegotiator',
                'only' => ['docs', 'index', 'test-db'],
                'formats' => [
                    'application/json' => Response::FORMAT_HTML,
                ],
            ],
        ];
    }
    public function actionIndex()
    {
        return "<h2 style='text-align: center;'>Welcome</h2>";
    }
    /**
     * Displays about page.
     *
     * @return string
     */
    public function actionDocs()
    {
        return $this->render('docs');
    }
    /*public function actionResource()
    {
        $swagger = \Swagger\scan(['../config', '../routes', '../models', '../modules']);
        return $swagger;
    }*/

    public function actionResource()
    {
        $paths = [
            Yii::getAlias('@api/OpenApiBootstrap.php'),
            Yii::getAlias('@api/OpenApiSchemas.php'),   // << ใส่ไฟล์ schema
            Yii::getAlias('@api/modules/v1/controllers/AuthController.php'),
            Yii::getAlias('@api/modules/v1/controllers/PingController.php'),
            Yii::getAlias('@api/modules/v1/controllers/GuestController.php'),
            Yii::getAlias('@api/modules/v1/controllers/HisRequestController.php'),
            Yii::getAlias('@api/modules/v1/controllers/LisResultController.php'),
            //Yii::getAlias('@common/models'),
        ];
        //var_dump($paths); // Debugging: check paths
        //die();

        try {
            $openapi = \OpenApi\scan($paths);  // ← ใช้ scan() ไม่ใช่ Generator::scan()

            $openapi = \OpenApi\Generator::scan($paths, [
                'exclude' => [Yii::getAlias('@app/runtime')], // ตัวอย่าง option
            ]);
            Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
            Yii::$app->response->headers->set('Content-Type', 'application/json; charset=UTF-8');

            $json = $openapi->toJson();
            return json_encode(json_decode($json, true), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        } catch (\Throwable $e) {
            Yii::$app->response->statusCode = 500;
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return [
                'error' => 'OpenAPI generation failed',
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'paths' => $paths,
            ];
        }
    }

    public function actionTestPatho()
    {
        $users = Yii::$app->patho->createCommand('SELECT * FROM user')->queryAll();
        echo '<pre>';
        var_dump($users);
        die();
    }
}
