<?php

namespace api\components;

use Yii;
use yii\rest\Controller as RestController;
use yii\web\Response;
use yii\filters\ContentNegotiator;
use yii\filters\Cors;
use yii\filters\auth\HttpBearerAuth;

class Controller extends RestController
{
    use TraitController;

    public function behaviors()
    {
        $b = parent::behaviors();

        // 1) บังคับคืน JSON UTF-8 เสมอ
        $b['contentNegotiator'] = [
            'class' => ContentNegotiator::class,
            'formats' => [
                'application/json' => Response::FORMAT_JSON,
            ],
        ];

        // 2) CORS ต้องมาก่อน authenticator
        $b['corsFilter'] = [
            'class' => Cors::class,
            'cors'  => [
                'Origin'                           => ['*'], // แนะนำระบุโดเมนของคุณในโปรดักชัน
                'Access-Control-Request-Method'    => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
                'Access-Control-Request-Headers'   => ['Authorization', 'Content-Type', 'Accept', 'X-Requested-With'],
                'Access-Control-Allow-Credentials' => false,
                'Access-Control-Max-Age'           => 86400,
            ],
        ];

        // 3) Bearer token (ยกเว้น endpoint สาธารณะ + OPTIONS)
        $b['authenticator'] = [
            'class'  => HttpBearerAuth::class,
            'except' => [
                'options',           // CORS preflight
                'ping/index',
                'guest/index',
                'guest/login',
                'auth/check',
                'site/resource',
            ],
        ];

        // 4) Charset ให้ชัด (กันปัญหา UTF-8)
        Yii::$app->response->format = Response::FORMAT_JSON;
        Yii::$app->response->charset = 'UTF-8';

        return $b;
    }

    // ให้ทุกคอนโทรลเลอร์ที่สืบทอด รองรับ OPTIONS อัตโนมัติ
    public function actions()
    {
        $actions = parent::actions();
        $actions['options'] = [
            'class' => 'yii\rest\OptionsAction',
        ];
        return $actions;
    }

    // ====== Helpers (ปรับเพิ่ม 409 Conflict) ======
    public function apiValidate($errors, $message = false)
    {
        Yii::$app->response->statusCode = 422;
        return [
            'statusCode' => 422,
            'name'       => 'ValidateErrorException',
            'message'    => $message ?: 'Error validation',
            'errors'     => $errors
        ];
    }

    public function apiConflict($errorCode = 'CONFLICT', $message = 'Conflict', $extra = [])
    {
        Yii::$app->response->statusCode = 409; // ใช้กับ duplicate
        return array_merge([
            'status'    => 'error',
            'statusCode' => 409,
            'errorCode' => $errorCode,
            'message'   => $message,
        ], $extra);
    }

    public function apiCreated($data, $message = false)
    {
        Yii::$app->response->statusCode = 201;
        return ['statusCode' => 201, 'message' => $message ?: 'Created successfully', 'data' => $data];
    }

    public function apiUpdated($data, $message = false)
    {
        Yii::$app->response->statusCode = 202;
        return ['statusCode' => 202, 'message' => $message ?: 'Updated successfully', 'data' => $data];
    }

    public function apiDeleted($data, $message = false)
    {
        Yii::$app->response->statusCode = 202;
        return ['statusCode' => 202, 'message' => $message ?: 'Deleted successfully', 'data' => $data];
    }

    public function apiItem($data, $message = false)
    {
        Yii::$app->response->statusCode = 200;
        return ['statusCode' => 200, 'message' => $message ?: 'Data retrieval successfully', 'data' => $data];
    }

    public function apiCollection($data, $total = 0, $message = false)
    {
        Yii::$app->response->statusCode = 200;
        return ['statusCode' => 200, 'message' => $message ?: 'Data retrieval successfully', 'data' => $data, 'total' => $total];
    }

    public function apiSuccess($message = false)
    {
        Yii::$app->response->statusCode = 200;
        return ['statusCode' => 200, 'message' => $message ?: 'Success'];
    }
}
