<?php

namespace App\Http\Controllers\Admin\Api;

use App\Http\Controllers\Controller;
use App\Models\Appointment;
use App\Models\Cart;
use App\Models\Lab;
use App\Models\LabKit;
use App\Models\MedicalHistoryAnswer;
use App\Models\Patient;
use App\Models\PatientPrescription;
use App\Models\PatientRegActivity;
use App\Models\Plan;
use App\Models\PlanV1;
use App\Models\ProfileAnswer;
use App\Models\QuestionBuilder;
use App\Models\Telemedpro;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Routing\UrlGenerator;
use Illuminate\Support\Facades\URL;
use Yajra\DataTables\DataTables;
use Illuminate\Auth\Access\AuthorizationException;

class MedicineController extends Controller
{
    protected $url;
    protected $user;
    public function __construct(UrlGenerator $url)
    {
        $this->url = $url;
        $this->user = Auth::guard('admin')->user();
    }
    public function getMedList()
    {
        try{
            $this->authorizeForUser($this->user,'list', new PlanV1);
            $medicines = PlanV1::query();
            return Datatables::of($medicines)
                ->addColumn('image_url', function ($med) {
                    return URL::to("product/" . $med->image_url);
                })
                ->toJson();
        } catch (AuthorizationException $e) {
            return  $e->getMessage();
        }
    }
    public function SaveMed(Request $request)
    {
        try{
            $this->authorizeForUser($this->user,'add', new PlanV1);
            $slug = self::createSlug($request->get('slug'));
            if ($request->get('image')) {
                //upload website logo
                $fileName = $slug;
                $filePath = public_path() . '/product/';
                $fileName = $this->uploadImage($request->get('image'), $fileName, $filePath);
                ////////////////
            }

            PlanV1::create([
                'title' => $request->get('title'),
                'currency' => $request->get('currency'),
                'price' => $request->get('price'),
                'list_one_title' => $request->get('list_one_title'),
                'list_two_title' => $request->get('list_two_title'),
                'list_sub_title' => $request->get('list_sub_title'),
                'image_url' => $fileName,
                'slug' => $slug,
                'domain' => $request->get('domain'),
                'product_file_path' => null
            ]);
            return response()->json([
                'message' => "success"
            ]);
        } catch (AuthorizationException $e) {
            return  $e->getMessage();
        }
    }
    public function uploadImage($image, $fileName, $path)
    {
        try{
            $this->authorizeForUser($this->user,'edit', new PlanV1);
            $logo = base64_decode($image);
            $filename = (explode('/', finfo_buffer(finfo_open(), $logo, FILEINFO_MIME_TYPE))[0]);
            $ext = (explode('/', finfo_buffer(finfo_open(), $logo, FILEINFO_MIME_TYPE))[1]);
            $imageName =  $fileName . '.' . $ext;
            $path =  $path . $imageName;
            file_put_contents($path, $logo);
            return $imageName;
        } catch (AuthorizationException $e) {
            return  $e->getMessage();
        }
    }
    public function EditMed($id, Request $request)
    {
        try{
            $this->authorizeForUser($this->user,'edit', new PlanV1);
            $medicine = PlanV1::find($id);
            $slug = self::createSlug($request->get('slug'));
            $fileName = null;
            if ($request->get('image')) {
                //upload website logo
                $fileName = $slug;
                $filePath = public_path() . '/product/';
                $fileName = $this->uploadImage($request->get('image'), $fileName, $filePath);
                ////////////////
            }
            $medicine->title = $request->get('title');
            $medicine->currency = $request->get('currency');
            $medicine->price = $request->get('price');
            $medicine->list_one_title = $request->get('list_one_title');
            $medicine->list_two_title = $request->get('list_two_title');
            $medicine->list_sub_title = $request->get('list_sub_title');
            $medicine->image_url =  $fileName;
            $medicine->slug = $slug;
            $medicine->domain = $request->get('domain');
            $medicine->save();
            return response()->json([
                'message' => "success"
            ]);
        } catch (AuthorizationException $e) {
            return  $e->getMessage();
        }
    }
    public function DeleteMed($id, Request $request)
    {
        try{
            $this->authorizeForUser($this->user,'edit', new PlanV1);
            $medicine = PlanV1::where("id", $id)->delete();
            return response()->json([
                'message' => "success"
            ]);
        } catch (AuthorizationException $e) {
            return  $e->getMessage();
        }
    }
    private function createSlug($string)
    {
        $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

        return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
    }
    private function storeFile($file, $destinationPath)
    {
        //Display File Name
        $file->getClientOriginalName();
        $file->getClientOriginalExtension();
        $file->getRealPath();
        $file->getSize();
        $file->getMimeType();
        //Move Uploaded File

        $file->move($destinationPath, $file->getClientOriginalName() . '.' . $file->getClientOriginalExtension());
    }
    public function getFileList()
    {
        $files = PlanV1::select('product_file_path')->groupBy('product_file_path')->get();
        return response()->json([
            'medicines' => $files
        ]);
    }
    public function updateStatusPatientPrescription(PatientPrescription $PatientPrescription, Request $request)
    {
        $PatientPrescription->status = $request->input("status");
        $PatientPrescription->save();
        return response()->json([
            'status' => 'updated to ' . $request->input("status")
        ]);
    }
    public function updateStatusLabkit(Cart $cart, Request $request)
    {
        try{
            $this->authorizeForUser($this->user,'edit', new LabKit);
            $cart->status = $request->input("status");
            $cart->save();
            return response()->json([
                'status' => 'updated to ' . $request->input("status")
            ]);
        } catch (AuthorizationException $e) {
            return  $e->getMessage();
        }
    }
    public function labkitList()
    {
        try{
            $this->authorizeForUser($this->user,'edit', new LabKit);
            $labkit = LabKit::all();
            return response()->json([
                'labkit' => $labkit
            ]);
        } catch (AuthorizationException $e) {
            return  $e->getMessage();
        }
    }
    public function labsKitDelete(LabKit $labkit)
    {
        try{
            $this->authorizeForUser($this->user,'delete', new LabKit);
            $labkit->delete();
            return response()->json([
                'message' => "Deleted Successfully"
            ]);
        } catch (AuthorizationException $e) {
            return  $e->getMessage();
        }
    }
    public function labskitUpdate(LabKit $labkit, Request $request)
    {
        try{
            $this->authorizeForUser($this->user,'edit', new LabKit);
            $labkit->update($request->all());
            return response()->json([
                'message' => 'Labkit updated successfully',
                'telemed' => $labkit
            ]);
        } catch (AuthorizationException $e) {
            return  $e->getMessage();
        }
    }
    public function labskitCreate(LabKit $labkit, Request $request)
    {
        try{
            $this->authorizeForUser($this->user,'add', new LabKit);
            $labkit->create($request->all());
            return response()->json([
                'message' => 'Labkit created successfully',
                'telemed' => $labkit
            ]);
        } catch (AuthorizationException $e) {
            return  $e->getMessage();
        }
    }
    public function getPatientLabKitOrders(Patient $patient, Request $request)
    {
        $cart = Cart::with("patient")->where("patient_id", $patient->id)->get();
        return response()->json(['cart' => $cart], 200);
    }
}
