<?php

namespace App\Controllers;

use App\Models\Gpt_connection as GptConnectionModel;
use Tectalic\OpenAi\Manager as OpenAiManager;
use GuzzleHttp\Client as GuzzleClient;

class Gpt_connection extends BaseController
{
    public function index()
    {
        return view('gpt_connection/index', $this->data + [
            'page' => 'gpt',
        ]);
    }

    public function submit()
    {
        // Load the model
        $model = new GptConnectionModel();

        // Validate the request
        $validation = $this->validate([
            'do_this' => 'required',
            'to_this' => 'required',
        ]);

        if (!$validation) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        // Collect the data to insert
        $data = [
            'user_id' => session()->get('user_id'), // Assuming you have user_id in the session
            'do_this' => $this->request->getPost('do_this'),
            'to_this' => $this->request->getPost('to_this'),
            'gpt_response' => '', // GPT response to be filled later
        ];

        // Insert data into the database
        $model->save($data);

        // Get the last inserted ID
        $insertedId = $model->getInsertID();

        // Fetch the newly inserted row
        $newData = $model->find($insertedId);

        if ($newData) {
            // Concatenate `do_this` and `to_this`
            $dataToSend = $newData['do_this'] . "\n" . $newData['to_this'];

            // Send the concatenated data to GPT for a response
            $response = $this->sendToGPT($dataToSend);

            // Update the row with the GPT response
            $model->update($insertedId, ['gpt_response' => $response]);
        }

        // Set a success message
        return redirect()->back()->with('success', 'Data submitted successfully with GPT response.');
    }

    private function sendToGPT($dataToSend)
    {
        // Build the OpenAI client
        $openaiClient = OpenAiManager::build(new GuzzleClient(), new \Tectalic\OpenAi\Authentication('YOUR_OPENAI_API_KEY'));

        try {
            // Send data to OpenAI
            $apiResponse = $openaiClient->chatCompletions()->create(
                new \Tectalic\OpenAi\Models\ChatCompletions\CreateRequest([
                    'model' => 'o1-preview',
                    'messages' => [
                        [
                            'role' => 'user',
                            'content' => $dataToSend
                        ],
                    ],
                ])
            )->toModel();

            // Return the response from GPT
            return $apiResponse->choices[0]->message->content;
        } catch (\Exception $e) {
            // Log or handle the exception as needed
            return 'Error communicating with GPT: ' . $e->getMessage();
        }
    }
}
