<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Sample;
use App\Models\TestResult;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SampleResultController extends Controller
{
    //
    protected $sampleModel;
    protected $testResultModel;
    public function __construct(){
        $this->sampleModel = new Sample();
        $this->testResultModel = new TestResult();
    }

    public function pushLabResult(Request $request){
        try{
            $validator = \Validator::make($request->all(), ['message.pid' => 'required', 'message.result' => 'required']);
            if ($validator->fails()) return response()->json(['success' => false, 'message' => __('Some variables are requires'), 'errors' => $validator->errors()->all()]);
            $testSamples = collect($this->getSampleTest($request->message['pid']));

            if(!empty($testSamples)) {
                foreach ($request->message['result'] as $row) {
                    if (!empty($row['code']) && !empty($row['value'])) {
                        $resultRecord = $testSamples->filter(function ($val, $key) use ($row) {
                            return $val->code == $row['code'];
                        })->first();
                        if(!empty($resultRecord)){
                            $data = array(
                                'test_result' => $row['value'],
                                'test_date' => date('Y-m-d'),
                                'created_at' => date('Y-m-d H:i:s')
                            );
                            $this->testResultModel::query()->where(['id' => $resultRecord->result_id])->update($data);
                        }
                    }
                }
            }
            return response()->json(['success' => true, 'message' => __('Laboratory result already pushed!')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('Failed while pushing laboratory result!'), 'errors' => $e->getMessage()]);
        }
    }

    private function getSampleTest( $sampleNumber){
        return DB::select("SELECT
                s.id,
                tr.id as result_id,
                tr.test_sample_id,
                tr.test_result,
                ts.code,
                ts.`unit_sign`
                FROM samples s
                INNER JOIN test_results tr ON tr.`sample_id` = s.`id` AND tr.`record_status_id` = 1
                INNER JOIN test_samples ts ON ts.`id` = tr.`test_sample_id`
                WHERE s.`sample_number` = '".$sampleNumber."'");
    }

}
