<?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 . "user_management/functions/functions.php";
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
// require_once $base_path_to_learning . 'admin_api/modules/activity_mentor/activity_functions.php';

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

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

$required_fields = ['api_signature', 'function_type', 'jwt_token'];
foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("All * fields are required.");
    }
}

validateApiSignature($postdata['api_signature']);

// Authenticate and validate the JWT token
$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 = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;
$class_id = $jwt_validate->data->class;
$section_id = $jwt_validate->data->section;
// Validate user access to a specific database
$specific_db_name = validateStudentAcess($conn_rjllearning, $role, $workspace_id, ["student"], null, null, $userid);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
validateStudentClassSection($conn_rjllearning_specific, $userid, $institution_id, $branch_id, $class_id, $section_id);


$academicSessionId = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if (!$academicSessionId) {
    errorreturn("Invalid institution_id");
}

// $isBranchClassSubjectValid = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, null, null, $institution_id);
// if (!$isBranchClassSubjectValid) {
//     errorreturn("Invalid branch_id.");
// }

function getActivity_details($conn_rjllearning_specific, $institution_id, $branch_id, $search_string, $class_id, $section_id, $userid)
{
    $currentDate = date('Y-m-d');
    $currentTime = date('H:i:s');

    // Query to fetch the featured image
$query = "
   SELECT title, description, attachment, tags 
    FROM activity_mentor 
    WHERE featured_bool = 1 
    AND (
        publish_date < :current_date 
        OR (publish_date = :current_date AND publish_time <= :current_time)
    )
    AND (
        termination_date IS NULL 
        OR termination_date > :current_date 
        OR (termination_date = :current_date AND termination_time >= :current_time)
    )
";

// Initialize parameters array
$array_params = [
    ':current_date' => $currentDate,
    ':current_time' => $currentTime
];

// Add conditional filters dynamically using named parameters
if (!empty($branch_id)) {
    $query .= " AND (branch_id LIKE :branch_id OR branch_id = 'all')";
    $array_params[':branch_id'] = '%' . $branch_id . '%';  // Named parameter for branch_id
}

if (!empty($class_id)) {
    $query .= " AND (class_id LIKE :class_id OR class_id = 'all')";
    $array_params[':class_id'] = '%' . $class_id . '%';  // Named parameter for class_id
}

if (!empty($section_id)) {
    $query .= " AND (section_id LIKE :section_id OR section_id = 'all')";
    $array_params[':section_id'] = '%' . $section_id . '%';  // Named parameter for section_id
}

if (!empty($userid)) {
    $query .= " AND (student_id LIKE :student_id OR student_id ='all')";
    $array_params[':student_id'] = '%' . $userid . '%';  // Named parameter for section_id
}



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

// Fetch the results
$session_rows = $stmt->fetchAll();

    $array_return = [];

    foreach ($session_rows as $rows) {
        
        $data_to_send = [];

        // Check if the attachment exists and is valid
        if (!empty($rows['attachment'])) {
            $data_attachment = json_decode($rows['attachment'], true);
            if (is_array($data_attachment)) {
                foreach ($data_attachment as $attachment) {
                    if (isset($attachment['filepath']) && isset($attachment['original_name'])) {
                        $filepath = $attachment['filepath'];
                        $originalname = $attachment['original_name'];

                        $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filepath);

                        $final_array_attachment = array(
                            "filepath" => $aws_attachment,
                            "original_name" => $originalname
                        );

                        $data_to_send[] = $final_array_attachment;
                    }
                }
            } else {
                if (isset($data_attachment['filepath']) && isset($data_attachment['original_name'])) {
                    $filepath = $data_attachment['filepath'];
                    $originalname = $data_attachment['original_name'];

                    $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filepath);

                    $final_array_attachment = array(
                        "filepath" => $aws_attachment,
                        "original_name" => $originalname
                    );

                    $data_to_send[] = $final_array_attachment;
                }
            }
        }

        if (empty($data_to_send)) {
            $data_to_send[] = array();
        }
        
//          $branch = [];
// // $section_info = [];
// $class_info = [];
// $student_info = [];



// // Handle branch_id
// $branch_id = $rows['branch_id'];

// $branch = []; // Initialize branch array

// // Decode branch_id if it's a JSON-encoded string
// $branch_ids_array = json_decode($branch_id, true);

// // Check if branch_id is 'all'
// if ($branch_id == 'all' || (is_array($branch_ids_array) && in_array('all', $branch_ids_array))) {
//     // If branch_id is 'all', return an entry for 'All branches'
//     $branch[] = array('branch_id' => 'all', 'branch_name' => 'All branches');

// } else {
//     // If branch_id is not 'all', ensure it's an array
//     if (!empty($branch_ids_array) && is_array($branch_ids_array)) {
//         // Implode the array into a comma-separated string
//         $imploded_branch_ids = implode(',', array_map('intval', $branch_ids_array)); // Convert to integers for safety

//         $sql = "SELECT * FROM branch WHERE institution_id = ? AND id IN ($imploded_branch_ids)";
//         $stmt = $conn_rjllearning_specific->prepare($sql);
//         $stmt->execute([$institution_id]); // Execute query with institution_id
//         $branch_rows = $stmt->fetchAll();

//         foreach ($branch_rows as $branch_data) {
//             $branch[] = array('branch_id' => $branch_data['id'], 'branch_name' => $branch_data['name']);
//         }
//     }
// }


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

// $section = []; // Initialize section array

// // Decode section_id in case it's a JSON-encoded string
// $section_ids_array = json_decode($section_id, true);

// // Check if section_id is 'all'
// if ($section_id == 'all' || (is_array($section_ids_array) && in_array('all', $section_ids_array))) {
//     // If section_id is 'all', return it as the section
//     $section[] = array('section_id' => 'all', 'section_name' => 'All Sections');
// } else {
//     // If section_id is not 'all', ensure it's an array
//     if (!empty($section_ids_array) && is_array($section_ids_array)) {
//         // Implode the array into a comma-separated string
//         $imploded_section_ids = implode(',', array_map('intval', $section_ids_array)); // Convert to integers for safety

//         $sql = "SELECT * FROM section_info WHERE institution_id = ? AND id IN ($imploded_section_ids)";
//         $array_params = [$institution_id]; // Add institution_id to parameters
//         $stmt = $conn_rjllearning_specific->prepare($sql);
//         $stmt->execute($array_params);
//         $section_rows = $stmt->fetchAll();

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



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

// $class_info = []; // Initialize class array

// // Decode class_id in case it's a JSON-encoded string
// $class_ids_array = json_decode($class_id, true);

// // Check if class_id is 'all'
// if ($class_id == 'all' || (is_array($class_ids_array) && in_array('all', $class_ids_array))) {
//     // If class_id is 'all', fetch all classes
//     // $sql = "SELECT * FROM class_info WHERE institution_id = ?";
//     // $stmt = $conn_rjllearning_specific->prepare($sql);
//     // $stmt->execute([$institution_id]);
//     // $class_rows = $stmt->fetchAll();

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

//     // Add an entry for 'all' classes
//     $class_info[] = array('class_id' => 'all', 'class_name' => 'All Classes');
// } else {
//     // If class_id is not 'all', ensure it's an array
//     if (!empty($class_ids_array) && is_array($class_ids_array)) {
//         // Implode the array into a comma-separated string
//         $imploded_class_ids = implode(',', array_map('intval', $class_ids_array)); // Convert to integers for safety

//         $sql = "SELECT * FROM class_info WHERE institution_id = ? AND id IN ($imploded_class_ids)";
//         $array_params = [$institution_id]; // Add institution_id to parameters
//         $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 branch_id, section_id, class_id, and student_id processing (similar to your existing logic)

        $array_return[] = array(
            // 'activity_id' => $rows['id'],
            // 'branch_id' => $branch,
            // 'class_info' => $class_info,
            // 'section_info' => $section,
            // 'student_info' => $student_info,
            // 'type' => $rows['type'],
            'tags' => json_decode($rows['tags'], true),
            'title' => $rows['title'],
            'description' => $rows['description'],
            'activity_attachment' => $data_to_send,
            // 'publish_date' => $rows['publish_date'],
            // 'publish_time' => $rows['publish_time'],
            // 'termination_date' => $rows['termination_date'],
            // 'termination_time' => $rows['termination_time'],
            // 'created_by' => $rows['created_by'],
            // 'date_created' => $rows['date_created'],
            // 'time_created' => $rows['time_created'],
            // 'status' => $rows['status']
        );
    }

    if (count($session_rows) < 50) {
        return array( 'activity_info' => $array_return, 'maxreach' => 1);
    } else {
        return array( 'activity_info' => $array_return, 'maxreach' => 0);
    }
}


if ($postdata['function_type'] == "fetch_featured_activity") {


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

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



  
        $success['data'] = getActivity_details($conn_rjllearning_specific, $institution_id, $branch_id, $search_string, $class_id, $section_id, $userid);
        successreturn($success);
   
}
