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

require_once '../../../resources/base_path_include.php';

require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

//valdation file
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';
//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
//aws image store
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 Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
$postdata = json_decode(file_get_contents("php://input"), true);

checkIfNoPhpContentsReceive();


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

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
//then workspace_id is iin decodede data of jwt use from there
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;

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

require_once $base_path_to_learning . 'user_management/user_versioning.php';

$version = isset($_POST['version']) ? $_POST['version'] : (isset($postdata['version']) ? $postdata['version'] : null);
$updated_time = isset($_POST['updated_time']) ? $_POST['updated_time'] : (isset($postdata['updated_time']) ? $postdata['updated_time'] : null);

$response = user_data_refresh($conn_rjllearning, $conn_rjllearning_specific, $version, $updated_time, $userid, $institution_id);


function getSpecificlesson($conn_rjllearning_specific,$institution_id,$activity_mentor_id) {
    
    $sql = $conn_rjllearning_specific->prepare("SELECT * FROM  activity_mentor where id = ? and institution_id =?");
    $sql->execute(array($activity_mentor_id,$institution_id));
    $rows = $sql->fetchAll();

   
    if (count($rows) == 1) {
        
         $final_array_attachment = array(); // Initialize the array to store attachments

// Check if the attachment exists and is valid
if (!empty($rows[0]['attachment'])) {
    // Decode the attachment data
    $data_attachment = json_decode($rows[0]['attachment'], true);
    
    // Check if the decoded data is an array (for multiple attachments)
    if (is_array($data_attachment)) {
        foreach ($data_attachment as $attachment) {
            // Ensure the required keys exist in each attachment
            if (isset($attachment['filepath']) && isset($attachment['original_name'])) {
                $filePath = $attachment['filepath'];
                $originalName = $attachment['original_name'];

                // Fetch the AWS attachment URL
                $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);

                // Prepare the attachment array
                $final_array_attachment[] = array(
                    "filepath" => $aws_attachment,
                    "original_name" => $originalName
                );
            }
        }
    } else {
        // If it's a single attachment
        if (isset($data_attachment['filepath']) && isset($data_attachment['original_name'])) {
            $filePath = $data_attachment['filepath'];
            $originalName = $data_attachment['original_name'];

            // Fetch the AWS attachment URL
            $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);

            // Prepare the attachment array
            $final_array_attachment[] = array(
                "filepath" => $aws_attachment,
                "original_name" => $originalName
            );
        }
    }
} else {
    // No attachments found, set to null or an empty array as required
    $final_array_attachment = null; // or you can use array() to initialize it as an empty array
}

// Now, $final_array_attachment will contain either the attachments or be null if none were found.

        
        // $class_info = getClass($conn_rjllearning_specific, $institution_id, $rows[0]['class_id']);
       
        // $branch = getBranchInfo($conn_rjllearning_specific, $institution_id, $rows[0]['branch_id']);
        

$branch = []; // Initialize branches array
$branch_id = $rows[0]['branch_id'];

// Ensure $branch_id is an array or valid JSON
if (is_string($branch_id)) {
    $decoded_branch_id = json_decode($branch_id, true); // Attempt to decode JSON string
    $branch_id = $decoded_branch_id !== null ? $decoded_branch_id : $branch_id; // Use decoded value if valid
}

// Handle "all" case for branch_id
if ($branch_id === 'all') {
    $branch[] = array('branch_id' => $branch_id, 'name' => ucwords($branch_id));
} else {
    // Ensure $branch_id is treated as an array
    $branch_id_array = is_array($branch_id) ? $branch_id : [$branch_id];

    // Prepare the query with placeholders for safety
    $placeholders = rtrim(str_repeat('?,', count($branch_id_array)), ',');
    $sql = "SELECT id, name FROM branch WHERE institution_id = ? AND id IN ($placeholders)";
    $stmt = $conn_rjllearning_specific->prepare($sql);

    // Merge institution_id with branch IDs for parameter binding
    $params = array_merge([$institution_id], $branch_id_array);
    $stmt->execute($params);

    $section_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Append each valid branch to the $branch array
    foreach ($section_rows as $section_data) {
        $branch[] = array('branch_id' => $section_data['id'], 'name' => ucwords($section_data['name']));
    }
}

$section_info = [];
$class_info = [];
$student_info = [];

// Handle section_id
$section_id = $rows[0]['section_id'];

// Check if section_id is an array or needs to be converted
if ($section_id == 'all') {
    $section_info[] = array('section_id' => $section_id, 'section_name' => ucwords($section_id));
} else {
    // Ensure $section_id is an array
    if (is_string($section_id)) {
        $section_id = json_decode($section_id, true); // Decode if it's a JSON string
    }

    // Check if $section_id is an array
    if (is_array($section_id)) {
        $placeholders = implode(',', array_fill(0, count($section_id), '?')); // Create placeholders
        $sql = "SELECT * FROM section_info WHERE institution_id = ? AND id IN ($placeholders)";
        $array_params = array_merge([$institution_id], $section_id); // Merge institution_id with section_ids
    } else {
        // Handle case where $section_id is not an array and not 'all'
        $sql = "SELECT * FROM section_info WHERE institution_id = ? AND id = ?";
        $array_params = [$institution_id, $section_id];
    }

    // Prepare and execute the SQL query
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $section_rows = $stmt->fetchAll();

    foreach ($section_rows as $section_data) {
        $section_info[] = array('section_id' => $section_data['id'], 'section_name' => $section_data['section_name']);
    }
}

// Handle class_id
$class_id = $rows[0]['class_id'];

// Check if class_id is an array or needs to be converted
if ($class_id == 'all') {
    $class_info[] = array('class_id' => $class_id, 'class_name' => ucwords($class_id));
} else {
    // Ensure $class_id is an array
    if (is_string($class_id)) {
        $class_id = json_decode($class_id, true); // Decode if it's a JSON string
    }

    // Check if $class_id is an array
    if (is_array($class_id)) {
        $placeholders = implode(',', array_fill(0, count($class_id), '?')); // Create placeholders
        $sql = "SELECT * FROM class_info WHERE institution_id = ? AND id IN ($placeholders)";
        $array_params = array_merge([$institution_id], $class_id); // Merge institution_id with class_ids
    } else {
        // Handle case where $class_id is not an array and not 'all'
        $sql = "SELECT * FROM class_info WHERE institution_id = ? AND id = ?";
        $array_params = [$institution_id, $class_id];
    }

    // Prepare and execute the SQL query
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $class_rows = $stmt->fetchAll();

    foreach ($class_rows as $class_data) {
        $class_info[] = array('class_id' => $class_data['id'], 'class_name' => $class_data['classname']);
    }
}

// Handle student_id
$student_id = $rows[0]['student_id'];

// Check if student_id is an array or needs to be converted
if ($student_id == 'all') {
    $student_info[] = array('student_id' => $student_id, 'student_name' => ucwords($student_id));
} else {
    // Ensure $student_id is an array
    if (is_string($student_id)) {
        $student_id = json_decode($student_id, true); // Decode if it's a JSON string
    }

    // Check if $student_id is an array
    if (is_array($student_id)) {
        $placeholders = implode(',', array_fill(0, count($student_id), '?')); // Create placeholders
        $sql = "SELECT * FROM students WHERE institution_id = ? AND user_id IN ($placeholders)";
        $array_params = array_merge([$institution_id], $student_id); // Merge institution_id with student_ids
    } else {
        // Handle case where $student_id is not an array and not 'all'
        $sql = "SELECT * FROM students WHERE institution_id = ? AND user_id = ?";
        $array_params = [$institution_id, $student_id];
    }

    // Prepare and execute the SQL query
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $student_rows = $stmt->fetchAll();

    foreach ($student_rows as $student_data) {
        $student_info[] = array('student_id' => $student_data['user_id'], 'student_name' => $student_data['name']);
    }
}


     
        return array('activity_mentor_id'=> $rows[0]['id'],
        'branch_id'=>$branch ,
        'class_id'=> $class_info,
        'section_id'=> $section_info,
        'student_id'=> $student_info,
        'publish_date' => $rows[0]['publish_date'],
        'publish_time' => $rows[0]['publish_time'],
        'termination_date' => $rows[0]['termination_date'],
        'termination_time' => $rows[0]['termination_time'],
        'tags' => json_decode($rows[0]['tags'],true),
        'title' => $rows[0]['title'],
        'featured_bool' => $rows[0]['featured_bool'],
        'description' => $rows[0]['description'],
        'type' => $rows[0]['type'],
        'attachment' => $final_array_attachment);
      
    }else{
          errorreturn("Enter Invalid lesson info.");
    }

}

if($postdata['function_type']  == "fetch_specific_activity_mentor") {  
    
    $activity_mentor_id = trim($postdata['activity_mentor_id']);
    // $institution_id = trim($postdata['institution_id']);    
    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific,$institution_id);
    if($check_academic_confirmation != true){
         errorreturn("Access denied. Academic session not active.");
    }
    $success['data'] = getSpecificlesson($conn_rjllearning_specific,$institution_id,$activity_mentor_id);
    successreturn($success);
      
}

