<?php

namespace App\Http\Controllers;
use App\Enums\RecordStatusEnum;
use App\Http\Controllers\Helper\GlobalController;
use App\Models\BaseModel;
use App\Models\Department;
use App\Models\SampleType;
use App\Models\TestNormalValue;
use App\Models\TestSample;
use App\Models\TestSampleOrganism;
use Illuminate\Http\Request;
use App\Models\Laboratory;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use App\Models\LabConfigure;


class LabController extends Controller
{
    protected $model;
    protected $baseLabId;
    protected $testSampleModel;
    protected $labs;

    public function __construct(Laboratory $model, TestSample $testSampleModel){
        $this->model = $model;
        $this->testSampleModel = $testSampleModel;
        $this->baseLabId = Session::get('base_lab_id');
        $this->base = Session::get('base_lab');
    }

    public function index(Request $request){
        if(!GlobalController::user_can(Auth::user()->role_id, ['system_settings'])) return redirect(url('my-profile'));
        $lab = $this->model::query()->find($this->baseLabId);
        return view('laboratory', ['info' => $lab]);
    }

    public function save(Request $request){
        try {

            $validator = \Validator::make($request->all(), [
                'lab_name_en' => 'required',
                'lab_code' => 'required|max:5',
                'sample_number' => 'required',
                'patient_code' => 'required',
                'start_date' => 'required',
                'end_date' => 'nullable'
            ]);
            if ($validator->fails()) {
                return response()->json(['success' => false, 'message' => __('laboratory.create_fail'), 'errors' => $validator->errors()->all()]);
            }
            $data = array(
                'name_en' => $request->lab_name_en,
                'name_kh' => $request->lab_name_kh,
                'short_name' => $request->lab_code,
                'sample_number' => $request->sample_number,
                'patient_code' => $request->patient_code,
                'phone_number' => $request->phone_number,
                'lab_category_id' => $request->lab_category_id,
                'is_auto_make_invoice' => $request->is_auto_make_invoice,
                'email' => $request->email,
                'shareable_lab_result' => isset($request->shareable_lab_result) ? 1 : 0,
                'allow_external_request' => isset($request->allow_external_request) ? 1 : 0,
                'is_hide_comission_percentage' => isset($request->is_hide_comission_percentage) ? $request->is_hide_comission_percentage : 0,
                'is_hide_inv_discount' => 0,
                'address_en' => $request->address_en,
                'address_kh' => $request->address_kh,
                'start_date' => ($request->start_date ? date('Y-m-d H:i:s', strtotime($request->start_date)) : null),
                'end_date' => ($request->end_date ? date('Y-m-d H:i:s', strtotime($request->end_date)) : null),
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => Auth::id()
            );
            $this->model::query()->insert($data);
            return response()->json(['success' => true, 'message' => __('laboratory.create_success')]);
        }
        catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('laboratory.create_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function updateInfo(Request $request){
        try {
            $validator = \Validator::make($request->all(), [
                'name_en' => 'required',
                'name_kh' => 'required',
                'short_name' => 'required|max:3'
            ]);
            if ($validator->fails()) return response()->json(['errors' => $validator->errors()->all()]);
            $data = array(
                'name_en' => $request->name_en,
                'name_kh' => $request->name_kh,
                'short_name' => $request->short_name,
                'email' => $request->email,
                'phone_number' => $request->phone_number,
                'address_en' => $request->address_en,
                'address_kh' => $request->address_kh,
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => Auth::id()
            );
            $this->model::query()->where('id', $this->baseLabId)->update($data);
            return redirect()->back();
            //return response()->json(['success' => true, 'message' => __('laboratory.update_success')]);
        } catch (\Exception $e){
            dd($e);
            //return redirect()->back();
            return response()->json(['success' => false, 'message' => __('laboratory.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function update(Request $request){
        try {

            $validator = \Validator::make($request->all(), [
                'lab_name_en' => 'required',
                'lab_code' => 'required|max:5',
                'sample_number' => 'required',
                'patient_code' => 'required',
                'start_date' => 'required',
                'end_date' => 'nullable'
            ]);
            if ($validator->fails()) return response()->json(['errors' => $validator->errors()->all()]);
            $data = array(
                'name_en' => $request->lab_name_en,
                'name_kh' => $request->lab_name_kh,
                'short_name' => $request->lab_code,
                'sample_number' => $request->sample_number,
                'patient_code' => $request->patient_code,
                'phone_number' => $request->phone_number,
                'lab_category_id' => $request->lab_category_id,
                'is_auto_make_invoice' => $request->is_auto_make_invoice,
                'email' => $request->email,
                'shareable_lab_result' => isset($request->shareable_lab_result) ? 1 : 0,
                'allow_external_request' => isset($request->allow_external_request) ? 1 : 0,
                'is_hide_comission_percentage' => isset($request->is_hide_comission_percentage) ? $request->is_hide_comission_percentage : 0,
                'address_en' => $request->address_en,
                'address_kh' => $request->address_kh,
                'start_date' => ($request->start_date ? date('Y-m-d H:i:s', strtotime($request->start_date)) : null),
                'end_date' => ($request->end_date ? date('Y-m-d H:i:s', strtotime($request->end_date)) : null),
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => Auth::id()
            );
            $this->model::query()->where('id', $request->lab_id)->update($data);
            return response()->json(['success' => true, 'message' => __('laboratory.update_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('laboratory.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function get(Request $request){
        try{
            $lab_id = $request->lab_id;
            $lab = $this->model::query()->where('id', $lab_id)->get()->first();
            return response()->json(['success' => true, 'message' => __('laboratory.get_success'), 'data' => $lab]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('laboratory.get_fail'), 'errors' => $e->getMessage()]);
        }

    }

    public function delete(Request $request){
        try{
            $this->model::query()->where('id', $request->lab_id)->update(array(BaseModel::RECORD_STATUS_FIELD=> RecordStatusEnum::DELETE));
            return response()->json(['success' => true, 'message' => __('laboratory.delete_success')]);
        }
        catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('laboratory.delete_fail'), 'errors' => $e->getMessage()]);
        }

    }

    public function restore(Request $request){
        try{
            $this->model::query()->where('id', $request->lab_id)->update(array(BaseModel::RECORD_STATUS_FIELD=> RecordStatusEnum::ACTIVE));
            return response()->json(['success' => true, 'message' => __('laboratory.restore_success')]);
        }
        catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('laboratory.restore_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function profile(){
        if(!GlobalController::user_can(Auth::user()->role_id, ['update_laboratory_information'])) return redirect(url('my-profile'));
        $lab = $this->model::query()->find($this->baseLabId);
        return view('lab_profile', ['info' => $lab]);
    }

    public function labSettingSetters(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['system_settings'])) return redirect(url('my-profile'));
            $validator = \Validator::make($request->all(), [
                'sample_number' => 'required|integer',
                'patient_code' => 'required|integer',
                'technician_label' => 'nullable',
                'discount_type' => 'required|integer'
                ]);
            if ($validator->fails()){ return response()->json(['errors'=>$validator->errors()->all()]);}
            $lab = $this->model::query()->where('id', $this->baseLabId)->first();
            $lab->update(array(
                'sample_number' => $request->sample_number,
                'currency' => $request->currency,
                'patient_code' => $request->patient_code,
                'technician_label' => $request->technician_label,
                'discount_type' => $request->discount_type,
                'phone_number' => $request->phone_number,
                'email' => $request->email,
                'exchange_rate' => $request->exchange_rate,
                //'is_hide_inv_discount' => $request->is_hide_inv_discount,
                'abnormal_text_color' => $request->abnormal_text_color,
                'show_result_footer' => $request->show_result_footer,
                'abnormal_result_font_weight' => $request->abnormal_result_font_weight,
                'result_header_id' => $request->result_header_id,
                'is_auto_make_invoice' => $request->is_auto_make_invoice,
                'invoice_template_id' => $request->invoice_template_id
            ));
            return response()->json(['success' => true, 'message' => __('laboratory.update_success'), 'data' => $lab]);
        } catch (\Exception $e)
        {
            return response()->json(['success'=> false , 'message' => __('laboratory.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function uploadImage(Request $request){
        try {
            $image = $request->file('image');
            $imageName = 'avatar_'.$this->baseLabId.'.' . $image->getClientOriginalExtension();
            $lab = $this->model::query()->where('id', $this->baseLabId)->first();
            $lab->update(array('logo' => $imageName));
            $image->move(public_path('storage/images/avatars/labs'), $imageName);
            return response()->json(['success' => true, 'message' => __('laboratory.update_success'), 'data' => $lab]);
        }catch (\Exception $e){
            return response()->json(['success'=> false , 'message' => __('laboratory.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function removeLabLogo(Request $request){
        try {
            $lab = $this->model::query()->find($this->baseLabId);
            if(!empty($lab->logo)) {
                if (file_exists(public_path('storage/images/avatars/labs/' . $lab->logo))) {
                    unlink(public_path('storage/images/avatars/labs/' . $lab->logo));
                    $lab->logo = null;
                }
            }
            $lab->save();
            return response()->json(['success' => true, 'message' => __('laboratory.update_success'), 'data' => $lab]);
        }catch (\Exception $e){
            return response()->json(['success'=> false , 'message' => __('laboratory.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function saveLabConfigure(Request $request){
        try{
            $validator = \Validator::make($request->all(), [
                'attribute_code' => 'required|string',
                'attribute_value' => 'required|string'
            ]);
            if ($validator->fails()){ return response()->json(['errors'=>$validator->errors()->all()]);}
            $labSetting = $this->labConfigureModel::query()->firstOrNew(['atrribute_code' => $request->attribute_code, 'lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD=> RecordStatusEnum::ACTIVE]);
            $labSetting->assigned_attribute_value = $request->attribute_value;
            $labSetting->save();
            return response()->json(['success' => true, 'message' => __('laboratory.update_success'), 'data' => $labSetting]);
        } catch (\Exception $e)
        {
            return response()->json(['success'=> false , 'message' => __('laboratory.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function initLabData(){
        return view('clone_lab',['labs' => $this->labs]);
    }

    function getLabData($labId){
        try{
            $department = Department::query()->with([
                'samples',
                'samples.testSamples',
                'samples.testSamples.testValues',
                'samples.testSamples.organisms',
                'samples.testSamples.organisms.antibiotics'
            ])->where(['lab_id' => $labId, BaseModel::RECORD_STATUS_FIELD => 1])->get()->toArray();
            return response()->json(['success' => true, 'data' => $department]);
        }
        catch (\Exception $e){
            return response()->json(['success'=> false , 'message' => 'Error while retrieving lab data.']);
        }
    }

    /** Verify Image */

    public function uploadVerifyImage(Request $request){
        try {
            $image = $request->file('image');
            $imageName = 'verify_label_'.$this->baseLabId.'.' . $image->getClientOriginalExtension();
            $lab = $this->model::query()->where('id', $this->baseLabId)->first();
            $lab->update(array('verify_label' => $imageName));
            $image->move(public_path('storage/images/avatars/labs'), $imageName);
            return response()->json(['success' => true, 'message' => __('laboratory.update_success'), 'data' => $lab]);
        }catch (\Exception $e){
            return response()->json(['success'=> false , 'message' => __('laboratory.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function removeVerifyImage(Request $request){
        try {
            $lab = $this->model::query()->find($this->baseLabId);
            if(!empty($lab->verify_label)) {
                if (file_exists(public_path('storage/images/avatars/labs/' . $lab->verify_label))) {
                    unlink(public_path('storage/images/avatars/labs/' . $lab->verify_label));
                    $lab->verify_label = null;
                }
            }
            $lab->save();
            return response()->json(['success' => true, 'message' => __('laboratory.update_success'), 'data' => $lab]);
        }catch (\Exception $e){
            return response()->json(['success'=> false , 'message' => __('laboratory.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    function updateHeading(){
         $targetLabTestSample = TestSample::query()->where(['lab_id' =>  18,'sample_type_id'=>397, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
                ->where('heading_id','>',0)->get();
           foreach ($targetLabTestSample as $targetTestSample){
               dd($targetTestSample);
                $source = TestSample::query()->where(['id' => $targetTestSample->heading_id, 'lab_id' => 29])->get();//->first();
              dd($source);
               $target = TestSample::query()->where(['lab_id' => 18, 'test_id' => $source->test_id , 'sample_type_id' => $targetTestSample->sample_type_id ])->get()->first();

                //TestSample::query()->where(['id' => $targetTestSample->id])->update([ 'heading_id' => $target->id]);
            }
    }


    public function uploadAlternativeLogo(Request $request){
        try {
            $image = $request->file('image');
            $imageName = 'alternative_logo_'.$this->baseLabId.'.' . $image->getClientOriginalExtension();
            $lab = $this->model::query()->where('id', $this->baseLabId)->first();
            $lab->update(array('alternative_logo' => $imageName));
            $image->move(public_path('storage/images/avatars/labs/alternative_logo'), $imageName);
            return response()->json(['success' => true, 'message' => __('laboratory.update_success'), 'data' => $lab]);
        }catch (\Exception $e){
            return response()->json(['success'=> false , 'message' => __('laboratory.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function removeAlternativeLogo(Request $request){
        try {
            $lab = $this->model::query()->find($this->baseLabId);
            if(!empty($lab->alternative_logo)) {
                if (file_exists(public_path('storage/images/avatars/labs/alternative_logo/' . $lab->alternative_logo))) {
                    unlink(public_path('storage/images/avatars/labs/alternative_logo/' . $lab->alternative_logo));
                    $lab->alternative_logo = null;
                }
            }
            $lab->save();
            return response()->json(['success' => true, 'message' => __('laboratory.update_success'), 'data' => $lab]);
        }catch (\Exception $e){
            return response()->json(['success'=> false , 'message' => __('laboratory.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

// Alternative Verify Signature
    public function uploadAlterVerifySignature(Request $request){
        try {
            $image = $request->file('image');
            $imageName = 'alter_verify_sign_'.$this->baseLabId.'.' . $image->getClientOriginalExtension();
            $lab = $this->model::query()->where('id', $this->baseLabId)->first();
            $lab->update(array('alter_verify_sign' => $imageName));
            $image->move(public_path('storage/images/avatars/labs'), $imageName);
            return response()->json(['success' => true, 'message' => __('laboratory.update_success'), 'data' => $lab]);
        }catch (\Exception $e){
            return response()->json(['success'=> false , 'message' => __('laboratory.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function removeAlterVerifySignature(Request $request){
        try {
            $lab = $this->model::query()->find($this->baseLabId);
            if(!empty($lab->alter_verify_sign)) {
                if (file_exists(public_path('storage/images/avatars/labs/' . $lab->alter_verify_sign))) {
                    unlink(public_path('storage/images/avatars/labs/' . $lab->alter_verify_sign));
                    $lab->alter_verify_sign = null;
                }
            }
            $lab->save();
            return response()->json(['success' => true, 'message' => __('laboratory.update_success'), 'data' => $lab]);
        }catch (\Exception $e){
            return response()->json(['success'=> false , 'message' => __('laboratory.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

// Alternative Labtech Signature
    public function uploadAlterLabtechSignature(Request $request){
        try {
            $image = $request->file('image');
            $imageName = 'alter_labtech_sign_'.$this->baseLabId.'.' . $image->getClientOriginalExtension();
            $lab = $this->model::query()->where('id', $this->baseLabId)->first();
            $lab->update(array('alter_labtech_sign' => $imageName));
            $image->move(public_path('storage/images/avatars/labs'), $imageName);
            return response()->json(['success' => true, 'message' => __('laboratory.update_success'), 'data' => $lab]);
        }catch (\Exception $e){
            return response()->json(['success'=> false , 'message' => __('laboratory.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function removeAlterLabtechSignature(Request $request){
        try {
            $lab = $this->model::query()->find($this->baseLabId);
            if(!empty($lab->alter_labtech_sign)) {
                if (file_exists(public_path('storage/images/avatars/labs/' . $lab->alter_labtech_sign))) {
                    unlink(public_path('storage/images/avatars/labs/' . $lab->alter_labtech_sign));
                    $lab->alter_labtech_sign = null;
                }
            }
            $lab->save();
            return response()->json(['success' => true, 'message' => __('laboratory.update_success'), 'data' => $lab]);
        }catch (\Exception $e){
            return response()->json(['success'=> false , 'message' => __('laboratory.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    /** default footer */
    public function uploadDefaultFooter(Request $request){
        try {
            $image = $request->file('image');
            $imageName = 'default_footer_'.$this->baseLabId.'.' . $image->getClientOriginalExtension();
            $lab = $this->model::query()->where('id', $this->baseLabId)->first();
            $lab->update(array('footer' => $imageName));
            $image->move(public_path('storage/images/avatars/labs/default_footer'), $imageName);
            return response()->json(['success' => true, 'message' => __('laboratory.update_success'), 'data' => $lab]);
        }catch (\Exception $e){
            return response()->json(['success'=> false , 'message' => __('laboratory.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function removeDefaultFooter(Request $request){
        try {
            $lab = $this->model::query()->find($this->baseLabId);
            if(!empty($lab->footer)) {
                if (file_exists(public_path('storage/images/avatars/labs/default_footer/' . $lab->footer))) {
                    unlink(public_path('storage/images/avatars/labs/default_footer/' . $lab->footer));
                    $lab->footer = null;
                }
            }
            $lab->save();
            return response()->json(['success' => true, 'message' => __('laboratory.update_success'), 'data' => $lab]);
        }catch (\Exception $e){
            return response()->json(['success'=> false , 'message' => __('laboratory.update_fail'), 'errors' => $e->getMessage()]);
        }
    }
    /* default footer end */

    /** alternative footer */
    public function uploadAlternativeFooter(Request $request){
        try {
            $image = $request->file('image');
            $imageName = 'alternative_footer_'.$this->baseLabId.'.' . $image->getClientOriginalExtension();
            $lab = $this->model::query()->where('id', $this->baseLabId)->first();
            $lab->update(array('alternative_footer' => $imageName));
            $image->move(public_path('storage/images/avatars/labs/alternative_footer'), $imageName);
            return response()->json(['success' => true, 'message' => __('laboratory.update_success'), 'data' => $lab]);
        }catch (\Exception $e){
            return response()->json(['success'=> false , 'message' => __('laboratory.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function removeAlternativeFooter(Request $request){
        try {
            $lab = $this->model::query()->find($this->baseLabId);
            if(!empty($lab->alternative_footer)) {
                if (file_exists(public_path('storage/images/avatars/labs/alternative_footer/' . $lab->alternative_footer))) {
                    unlink(public_path('storage/images/avatars/labs/alternative_footer/' . $lab->alternative_footer));
                    $lab->alternative_footer = null;
                }
            }
            $lab->save();
            return response()->json(['success' => true, 'message' => __('laboratory.update_success'), 'data' => $lab]);
        }catch (\Exception $e){
            return response()->json(['success'=> false , 'message' => __('laboratory.update_fail'), 'errors' => $e->getMessage()]);
        }
    }
    /* alternative footer end */

}
