<?php

namespace App\Http\Controllers\OpdAppointment;

use App\Http\Controllers\Controller;
use App\Models\Doctor;
use App\Models\OpdPrescriptionImage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class OpdPrescriptionImageController extends Controller
{
    public function index(Request $request, $id)
    {
        $doctor_id = $id;
        $doctor = Doctor::with('getAccount')->find($id);
        $data = OpdPrescriptionImage::with(['getDoctorAccount'])
            ->select(
                'id',
                'doctor_id',
                'position',
                'image_url',
                'status',
            )->where('doctor_id',$doctor_id);
        $sort_by      = $request->get('sortby') ?? 10;
        if ($request->ajax()) {
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('position', 'like', '%' . $search_query . '%')
                    ->orWhere('position', 'like', '%' . $search_query . '%');
            })
                ->orderBy('id', 'DESC')
                ->paginate($sort_by);

            return view('doctor.prescription-setting.table', compact('data', 'doctor', 'doctor_id'));
        } else {
            $data = $data->orderBy('id', 'DESC')
                ->paginate($sort_by);

            return view('doctor.prescription-setting.index', compact('data', 'doctor', 'doctor_id'));
        }
    }
    public function create(Request $request, $id)
    {
        $doctor_id = $id;

        return view('doctor.prescription-setting.create', compact('doctor_id'));
    }
    public function store(Request $request, $id)
    {
        $validator =  Validator::make($request->all(), [
            'position' => 'required',
            'image' => 'required|mimes:jpeg,pdf,png,jpg,gif,svg,xlsx,docx|max:9000',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'message' => $validator->errors()->all()]);
        } else {

            if ($request->hasFile('image')) {
                $url      = \Str::slug($request->position);
                $path     = "upload/prescription_image/" . $id . '/' . $url . '/' . date('Y') . '/' . date('m');
                $response = uploadImage($path, $request->image);

                if ($response['status'] == true) {
                    $image = $response['file_name'];
                } else {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }
            } else {
                $image = '';
            }

            $doctorData = Doctor::find($id)->first();

            $existed = OpdPrescriptionImage::where([
                'position'       => $request->position,
                'doctor_id'      => $id,
                'chamber_id'     => $doctorData->doctors_chamber_id,
            ])
                ->first();
            if ($existed) {
                return response()->json(['success' => false, 'message' => 'Position Already Exited']);
            }
            $file = OpdPrescriptionImage::create([
                'position'       => $request->position,
                'doctor_id'      => $id,
                'image_url'      => $image,
                'status'         => '1',
                'chamber_id'     => $doctorData->doctors_chamber_id,
                'top_margin'     => $request->filled('top_margin') ? $request->top_margin : 1,
                'bottom_margin'  => $request->filled('bottom_margin') ? $request->bottom_margin : 1,
                'left_margin'    => $request->filled('left_margin') ? $request->left_margin : 1,
                'right_margin'   => $request->filled('right_margin') ? $request->right_margin : 1,
                'top_padding'    => $request->filled('top_padding') ? $request->top_padding : 1,
                'bottom_padding' => $request->filled('bottom_padding') ? $request->bottom_padding : 1,
                'left_padding'   => $request->filled('left_padding') ? $request->bottom_padding : 1,
                'right_padding'  => $request->filled('right_padding') ? $request->bottom_padding : 1,
                'height'         => $request->filled('height') ? $request->height : 1,
                'width'          => $request->filled('width') ? $request->width : 1,
                'alignment'      => $request->filled('alignment') ? $request->alignment : 1,
            ]);

            if ($request->ajax()) {
                return response()->json([
                    'success' => true,
                    'message' => 'Prescription has been uploaded successfully',
                    'data'    => $file
                ]);
            }

            return redirect()->route('doctor-prescription.index', $id)->with('success', "Prescription has been uploaded successfully");
        }
    }


    public function edit(Request $request, $id)
    {
        $prescriptions=OpdPrescriptionImage::find($id);
        return view('doctor.prescription-setting.edit', compact('id','prescriptions'));
    }

    public function update(Request $request, $id)
    {
        $validator =  Validator::make($request->all(),[
            'position' => 'required',
        ]);
        if($validator->fails())
        {
            return response()->json(['success'=>false,'message'=>$validator->errors()->all()]);
        }
        else{
            $prescriptions  =   OpdPrescriptionImage::find($id);
            $doctor_id = $prescriptions->doctor_id;

            $doctorData = Doctor::find($doctor_id)->first();

            $existed = OpdPrescriptionImage::where([
                'position'       => $request->position,
                'doctor_id'      => $doctor_id,
                'chamber_id'     => $doctorData->doctors_chamber_id,
            ])->whereNotIn('id', [$id])
                ->first();
            if ($existed) {
                return response()->json(['success' => false, 'message' => 'Position Already Exited']);
            }
           
            if ($request->hasFile('image')) {
                $url      = \Str::slug($request->position);
                $path     = "upload/prescription_image/" . $doctor_id . '/' . $url . '/' . date('Y') . '/' . date('m');
                $response = uploadImage($path,$request->image);

                if ($response['status'] == true)
                {
                    $image = $response['file_name'];
                }
                else
                {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }
            }
            else
            {
                $image=$prescriptions->image_url;
            }

            $data = array(
                        'position'       => $request->position,
                        'image_url'      => $image,
                        'chamber_id'     => $doctorData->doctors_chamber_id,
                        'top_margin'     => $request->filled('top_margin') ? $request->top_margin : 1,
                        'bottom_margin'  => $request->filled('bottom_margin') ? $request->bottom_margin : 1,
                        'left_margin'    => $request->filled('left_margin') ? $request->left_margin : 1,
                        'right_margin'   => $request->filled('right_margin') ? $request->right_margin : 1,
                        'top_padding'    => $request->filled('top_padding') ? $request->top_padding : 1,
                        'bottom_padding' => $request->filled('bottom_padding') ? $request->bottom_padding : 1,
                        'left_padding'   => $request->filled('left_padding') ? $request->bottom_padding : 1,
                        'right_padding'  => $request->filled('right_padding') ? $request->bottom_padding : 1,
                        'height'         => $request->filled('height') ? $request->height : 1,
                        'width'          => $request->filled('width') ? $request->width : 1,
                        'alignment'      => $request->filled('alignment') ? $request->alignment : 1,
                    );
            $prescriptions->update($data);

            $data=OpdPrescriptionImage::find($id);
            $Redirect = '';
            return response()->json([
                'success'=>true,
                'message'=>['Prescriptions successfully Update'],
                'data'=>$data
            ]);
        }
    }

    
    public function destroy(Request $request,$id)
    {
        
        $Delete = OpdPrescriptionImage::where(['id'=>$id])->delete();
    
        $Redirect = '';
        return response()->json([
            'success'=>true,
            'message'=>['Deleted successfully'],
            'data'=>[
            'redirect'=>$Redirect,
            ]
        ]);
    }


    public function changestatus(Request $request,$id)
    {
        if ($request->ajax())
        {
            $data = array('status' => $request->status );
            $Update =OpdPrescriptionImage::where('id', '=', $id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Status successfully change'],
                    'data'=>[
                        'redirect'=>'',
                        'reload'=>true,
                    ]
                ]);
            }
            else{
                return response()->json([
                    'success'=>false,
                    'message'=>['Error for change status'],
                    'data'=>[
                        'redirect'=>'',
                    ]
                ]);
            }
        }
    }
}
