<?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';


use GeminiAPI\Client;
use GeminiAPI\Resources\Parts\TextPart;

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['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 = isset($postdata['institution_id']) ? trim($postdata['institution_id']) : null;
$branch_id = isset($postdata['branch_id']) ? trim($postdata['branch_id']) : null;

if (isset($postdata['search_string']) and !empty($postdata['search_string'])) {
    $search_string = trim($postdata['search_string']);
} else {
    $search_string = null;
}




$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ["superadmin","admin","principal","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.');
}



if ($postdata['function_type'] == "chat_history") {
    try {
        // Start building the SQL query
       // Initialize parameters array
       $array_params = [];

        // Step 1: Base SQL Query
        $sql = "
            SELECT 
                id, user_id, question, answer, type, time_created, DATE(date_created) AS date, class, subject, date_created
            FROM 
                ai_responses
            WHERE user_id = ? and status = 1
        ";
        $array_params[] = $userid;
        
        // // Apply institution_id condition
        // if (in_array($role, ['admin', 'superadmin'])) {
        //     $sql .= " AND (institution_id = ? OR institution_id IS NULL)";
        //     $array_params[] = $institution_id;
        // } else {
        //     $sql .= " AND institution_id = ?";
        //     $array_params[] = $institution_id;
        // }
        
        // Apply branch_id condition
        // if (in_array($role, ['admin', 'superadmin'])) {
        //     $sql .= " AND (branch_id = ? OR branch_id IS NULL)";
        //     $array_params[] = $branch_id;
        // } else {
        //     $sql .= " AND branch_id = ?";
        //     $array_params[] = $branch_id;
        // }
        
        // // Add role-based filtering
        // if ($role == 'student') {
        //     $sql .= " AND type = 'student'";
        // } elseif ($role == 'teacher') {
        //     $sql .= " AND type = 'teacher'";
        // } elseif ($role == 'principal') {
        //     $sql .= " AND type = 'principal'";
        // } elseif (in_array($role, ['admin', 'superadmin'])) {
        //     $sql .= " AND (type = 'admin' OR type = 'superadmin')";
        // }
        
        // Apply search filter
        if (!empty($search_string)) {
            $sql .= " AND (question LIKE ? OR answer LIKE ?)";
            $array_params[] = "%$search_string%";
            $array_params[] = "%$search_string%";
        }
        
        // Step 2: Count SQL Query
        $count_sql = "SELECT COUNT(*) AS total_rows FROM ai_responses WHERE user_id = ? and status =1";
        $count_params = [$userid];
        
        // if (in_array($role, ['admin', 'superadmin'])) {
        //     $count_sql .= " AND (institution_id = ? OR institution_id IS NULL)";
        //     $count_params[] = $institution_id;
        // } else {
        //     $count_sql .= " AND institution_id = ?";
        //     $count_params[] = $institution_id;
        // }
        
        // if (in_array($role, ['admin', 'superadmin'])) {
        //     $count_sql .= " AND (branch_id = ? OR branch_id IS NULL)";
        //     $count_params[] = $branch_id;
        // } else {
        //     $count_sql .= " AND branch_id = ?";
        //     $count_params[] = $branch_id;
        // }
        
        // Apply search filter in count query
        if (!empty($search_string)) {
            $count_sql .= " AND (question LIKE ? OR answer LIKE ?)";
            $count_params[] = "%$search_string%";
            $count_params[] = "%$search_string%";
        }
        
        // Execute the count query
        $count_stmt = $conn_rjllearning->prepare($count_sql);
        $count_stmt->execute($count_params);
        $total_rows = $count_stmt->fetch(PDO::FETCH_ASSOC)['total_rows'];
        
        // Step 3: Paginate the main query
        $sql .= " ORDER BY id DESC";
        
        $limit = isset($postdata['limit']) ? $postdata['limit'] : 'all';
        $page = (isset($postdata['page']) && is_numeric($postdata['page'])) ? (int)$postdata['page'] : 1;
        
        if ($limit != 'all' && is_numeric($limit)) {
            $limit = (int)$limit;
            $offset = ($page - 1) * $limit;
            $sql .= " LIMIT " . $offset . ", " . $limit;
        }
        
        // Prepare and execute the main query
        $stmt = $conn_rjllearning->prepare($sql);
        $stmt->execute($array_params);
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
                

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

        // Organize the results
        $ordered_history = [];
        foreach ($results as $row) {
            
            
            
            $parts = explode("Question: ", $row['question']);
            $question = isset($parts[1]) ? trim(explode(",", $parts[1])[0]) : '';
            $entry = [
                "ai_id" => $row['id'],
                "user_id" => $row['user_id'],
                "question_asked" => $row['question'],   
                "answer" => $row['answer'],
                "date" => $row['date_created'],
                "time" => $row['time_created']
            ];

            // If role is student, add class info
            if ($role == 'student') {
                $entry["class_info"] = getClass($conn_rjllearning_specific, $institution_id, $row['class']);
            }

            $ordered_history[] = $entry;
        }

        // **STEP 3: Return data with total rows**
        successreturn([
            "total_rows" => $total_rows,
            "history" => $ordered_history
        ]);

    } catch (Exception $e) {
        errorreturn(["message" => "Error fetching history: " . $e->getMessage()]);
    }
}



?>
