<?php
ini_set('display_errors', 1);

require_once '../../../resources/base_path_include.php';
require_once $base_path_to_learning_resources . "includes/connect.php"; 
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';
require_once $base_path_to_learning_resources ."includes/ai_config.php";

require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';

use GeminiAPI\Client;
use GeminiAPI\Resources\ModelName;
use GeminiAPI\Resources\Parts\TextPart;
use GuzzleHttp\Client as GuzzleClient;

$postdata = json_decode(file_get_contents("php://input"), true);

checkIfNoPhpContentsReceive();

if (
    // !isset($postdata['institution_id']) || !checkIfIssetAndNotEmpty($postdata['institution_id']) || 
    !isset($postdata['question']) || !checkIfIssetAndNotEmpty($postdata['question']) || 
    !isset($postdata['api_signature']) || !checkIfIssetAndNotEmpty($postdata['api_signature']) || 
    !isset($postdata['function_type']) || !checkIfIssetAndNotEmpty($postdata['function_type']) || 
    !isset($postdata['jwt_token']) || !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

$institution_id = isset($postdata['institution_id']) ? trim($postdata['institution_id']) : null;
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ["superadmin","admin","principal","teacher", "student"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
   

$branch_id = isset($postdata['branch_id']) ? trim($postdata['branch_id']) : null;

if ($role == 'student') {
    // Fetch student details like dob, class, and section
    $Student_Query = $conn_rjllearning_specific->prepare("SELECT dob, class_id, section_id FROM students WHERE user_id = ? AND institution_id = ? AND branch_id = ?");
    $Student_Query->execute([$userid, $institution_id, $branch_id]);

    $result_student = $Student_Query->fetch(PDO::FETCH_ASSOC);
    if ($result_student === false) {
        errorreturn("Student Not Found.");
    }

    // Calculate age from DOB (assuming dob is stored in 'YYYY-MM-DD' format)
    $dob = $result_student['dob'];
    $dob_date = new DateTime($dob);
    $current_date = new DateTime();
    $interval = $dob_date->diff($current_date);
    $age = $interval->y; // Full years

    $class_id = $result_student['class_id'];
    $section_id = $result_student['section_id'];

    // Assign class based on age
    if ($age >= 3 && $age <= 8) {
        $class = 'Primary';
        $question_limit = 10;
        $answer_limit = 20;
    } elseif ($age >= 9 && $age <= 14) {
        $class = 'Middle School';
        $question_limit = 20;
        $answer_limit = 35;
    } elseif ($age >= 15 && $age <= 17) {
        $class = 'High School';
        $question_limit = 35;
        $answer_limit = 100;
    } elseif ($age >= 17 && $age <= 19) {
        $class = 'Senior High School';
        $question_limit = 750;
        $answer_limit = 150;
    } else {
        $class = 'Adult';
        $question_limit = 100;
        $answer_limit = 250;
    }

} elseif ($role == 'teacher') {
    // teacher has different token limits
    $class = 'teacher';
    $class_id =null;
    $question_limit = 100;
    $answer_limit = 250;

} elseif ($role == 'principal') {
    // teacher has different token limits
    $class = 'principal';
    $class_id =null;
    $question_limit = 100;
    $answer_limit = 250;

}elseif ($role == 'admin' || $role == 'superadmin') {
    // teacher has different token limits
    $class = $role;
    $class_id = null;
    $question_limit = 150;
    $answer_limit = 300;
}else {
    errorreturn("Invalid role.");
}

$users_Query = $conn_rjllearning->prepare("SELECT dob FROM users WHERE id = ? ");
$users_Query->execute([$userid]);

$result_users = $users_Query->fetch(PDO::FETCH_ASSOC);
if ($result_users === false) {
    errorreturn("user Not Found.");
}

// Check role before calculating age
$age = null;  // Default to null, won't be calculated unless role is principal or teacher
if (in_array($role, ['principal', 'teacher','admin', 'superadmin'])) {
    $dob = $result_users['dob'];
    if (!empty($dob)) {
        $dob_date = new DateTime($dob);
        $current_date = new DateTime();
        $interval = $dob_date->diff($current_date);
        $age = $interval->y; // Full years
    }
}

if ($postdata['function_type'] == "chat_fetch") {
    $question = isset($postdata['question']) ? $postdata['question'] : '';
    $subject = isset($postdata['subject_id']) ? $postdata['subject_id'] : null;

    // if ($role == 'student' && $subject == null) {
    //     errorreturn("Subject ID is required for students.");
    // }
    $question_tokens = str_word_count($question); // Approximate token count using word count
    if ($question_tokens > $question_limit) {
        errorreturn("Question exceeds the allowed token limit of $question_limit.");
    }
    // Correct approach: passing the string API key
    $gemini_api_key = $GEMINI_API_KEY;
    $client = new Client($gemini_api_key);

    $academic_prompt = "Determine if the following question is related to an academic topic, and is appropriate for a student of age: $age and class: $class. Answer with 'yes' or 'no' only. Question: $question";

    // Set the max tokens for the response
    $max_tokens = $answer_limit;
 
    try {
        $textPart = new TextPart($academic_prompt);
        $response = $client->generativeModel('gemini-2.0-flash')->generateContent($textPart);
        $academic_check = strtolower(trim($response->text()));

        if ($academic_check == "yes") {
            $age_check_prompt = "Is the following topic and question appropriate for a student of age: $age and class: $class, considering that the topic could not involve sensitive information or concepts that are not developmentally suitable for children? Answer with 'yes' or 'no' only. Topic: " . $question;
            $age_check_textPart = new TextPart($age_check_prompt);
            $age_check_response = $client->generativeModel('gemini-2.0-flash')->generateContent($age_check_textPart);
            $age_check_result = strtolower(trim($age_check_response->text()));

            if ($age_check_result != "yes") {
                errorreturn("The topic is not suitable for your age and class.");
            }
            
            $academic_prompt = "Respond to the following academic question within the given token limit, and ensure the response is appropriate for a student of age: $age and class: $class. Age: $age, Class: $class, 
            Question: $question, Answer Limit: {$answer_limit} tokens. Ensure the answer is strictly related to the educational context, and avoid sensitive or inappropriate topics for young children.";
            $textPart = new TextPart($academic_prompt);
            $response = $client->generativeModel('gemini-2.0-flash')->generateContent($textPart);
            $answer = $response->text();
            
            // Check response appropriateness using Gemini API.
            $check_prompt = "Is the following response appropriate for a student of age: $age and class: $class considering their developmental stage? Answer with 'yes' or 'no' only. Response: $answer";
            // $check_prompt = "Is the following response appropriate for a student of age: $age and class: $class? Answer with 'yes' or 'no' only. Response: $answer";
            $check_textPart = new TextPart($check_prompt);
            $check_response = $client->generativeModel('gemini-2.0-flash')->generateContent($check_textPart);
            $appropriateness_check = strtolower(trim($check_response->text()));

            if ($appropriateness_check != "yes") {
                errorreturn("The topic is not suitable for your age and class.");
            }

            $status = '1';
            $date_created = date('Y-m-d');
            $time_created = time();

            $sql = "INSERT INTO ai_responses (workspace_id, institution_id, branch_id, user_id, question, answer, date_created, time_created, status, age, class, subject, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $conn_rjllearning->prepare($sql);

            $result = $stmt->execute([$workspace_id, $institution_id, $branch_id, $userid, $question, $answer, $date_created, $time_created, $status, $age, $class_id, $subject, $role]);

            if ($result) {
                successreturn(["answer" => $answer]);
            } else {
                errorreturn("Error while storing data.");
            }

        } else if ($academic_check == "no") {
            // Question is not academic.
            errorreturn("Please ask questions only related to academic topics.");
        } else {
            // Gemini returned an unexpected response.
            errorreturn("Unable to determine question's academic relevance. Please try again.");
        }
    } catch (Exception $e) {
        errorreturn("Gemini API error: " . $e->getMessage());
    }
}

?>
