<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LiveChatGptController extends Controller
{



    public function msg(Request $request)
    {

        // Default response
        $status = 'error';
        $result = null;

        // Getting the response from GPT
        // $response = $this->chatGPT($request);
        if(setting('GPT_PROVIDER') == 1){
            $ollama = $this->ollama($request)->getData()->message->content;
            $result = Str::markdown($ollama);
            $status = 'success';
        } elseif(setting('GPT_PROVIDER') == 2){
            // $response = $this->chatGPT($request);
            // $result = Str::markdown($response['choices'][0]['message']['content']);
            // $status = 'success';
        }


        if($result == null){
            $status = 'error';
            $result = "Sorry, I didn't get that. Can you please rephrase?";
        }

        return response()->json([
            'status' => $status ?? 'success',
            'message' => $result ?? 'Sorry, I didn\'t get that. Can you please rephrase?'
        ], $status == 'error' ? 400 : 200);

    }


    // Ollama API
    public function ollama($request){

        $url = setting('OLLAMA_API') ?? 'http://localhost:11434/api/chat';


        $data = [
            "model" => setting('OLLAMA_MODEL') ?? 'llama3.2:3b',
            "messages" => [
                [
                    "role" => "user",
                    "content" => $request->msg ?? "Hello there!, who are you?"
                ]
            ],
            "stream" => false
        ];

        $data = json_encode($data);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
        ]);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($result, true);





        return response()->json($result);
    }


    // Chat GPT API
    public static function chatGPT($request){
        // Retrieve the user's message
        $userMessage = $request->input('msg');

        // Fetch some product data for context (example: fetching product names)
        $products = Product::select(
                'id',
                'slug',
                'title',
                'status',
                'quantity',
                'regular_price',
                'discount_price',
                'shipping_charge',
                'dedicated_shipping_charge',
                'short_description',
                'full_description',
                'image',
                'updated_at',
            )->get();
            
        $productNames = $products->pluck('title')->implode(', ');

        // Prepare the messages for GPT including product data
        $messages = [
            [
                "role" => "system",
                "content" => "You are a helpful assistant."
            ],
            [
                "role" => "user",
                "content" => "User message: " . $userMessage . "\nAvailable products: " . $productNames
            ]
        ];

        // Set up the GPT API request
        $url = "https://api.openai.com/v1/chat/completions";
        $data = [
            "model" => "gpt-3.5-turbo",
            "messages" => $messages,
            "max_tokens" => 100,
            "temperature" => 0.5,
            "top_p" => 1,
            "frequency_penalty" => 0,
            "presence_penalty" => 0
        ];
        $data = json_encode($data);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . setting('chatGPT_api_key') ?? "",
            'Content-Type: application/json',
        ]);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($result, true);



        // Return the GPT response
        return $result;
    }
}