<?php

namespace App\Http\Controllers;

use App\Models\Booking;
use App\Models\BookingPayment;
use Carbon\Carbon;
use App\Models\Member;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use App\Models\BookingConversation;
use Barryvdh\DomPDF\Facade\Pdf;
use League\CommonMark\CommonMarkConverter;
use Illuminate\Support\Facades\DB;

class BookingController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $latestConversations = BookingConversation::where("member_id", auth("member")->user()->member_id)->join(DB::raw('(
            SELECT booking_id, MAX(created_at) AS max_created_at
            FROM booking_conversations
            GROUP BY booking_id
        ) as latest'), function ($join) {
            $join->on('booking_conversations.booking_id', '=', 'latest.booking_id')
                 ->on('booking_conversations.created_at', '=', 'latest.max_created_at');
        })
        ->select('booking_conversations.*')
        ->latest()
        ->get();
        $member = Member::where("member_id", auth("member")->user()->member_id)->first();
        if ($member->hasActiveSubscription() == false) {
            $member->update([
                "next_subscription_date" => null
            ]);
            // return response()->json(["message" => "No active subscription"], 400);
        }
        return response()->json([
            "message" => "Bookings successfully",
            "data" => $latestConversations,
            "member" => $member,
            "price" => 100
        ], 201);
    }

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

    /**
     * Store a newly created resource in storage.
     */
    public function download(Request $request)
        {

            $request->validate([
                "booking_id" => "required|string|exists:booking_payments,booking_id",
            ]);

            $booking = Booking::where("booking_id", $request->booking_id)->first();
            if ($booking->report_markdown != null) {
                return $this->getReport($booking->report_markdown);
            }
            $now = Carbon::now();


            $chats = BookingConversation::where("booking_id", $request->booking_id)->select(["role", "content"])->get()->toArray();
            if (count($chats) < 5) {
               return response()->json([ "message"=>"not enough content to create report"], 400);
            }

            $chats[] = [
                "role" => "assistant",
                "content" => "
                    You are an AI medical assistant. Generate a professional doctor's report using the SOAPE (Subjective, Objective, Assessment, Plan, Evaluation/Education) model for this booking made on {$now}. The consultation is handled by an AI doctor, and the Booking/Consultation ID is {$request->booking_id}.

                    Use the following structure:

                    ## SOAPE Medical Report

                    **Booking Date:** {$now}
                    **Consultation ID:** {$request->booking_id}
                    **Consulted by:** AI Medical Assistant

                    ### S – Subjective
                    (Patient's reported symptoms, complaints, and medical history.)

                    ### O – Objective
                    (Clinical findings, vitals, observations, lab results, if any.)

                    ### A – Assessment
                    (Professional interpretation of the condition. Include differential diagnosis if relevant.)

                    ### P – Plan
                    (Proposed treatment, lifestyle advice, medications, further investigations or referrals.)

                    ### E – Evaluation / Education
                    (What the patient was educated about, follow-up instructions, and response to advice.)

                    ⚠️ Do not include system ID, license information, or support links.
                    🧾 Only respond with the markdown in a detailed and explanatory format. No emojis.

                    make it uptimzed for a doctor and human to read and understand. Use markdown format.
                    it will be render for A4 paper size.

                    make the markdown in a detailed and explanatory format. No emojis.
                    make it uptimzed for a doctor and human to read and understand. Use markdown format.
                    it will be render for A4 paper size.
                    format it properly and make it look good.
                    use headings, subheadings, bullet points, and other formatting techniques to enhance readability.
                    make it look like a professional medical report.

                    dont return ```markdown as part of response just return the markdown content only .

                "

            ];
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . env('DEEPSEEK_API_KEY'), // 🔑 Put this in .env
                'Content-Type' => 'application/json',
            ])->timeout(420)
            ->post('https://api.deepseek.com/v1/chat/completions', [
                "model" => "deepseek-chat",
                "messages" => $chats,
                "temperature" => 1.5,
                "stream" => false
            ]);

            $markdown = $response->json()["choices"][0]["message"]["content"];
            $booking->update([
                "report_markdown" => $response->json()["choices"][0]["message"]["content"]
            ]);

            return $this->getReport($markdown);
            // $pdf = Pdf::loadView('pdf.doctor_report', compact('data'));
            // return $pdf->download('doctor_report.pdf');



    }

    function getReport($markdown) {
        $converter = new CommonMarkConverter([
            'html_input' => 'escape',
            'allow_unsafe_links' => false,
        ]);
        $html = $converter->convert($markdown)->getContent();

        // Pass HTML to the Blade view
        return Pdf::loadView('pdf.doctor_report', [
            'html' => $html
        ])
        ->setPaper('A4')
        ->download('doctor_report.pdf');
    }

    public function store(Request $request)
    {
        $request->validate([
            "name" => "string",
            "sex" => "string",
            "age" => "string",
            "gender" => "string",
            "amount" => "required|string"
        ]);
        $user = Member::where("id", auth("member")->user()->id)->first();

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

        $booking = Booking::create([
            "booking_id" => "BOOK".rand(100000, 999999).date("YmdHis"),
            "member_id" => auth("member")->user()->id,
            "amount_paid" => $request->amount,
            "amount_booked" => 1,
            "booking_start_time" => Carbon::now(),
            "booking_end_time" => Carbon::now()->addMinutes(30),
            "member_data" => json_encode($request->all())
            // "booking_status" => $request->booking_status,
        ]);

        $bookingPayment = BookingPayment::create([
            "booking_id" => $booking->booking_id,
            "payment_method" => "safehaven",
            "payment_id" => "BOOK".rand(100000, 999999).date("YmdHis").date("YmdHis"),
            "member_id" => auth("member")->user()->id,
            "payment_amount" => $request->amount,
            "payment_status" => Booking::INITALIZED
        ]);

        return response()->json([
            "message" => "Booking created successfully",
            "data" => $booking,
            "bookingPayment" => $bookingPayment,
            "price" => 100
        ], 201);
    }

    /**
     * Display the specified resource.
     */
    public function show($bookingid)
    {
        $booking = Booking::where("booking_id", $bookingid)->first();
        return response()->json([
            "message" => "Booking created successfully",
            "data" => $booking,
            "chats" => $this->getChatsBooking($bookingid),
            "price" => 100
        ], 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;
    }


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

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

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

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