<?php

namespace App\Http\Controllers;
use App\Enums\RecordStatusEnum;
use App\Http\Controllers\Helper\GlobalController;
use App\Models\BaseModel;
use App\Models\SampleType;
use Illuminate\Http\Request;
use App\Models\Organization;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;


class OrganizationController extends Controller
{
    protected $model;
    protected $baseOrganizationId;
    protected $labs;

    public function __construct(Organization $model){
        $this->model = $model;
        $this->baseOrganizationId = Session::get('base_organization_id');
        $this->base = Session::get('base_organization');
    }

    public function index(Request $request){
        $recordStatusCondition = Auth::id()==1 ? [RecordStatusEnum::DELETE, RecordStatusEnum::ACTIVE] : [RecordStatusEnum::ACTIVE];
        $labs = $this->model::query()->whereIn(BaseModel::RECORD_STATUS_FIELD, $recordStatusCondition)
            ->when(Auth::id()!=1, function ($labs){
                $labs->whereIn('id', $this->labs->pluck('id'));
            })->when(!empty($request->kword), function ($labs) use($request){
                $labs->whereRaw("replace(name_en, ' ','') like '%".str_replace(" ","",$request->kword)."%'")
                    ->orWhereRaw("replace(name_kh, ' ','') like '%".str_replace(" ","",$request->kword)."%'")
                    ->orWhere('address_en','like','%'.$request->kword.'%')
                    ->orWhere('address_kh','like','%'.$request->kword.'%');
            })->orderBy(BaseModel::CREATED_AT,'desc')->paginate(config('labis.pagination.perpage', 10));
        return view('laboratory', ['laboratories' => $labs]);
    }

    public function save(Request $request){
        try {

            $validator = \Validator::make($request->all(), [
                'lab_name_en' => 'required',
                'lab_code' => 'required|max:10',
                '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,
                'code' => $request->lab_code,
                'phone_number' => $request->phone_number,
                'email' => $request->email,
                'address_en' => $request->address_en,
                'address_kh' => $request->address_kh,
                '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:10'
            ]);
            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->baseOrganizationId)->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->organization_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{
            $organization_id = $request->organization_id;
            $lab = $this->model::query()->where('id', $organization_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->organization_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->organization_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'));
        $organization = $this->model::query()->find($this->baseOrganizationId);
        return view('organization_profile', ['info' => $organization]);
    }

    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->baseOrganizationId)->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->baseOrganizationId.'.' . $image->getClientOriginalExtension();
            $lab = $this->model::query()->where('id', $this->baseOrganizationId)->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->baseOrganizationId);
            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()]);
        }
    }


}
