<?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 . '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_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning . "faculty_api/faculty_function/common_faculty_function.php";
require_once $base_path_to_learning . "principal_api/principal_function/principal_function.php";

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

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

checkIfNoPhpContentsReceive();

if (
    !isset($postdata['institution_id']) || !checkIfIssetAndNotEmpty($postdata['institution_id']) ||
    !isset($postdata['branch_id']) || !checkIfIssetAndNotEmpty($postdata['branch_id']) ||
    !isset($postdata['date']) || !checkIfIssetAndNotEmpty($postdata['date']) ||
    !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);

if (!$jwt_validate) {
    errorreturn("Invalid JWT token.");
}

$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

$institution_id = trim($postdata['institution_id']);
$branch_id = trim($postdata['branch_id']);
$date = trim($postdata['date']);

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ["teacher", "student"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
}

$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
if (!$conn_rjllearning_specific) {
    errorreturn('Failed to connect to the specific database.');
}

$check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if (!$check_academic_confirmation) {
    errorreturn("Access denied. Academic session not active.");
}

if ($postdata['function_type'] == "chat_specific_history") {
    try {
        // Fetch AI response history
        $sql = "
            SELECT 
                id , user_id, question, answer, type, DATE(date_created) AS date,class,subject, date_created
            FROM 
                ai_responses
            WHERE 
                institution_id = ? AND branch_id = ? and date_created =?
        ";
        
        // Initialize parameters array
        $array_params = [$institution_id, $branch_id,$date];
        
        // Add condition for the role 'student'
        if ($role == 'student') {
            $sql .= " AND user_id = ?";
            $array_params[] = $userid;
        }
        
        if ($role == 'faculty') {
            $sql .= " AND user_id = ?";
            $array_params[] = $userid;
        }
        
        // Append the ORDER BY clause
        $sql .= " ORDER BY date_created DESC";
        
        $stmt = $conn_rjllearning->prepare($sql);
        $stmt->execute($array_params);
        
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

       
        if (!$results) {
            errorreturn(["message" => "No history found."]);
        }

        // Organize results into a date-wise format
        $history = [];
        foreach ($results as $row) {
            
            
            $date = $row['date'];

            // Create a new date entry if it doesn't exist
            if (!isset($history[$date])) {
                $history[$date] = [
                    "faculty" => [],
                    "students" => []
                ];
            }

            // Add responses to the appropriate type
            if ($row['type'] === 'Faculty') {
                $history[$date]['faculty'][] = [
                    "ai_id" => $row['id'],
                    "user_id" => $row['user_id'],
                    "question" => $row['question'],
                    "answer" => $row['answer'],
                    "timestamp" => $row['date_created']
                ];
            } elseif ($row['type'] === 'student') {
                 $class_info = getClass($conn_rjllearning_specific, $institution_id, $row['class']);
                 $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $row['subject']);
                $history[$date]['students'][] = [
                    "ai_id" => $row['id'],
                    "user_id" => $row['user_id'],
                    "question" => $row['question'],
                    "answer" => $row['answer'],
                    "class_info"=>$class_info,
                    'subject_info'=> $subject_info,
                    "timestamp" => $row['date_created']
                ];
            }
        }

        // Convert history array into a list ordered by date
        $ordered_history = [];
        foreach ($history as $date => $data) {
            $ordered_history[] = [
                "date" => $date,
                "faculty" => array_reverse($data['faculty']), // Reverse for oldest first in the day
                "students" => array_reverse($data['students']) // Reverse for oldest first in the day
            ];
        }
        
        // Return the ordered history
        successreturn(["history" => $ordered_history]);
    } catch (Exception $e) {
        errorreturn("Error fetching history: " . $e->getMessage());
    }
} else {
    errorreturn("Invalid function type.");
}
?>
