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


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

if (

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




function getAnnouncement($conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id,$check_academic_confirmation, $search_string, $from_date, $to_date, $limit, $offset)
{
    // Query to get the total number of announcements
    $sql = "SELECT COUNT(*) as total_rows FROM announcement WHERE institution_id = ? and academic_id =?";
    $array_params = [$institution_id,$check_academic_confirmation];

    // Add branch_id filter
    if ($branch_id != null && $branch_id != 'all') {
        $sql .= " AND (branch_id = ? or branch_id='all')";
        $array_params[] = $branch_id;
    }

    // Add class_id filter
    if ($class_id != null && $class_id != 'all') {
        $sql .= " AND (class_id = ? or class_id ='all')";
        $array_params[] = $class_id;
    }

    // Add section_id filter
    if ($section_id != null && $section_id != 'all') {
        $sql .= " AND (section_id = ? OR section_id = 'all')";
        $array_params[] = $section_id;
    }

    // Add search string filtering
    if ($search_string != null) {
        $sql .= " AND (title LIKE ? OR message LIKE ?)";
        $array_params[] = '%' . $search_string . '%';
        $array_params[] = '%' . $search_string . '%';
    }

    // Prepare and execute the query
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $result_total = $stmt->fetch();
    $totalrows = $result_total['total_rows'];

    // Base query for fetching announcements
    $sql = "SELECT * FROM announcement WHERE institution_id = ? and academic_id=?";
    $array_params = [$institution_id,$check_academic_confirmation];

    if ($branch_id != null && $branch_id != 'all') {
        $sql .= " AND (branch_id = ? or branch_id='all')";
        $array_params[] = $branch_id;
    }

    if ($class_id != null && $class_id != 'all') {
        $sql .= " AND (class_id = ? or class_id ='all')";
        $array_params[] = $class_id;
    }

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

    if ($search_string != null) {
        $sql .= " AND (title LIKE ? OR message LIKE ?)";
        $array_params[] = '%' . $search_string . '%';
        $array_params[] = '%' . $search_string . '%';
    }

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

    $sql .= " ORDER BY date_created DESC, time_created DESC";
    if ($limit != 'all') {
        $sql .= " LIMIT " . $offset . ", " . $limit;
    }

    // Execute the query and fetch results
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $result = $stmt->fetchAll();

    $array_return = [];
    foreach ($result as $rows) {
        // Process attachment
        $final_array_attachment = null;
        if (!empty($rows['attachment'])) {
            $data_attachment = json_decode($rows['attachment'], true);
            if ($data_attachment && isset($data_attachment['filepath'], $data_attachment['original_name'])) {
                $filePath = $data_attachment['filepath'];
                $originalName = $data_attachment['original_name'];
                $fileExtension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));

                $allowedExtensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];
                if (in_array($fileExtension, $allowedExtensions)) {
                    $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
                    $final_array_attachment = [
                        "filepath" => $aws_attachment,
                        "original_name" => $originalName,
                        "type" => $fileExtension
                    ];
                }
            }
        }

        // Fetch branch, class, and section information
        $branch_info = $rows['branch_id'] == 'all' ? ['branch_id' => 'all', 'name' => ucwords('all')] : getBranchInfo($conn_rjllearning_specific, $institution_id, $rows['branch_id']);

        $class_info = $rows['class_id'] == 'all' ? ['class_id' => 'all', 'class_name' => ucwords('all')] : getClass($conn_rjllearning_specific, $institution_id, $rows['class_id']);

        $section = $rows['section_id'] == 'all' ? ['section_id' => 'all', 'section_name' => ucwords('all')] : getSection($conn_rjllearning_specific, $institution_id, $rows['section_id']);

        // Add formatted data to the return array
        $array_return[] = [
            'announcement_id' => $rows['id'],
            'branch_info' => $branch_info,
            'class_info' => $class_info,
            'section_info' => $section,
            'title' => $rows['title'],
            'message' => $rows['message'],
            'attachment' => $final_array_attachment,
            'date_created' => $rows['date_created'],
            'time_created' => date("H:i:s", strtotime($rows['time_created']))
        ];
    }

    $maxreach = count($result) < $limit ? 1 : 0;

    return [
        'total_rows' => $totalrows,
        'announcement_info' => $array_return,
        'maxreach' => $maxreach
    ];
}


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

    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;
    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }

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