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

$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);



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

function getActivity_details($conn_rjllearning_specific, $institution_id, $student_id, $branch_id, $search_string, $userid, $class_id, $section_id, $from_date, $to_date, $limit, $offset) 
{
    // Count total rows without student-specific filtering
    $sql = "SELECT count(*) as total_rows FROM activity_mentor WHERE institution_id = ?";
    $array_params = [$institution_id];

    if (!empty($search_string)) {
        $sql .= " AND (type LIKE ? OR title LIKE ? OR description LIKE ?)";
        $search_term = '%' . $search_string . '%';
        array_push($array_params, $search_term, $search_term, $search_term);
    }

    if (!empty($branch_id)) {
        $sql .= " AND (branch_id LIKE ? OR branch_id = 'all')";
        $array_params[] = '%"' . $branch_id . '"%';
    }

    if (!empty($class_id)) {
        $sql .= " AND (class_id LIKE ? OR class_id = 'all')";
        $array_params[] = '%"' . $class_id . '"%';
    }

    if (!empty($section_id)) {
        $sql .= " AND (section_id LIKE ? OR section_id = 'all')";
        $array_params[] = '%"' . $section_id . '"%';
    }

    if ($from_date != null && $to_date != null) {
        $sql .= " AND date_created BETWEEN ? AND ?";
        array_push($array_params, $from_date, $to_date);
    }

    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $result_total = $stmt->fetchAll();
    $totalrows = $result_total[0]['total_rows'];

    // Main query to get activity details
    $sql_query = "SELECT * FROM activity_mentor WHERE institution_id = ?";
    $array_params = [$institution_id];

    // Add the same conditions as above
    if (!empty($search_string)) {
        $sql_query .= " AND (type LIKE ? OR title LIKE ? OR description LIKE ?)";
        $search_term = '%' . $search_string . '%';
        array_push($array_params, $search_term, $search_term, $search_term);
    }

    if (!empty($branch_id)) {
        $sql_query .= " AND (branch_id LIKE ? OR branch_id = 'all')";
        $array_params[] = '%"' . $branch_id . '"%';
    }

    if (!empty($class_id)) {
        $sql_query .= " AND (class_id LIKE ? OR class_id = 'all')";
        $array_params[] = '%"' . $class_id . '"%';
    }

    if (!empty($section_id)) {
        $sql_query .= " AND (section_id LIKE ? OR section_id = 'all')";
        $array_params[] = '%"' . $section_id . '"%';
    }

    if ($from_date != null && $to_date != null) {
        $sql_query .= " AND date_created BETWEEN ? AND ?";
        array_push($array_params, $from_date, $to_date);
    }

    // Order and limit
    $sql_query .= " ORDER BY publish_date DESC, publish_time DESC";
    
    if ($limit !== 'all') {
        $sql_query .= " LIMIT " . $offset . " ," . $limit;
    }

    $stmt = $conn_rjllearning_specific->prepare($sql_query);
    $stmt->execute($array_params);
    $session_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $array_return = [];

    foreach ($session_rows as $rows) {
        $data_to_send = [];
        
        // Process attachments
        if (!empty($rows['attachment'])) {
            $data_attachment = json_decode($rows['attachment'], true);
            
            if (!is_array($data_attachment) || !isset($data_attachment[0])) {
                $data_attachment = [$data_attachment];
            }
            
            foreach ($data_attachment as $attachment) {
                if (isset($attachment['filepath']) && isset($attachment['original_name'])) {
                    $filepath = $attachment['filepath'];
                    $originalname = $attachment['original_name'];
                    $parts = explode('.', $originalname);
                    
                    if (count($parts) > 1) {
                        $fileExtension = strtolower(end($parts));
                        $allowedExtensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx', 'mp4'];
                        
                        if (in_array($fileExtension, $allowedExtensions)) {
                            $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filepath);
                            
                            $data_to_send[] = [
                                "filepath" => $aws_attachment,
                                "original_name" => $originalname,
                                "type" => $fileExtension
                            ];
                        }
                    }
                }
            }
        }

        // Process branch information
        $branch = [];
        $branch_id = $rows['branch_id'];
        $branch_ids_array = json_decode($branch_id, true);
        
        if ($branch_id == 'all' || (is_array($branch_ids_array) && in_array('all', $branch_ids_array))) {
            $branch[] = ['branch_id' => 'all', 'branch_name' => 'All branches'];
        } elseif (!empty($branch_ids_array) && is_array($branch_ids_array)) {
            $imploded_branch_ids = implode(',', array_map('intval', $branch_ids_array));
            $sql = "SELECT * FROM branch WHERE institution_id = ? AND id IN ($imploded_branch_ids)";
            $stmt = $conn_rjllearning_specific->prepare($sql);
            $stmt->execute([$institution_id]);
            foreach ($stmt->fetchAll() as $branch_data) {
                $branch[] = ['branch_id' => $branch_data['id'], 'branch_name' => $branch_data['name']];
            }
        }

        // Process section information (similar to branch)
        $section = [];
        $section_id = $rows['section_id'];
        $section_ids_array = json_decode($section_id, true);
        
        if ($section_id == 'all' || (is_array($section_ids_array) && in_array('all', $section_ids_array))) {
            $section[] = ['section_id' => 'all', 'section_name' => 'All Sections'];
        } elseif (!empty($section_ids_array) && is_array($section_ids_array)) {
            $imploded_section_ids = implode(',', array_map('intval', $section_ids_array));
            $sql = "SELECT * FROM section_info WHERE institution_id = ? AND id IN ($imploded_section_ids)";
            $stmt = $conn_rjllearning_specific->prepare($sql);
            $stmt->execute([$institution_id]);
            foreach ($stmt->fetchAll() as $section_data) {
                $section[] = ['section_id' => $section_data['id'], 'section_name' => $section_data['section_name']];
            }
        }

        // Process class information (similar to branch)
        $class_info = [];
        $class_id = $rows['class_id'];
        $class_ids_array = json_decode($class_id, true);
        
        if ($class_id == 'all' || (is_array($class_ids_array) && in_array('all', $class_ids_array))) {
            $class_info[] = ['class_id' => 'all', 'class_name' => 'All Classes'];
        } elseif (!empty($class_ids_array) && is_array($class_ids_array)) {
            $imploded_class_ids = implode(',', array_map('intval', $class_ids_array));
            $sql = "SELECT * FROM class_info WHERE institution_id = ? AND id IN ($imploded_class_ids)";
            $stmt = $conn_rjllearning_specific->prepare($sql);
            $stmt->execute([$institution_id]);
            foreach ($stmt->fetchAll() as $class_data) {
                $class_info[] = ['class_id' => $class_data['id'], 'class_name' => $class_data['classname']];
            }
        }

        // Process student information
        $student_info = [];
        $student_id = $rows['student_id'];
        $student_ids_array = json_decode($student_id, true);
        
        if ($student_id == 'all' || (is_array($student_ids_array) && in_array('all', $student_ids_array))) {
            $student_info[] = ['student_id' => 'all', 'student_name' => 'All Students'];
        } elseif (!empty($student_ids_array) && is_array($student_ids_array)) {
            $imploded_student_ids = implode(',', array_map('intval', $student_ids_array));
            $sql = "SELECT * FROM students WHERE institution_id = ? AND user_id IN ($imploded_student_ids)";
            $stmt = $conn_rjllearning_specific->prepare($sql);
            $stmt->execute([$institution_id]);
            foreach ($stmt->fetchAll() as $student_data) {
                $student_info[] = ['student_id' => $student_data['user_id'], 'student_name' => $student_data['name']];
            }
        }

        $array_return[] = [
            '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'],
            'featured_bool' => $rows['featured_bool']
        ];
    }

    return [
        'total_rows' => $totalrows,
        'activity_info' => $array_return,
        'maxreach' => (count($session_rows) < 50 ? 1 : 0)
    ];
}

if ($postdata['function_type'] == "fetch_activity_info") {
   
    $check_academic_confirmation = 
    $student_id=$userid;

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

   if (isset($postdata['from_date']) and !empty($postdata['from_date'])) {
        $from_date = trim($postdata['from_date']);
    } else {
        $from_date = null;
    }
    if (isset($postdata['to_date']) and !empty($postdata['to_date'])) {
        $to_date = trim($postdata['to_date']);
    } else {
        $to_date = null;
    }
    
    if ($from_date > $to_date) {
    errorreturn('Invalid Date format');
    }

    $limit = $postdata['limit'];


    $page = (isset($postdata['page']) and isNumeric($postdata['page'])) ? (int)$postdata['page'] : 1;

    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;
        $success['data'] = getActivity_details($conn_rjllearning_specific, $institution_id,$student_id, $branch_id, $search_string,$userid, $class_id, $section_id,$from_date,$to_date, $limit, $offset);
        successreturn($success);
    } else {
        $success['data'] = getActivity_details($conn_rjllearning_specific, $institution_id,$student_id, $branch_id, $search_string,$userid, $class_id, $section_id,$from_date,$to_date, $limit, null);
        successreturn($success);
    }
}
