<?php

namespace api\modules\v1\controllers;

use api\components\Controller;
use common\models\HisRequest;
use common\models\HisRequestTestList;
use Yii;
use OpenApi\Annotations as OA;
use yii\helpers\Json;

/**
 * @OA\Tag(
 *   name="HisRequest",
 *   description="Hospital import endpoints"
 * )
 */
class HisRequestController extends Controller
{

    /**
     * @OA\Post(
     *   path="/his-request",
     *   summary="Create data hospital request API",
     *   operationId="hisRequestCreate",
     *   tags={"HisRequest"},
     *   security={{"bearerAuth": {}}},
     *   requestBody={"$ref":"#/components/requestBodies/HisRequestCreateBody"},
     *   @OA\Response(response=201, ref="#/components/responses/HisRequestCreated"),
     *   @OA\Response(response=422, ref="#/components/responses/ValidationError")
     * )
     */
    public function actionCreate()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        //error_log(Yii::$app->request->rawBody);

        if (empty(Yii::$app->request->rawBody)) {
            return ['message' => 'ไม่มีข้อมูล'];
        }
        $data['HisRequest'] = Json::decode(Yii::$app->request->rawBody);

        // เริ่มทำงานแบบ Transaction
        $tx = Yii::$app->db->beginTransaction();
        try {
            $hisRequest = HisRequest::findOne(['LabNo' => $data['HisRequest']['LabNo']]);
            if ($hisRequest === null) {
                $hisRequest = new HisRequest();
            }
            $hisRequest->setAttributes($data['HisRequest']);

            $hisRequest->UserID = Yii::$app->user->getId();
            $hisRequest->CustomerCode = Yii::$app->user->identity->username;
            if (!$hisRequest->save()) {
                throw new \RuntimeException($this->firstError($hisRequest->getFirstErrors()));
            }

            foreach ($data['HisRequest']['TestList'] as $chargeData) {
                $charge = HisRequestTestList::findOne([
                    'HisRequestID' => $hisRequest->ID,
                    'TestCode' => $chargeData['TestCode']
                ]);
                if ($charge === null) {
                    $charge = new HisRequestTestList();
                }
                $charge->setAttributes($chargeData);
                $charge->HisRequestID = $hisRequest->ID;
                if (!$charge->save()) {
                    throw new \RuntimeException($this->firstError($charge->getFirstErrors()));
                }
            }

            // ถึงตรงนี้ทุกอย่างบันทึกฐานข้อมูลสำเร็จ → commit
            $tx->commit();

            //ส่งไป Prolab
            error_log('Before Send API');
            $prolab_result = Yii::$app->pathology->createRequestOrderCurl($hisRequest);
            error_log('Prolab Result ' . (is_array($prolab_result) ? reset($prolab_result) : ''));
            Yii::$app->response->statusCode = 201;
            return ['message' => 'success', 'status' => 0];
        } catch (\Throwable $e) {
            // มีข้อผิดพลาด → rollback
            if ($tx->isActive) {
                $tx->rollBack();
            }
            Yii::$app->response->statusCode = 422;
            // ส่งข้อความแรกที่ชัดเจนกลับไปให้ client
            return ['message' => $e->getMessage(), 'status' => 1];
        }
    }

    /**
     * ดึงข้อความ error แรกอย่างปลอดภัย
     */
    private function firstError($errors): string
    {
        if (is_array($errors) && !empty($errors)) {
            $first = reset($errors);
            return is_array($first) ? reset($first) : (string)$first;
        }
        return 'เกิดข้อผิดพลาดที่ไม่ทราบสาเหตุ';
    }
}