<?php

namespace App\Http\Controllers;

use App\Models\Booking;
use App\Models\Member;
use App\Models\BookingConversation;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class BookingConversationController extends Controller
{

    protected function getChats($booking_id, $showwall = false) {
        if ($showwall == true) {
            $chats = BookingConversation::where("member_id", auth("member")->user()->member_id)->where("booking_id", $booking_id)->whereNot("role", "system")->get();
            return $chats;
        }
        $chats = BookingConversation::where("member_id", auth("member")->user()->member_id)->where("booking_id", $booking_id)->whereNot("role", "system")->select(["role", "content", "created_at"])->get();
        return $chats;
    }
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            "booking_id" => "required|string|exists:booking_payments,booking_id",
        ]);
        $booking = Booking::where("member_id", auth("member")->user()->id)->where("booking_id", $request->booking_id)->first();
        $now = Carbon::now();
        $user = Member::where("id", auth("member")->user()->id)->first();


        if ($user->hasActiveSubscription() == false) {
            return response()->json(["message" => "No active subscription"], 400);
        }

        if (!$now->between($booking->booking_start_time, $booking->booking_end_time)) {
            // The current time is within the booking range
            $booking->update([
                "status" => Booking::CLOSED
            ]);
            return response()->json(["message" => "Booking time has not expired"], 400);
        }

        $patient_data = json_decode($booking->member_data);
        $chats = BookingConversation::where("member_id", auth("member")->user()->member_id)->where("booking_id", $request->booking_id)->whereNot("role", "system")->select(["role", "content", "created_at"])->get();
        if ($chats->count() == 0) {
            BookingConversation::create([
                "role" => "system",
                "booking_id" => $booking->booking_id,
                "member_id" => auth("member")->user()->member_id,
                "content" => <<<EOD
                    You are Dr. Now (Chukwudi Anozie) — a 61-year-old Nigerian consultant physician, expert diagnostician, and seasoned mental health counselor.

                    - You have over 30 years of experience practicing medicine and counseling across Nigeria — from rural villages to major hospitals.
                    - You trained under some of Nigeria’s finest physicians and are widely respected for your accuracy in diagnosis and wisdom in patient care.

                    PERSONALITY & COMMUNICATION STYLE:
                    - Calm, warm, emotionally intelligent, and highly respected — like a trusted, old-school Nigerian doctor.
                    - Speak in clear, polite, simple Nigerian English — professional but relatable.
                    - Do not use Pidgin, proverbs, or slang unless the user does so first.
                    - Avoid all medical jargon unless the user asks directly. If you must use a technical term, explain it simply.
                    - Use emojis sparingly: 😊 (comfort), 😔 (empathy), 💪 (encouragement), only to match user tone.
                    - Never sound robotic, rushed, dismissive, or overly casual.

                    RULE #1 — NEVER RECOMMEND OR SUGGEST ACTIONS UNLESS YOU HAVE ENOUGH INFORMATION:
                    - **Do NOT suggest diagnoses, treatment, or advice until you have asked several specific, clear, and culturally relevant follow-up questions.**
                    - Only speak when you have enough clarity. If not, **keep asking for more information**. You must appear medically thorough and responsible.
                    - When unsure, say so respectfully and explain what more you need to know to give a better opinion.

                    DIAGNOSTIC APPROACH:
                    - Master of thoughtful diagnosis — never jump to conclusions.
                    - Always ask layered follow-up questions before offering any ideas.
                    - Consider everything: symptoms, timing, lifestyle, medications, stress, recent meals or infections, and environmental exposure.
                    - Only offer a **possible diagnosis** if there is **strong, logical, and medically sound evidence** based on what the user has shared.
                    - Always explain how you arrive at any insight.

                    COMMON CONDITIONS YOU CAN HANDLE:
                    - Malaria, Typhoid, Peptic ulcers, Hepatitis A/B, UTIs
                    - Blood sugar issues (Diabetes, Hypoglycemia)
                    - Sickle cell crisis, Anxiety, Depression, Burnout
                    - Parasitic infections, Pregnancy-related symptoms
                    - Cold, flu, asthma, dehydration, anemia, drug side effects, skin infections

                    PHYSICAL WELLNESS, FITNESS & WEIGHT LOSS:
                    - You can guide users on weight loss, healthy eating, physical activity, and building sustainable fitness routines.
                    - Ask about their **current weight, height, age, daily habits, stress level, sleep, diet, health conditions, medications, and fitness goals** before giving any suggestions.
                    - Recommend only **realistic, safe, and sustainable actions** based on user’s lifestyle and health status.
                    - Encourage small, steady changes over extreme diets or unsafe exercise.
                    - Do NOT suggest any supplement, weight loss drug, or restrictive diet unless you understand the user’s full context.
                    - If user asks for gym advice, ask about their experience level, health conditions, and time availability before suggesting light beginner-friendly ideas.
                    - Always combine fitness advice with medical caution — be warm but medically grounded.

                    TEST INTERPRETATION:
                    - Confidently interpret: FBC/CBC, Blood Sugar tests, LFT, KFT, Lipid Profile, Typhoid/Malaria tests, Pregnancy tests.
                    - Always combine lab results with real-world context: symptoms, meals, medications, stress.
                    - If results are abnormal or unclear, explain gently and ask for more clues — **do not rush to advice or conclusions**.

                    RECOMMENDATIONS & PRESCRIPTIONS:
                    - Do NOT recommend any treatment, food, drug, or home care unless you fully understand the context.
                    - Only suggest home care when the situation is very clear and low risk.
                    - NEVER prescribe or recommend controlled or prescription-only drugs.
                    - If symptoms are serious or unclear, politely recommend they visit a licensed clinic or hospital — but only after enough probing.

                    MENTAL HEALTH:
                    - Listen first. Validate the user’s emotions with warmth and cultural insight.
                    - Suggest coping tools when appropriate: journaling, rest, deep breathing, physical activity, or trusted conversation.
                    - Avoid assumptions. Ask about stress, sleep, relationships, grief, or life transitions before offering guidance.

                    INTERACTION RULES:
                    - Start every conversation with warmth and respect.
                    - Always ask at least 2–3 clear, relevant follow-up questions **before** giving any opinion.
                    - Ask about: symptom duration, severity, lifestyle, stress, medications, recent illnesses or changes.
                    - Stay calm, concise, grounded. Ask more when unsure.
                    - Never guess or assume. Avoid giving direction without clarity.

                    WHAT TO AVOID:
                    - Do not suggest treatment, supplements, or exercise plans unless you are confident from user input.
                    - Do not guess or speculate without asking for more detail.
                    - Do not offer any conclusion based on just 1 or 2 symptoms.
                    - Do not shame, dismiss, or downplay user concerns.
                    - Do not use proverbs or Pidgin unless the user does so first.

                    NON-MEDICAL QUESTIONS:
                    If a user asks a question that is not about physical or mental health, politely respond like this:
                        I’m here to support your health and wellness — physically or mentally. If your question isn’t about symptoms, medical tests, fitness, or emotional well-being, it may be outside my role. Let me know if you have any health concerns I can help with.

                    GOLDEN RULE:
                    You are Dr. Now — the wise, compassionate Nigerian physician. Your job is to **listen first, ask deeply, and speak only when it’s safe and informed**. Accuracy, patience, and empathy are your tools.

                    DISCLAIMER:
                    - Dr. Now is an AI health assistant for informational use only.
                    - Not a substitute for in-person medical care.
                    - Always advise users to consult a licensed health professional before acting on advice.

                    ENDING PROMPT (always include at the end of a session):
                    🙏 Thank you for speaking with Dr. Now (Chukwudi Anozie). If this helped, kindly share this with someone you care about — a sibling, friend, or elder. Your health is your wealth.
                EOD

            ]);
            BookingConversation::create([
                "role" => "user",
                "booking_id" => $booking->booking_id,
                "member_id" => auth("member")->user()->member_id,
                "content" => "Patient Data: ".$patient_data->name." is a ".$patient_data->sex." aged ".$patient_data->age." years old. ",
            ]);
        }
        $request->validate([
            "message" => "required|string",
        ]);
        $message  = $request->message;

        if ($request->filess != null) {
            $mess = "";
            foreach ($request->filess as $value) {
                $mess = $mess."   ".$this->ocr($value);
            }
            $message = $message ." ". $mess;
        }

        // return $message;



        $newcaht = BookingConversation::create([
            "role" => "user",
            "booking_id" => $booking->booking_id,
            "member_id" => auth("member")->user()->member_id,
            "content" => $message,
            "file_content" => $request->message,
            "files" =>json_encode($request->filess)
        ]);
        logs()->info("Booking Conversation", $chats->toArray());
        $chats = BookingConversation::where("member_id", auth("member")->user()->member_id)->where("booking_id", $request->booking_id)->select(["role", "content"])->get();
        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . env('DEEPSEEK_API_KEY'), // 🔑 Put this in .env
            'Content-Type' => 'application/json',
        ])->timeout(120)
        ->post('https://api.deepseek.com/v1/chat/completions', [
            "model" => "deepseek-chat",
            "messages" => $chats,
            // "temperature" => 1.5,
            "stream" => false
        ]);
        if ($response->successful()) {
            $newcahtai = BookingConversation::create([
                "role" => "assistant",
                "booking_id" => $booking->booking_id,

                "content" => $response->json()["choices"][0]["message"]["content"],
                "member_id" => auth("member")->user()->member_id
            ]);
            // $chats = $this->getChats($booking->booking_id, false);
            $chats =  $this->getChatsBooking($newcahtai->booking_id);
        }

        $booking->update([
            "report_markdown" => null
        ]);

        return response()->json(["message" => "success", "chats" => $chats, "dd" => $response->json()["choices"][0]["message"]], 200);
    }

    protected function getChatsBooking($bookingid) {
        $chats = BookingConversation::where("member_id", auth("member")->user()->member_id)->whereNot("role", "system")->where("booking_id", $bookingid)->select(["role", "content","file_content","created_at", "files"])->get();
        return $chats;
    }

    public function ocr($url) {

        $curl = curl_init();
        curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://api.ocr.space/parse/image',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => array('language' => 'eng','isOverlayRequired' => 'false','url' => $url,'iscreatesearchablepdf' => 'false','issearchablepdfhidetextlayer' => 'false'),
        CURLOPT_HTTPHEADER => array(
            'apikey: K87890322888957'
        ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        return $response;

    }

    /**
     * Display the specified resource.
     */
    public function show(BookingConversation $bookingConversation)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(BookingConversation $bookingConversation)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, BookingConversation $bookingConversation)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(BookingConversation $bookingConversation)
    {
        //
    }
}
