<?php

// fetch homework faculty

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';
//dynemic db
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning . "faculty_api/faculty_function/common_faculty_function.php";
require_once $base_path_to_learning . "principal_api/principal_function/principal_function.php";

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

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

if (
    !isset($postdata['class_id']) or !checkIfIssetAndNotEmpty($postdata['class_id']) or
    !isset($postdata['section_id']) or !checkIfIssetAndNotEmpty($postdata['section_id']) or
    !isset($postdata['subject_id']) or !checkIfIssetAndNotEmpty($postdata['subject_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  !checkIfIssetAndNotEmpty($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;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;

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

require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
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_type = trim($postdata['function_type']);

$Faculty_Codes = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE userid = ? AND institution_id = ? AND branch_id = ?");
$Faculty_Codes->execute(array($userid, $institution_id, $branch_id));

// Fetch a single row instead of all
$result_faculty = $Faculty_Codes->fetch(PDO::FETCH_ASSOC);

// Check if the faculty exists
if ($result_faculty === false) {
    errorreturn("Faculty Not Found.");
}

// Retrieve the faculty_id from the result
$faculty_id = $result_faculty['id'];

// function getHomework($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $subject_id, $class_id, $section_id, $from_date, $to_date, $limit, $faculty_id, $function_type, $conn_rjllearning, $userid, $offset)
// {
//     // get roles
//     $teacher_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $userid);
//     $class_section_subjects  = $teacher_data['class_section_subjects'];

//     $class_incharge_roles = $teacher_data['class_incharge_roles'];
//     $staff_access_modules = $teacher_data['staff_access_modules'];

//     $check_faculty_status = checkFacultyModuleGranted($function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, $class_id, $section_id, $subject_id, $conn_rjllearning);
//     if ($check_faculty_status == false) {
//         errorreturn("Access denied: You do not have the required permissions.");
//     }

//     $sql_count = "SELECT  count(*) as total_rows FROM  homework  where institution_id =? AND branch_id = ?";
//     $array_params = [$institution_id, $branch_id];


//     // Search string filter
//     if ($search_string != null) {
//         $sql_count .= " AND message LIKE ?";
//         $array_params[] = '%' . $search_string . '%'; // Add the search string to the parameters
//     }

//     // Date range filter
//     if ($from_date != null && $to_date != null) {
//         $sql_count .= " AND date_created BETWEEN ? AND ?";
//         $array_params[] = $from_date; // Start date
//         $array_params[] = $to_date;   // End date
//     }

//     // Call facultyFilterQueryAppend to modify the query and parameters
//     $sql_append_data = facultyFilterQueryAppend($sql_count, $array_params, $function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, $class_id, $section_id, $subject_id, $conn_rjllearning, 1, 1, 1, 1, true);
//     $sql_count = $sql_append_data['sql']; // Get the modified SQL
//     $array_params = $sql_append_data['array_params'];

//     $stmt = $conn_rjllearning_specific->prepare($sql_count);
//     $stmt->execute($array_params);
//     $result_total = $stmt->fetchAll();
//     $totalrows = $result_total[0]['total_rows'];
//     // Prepare the homework query
//     $array_params = [$institution_id, $branch_id];
//     $sql_session = "SELECT * FROM homework WHERE institution_id = ? AND branch_id = ?";


//     // Search string filter
//     if ($search_string !== null) {
//         $sql_session .= " AND message LIKE ?";
//         $array_params[] = '%' . $search_string . '%'; // Add the search string to the parameters
//     }

//     // Date range filter
//     if ($from_date !== null && $to_date !== null) {
//         $sql_session .= " AND date_created BETWEEN ? AND ?";
//         $array_params[] = $from_date; // Start date
//         $array_params[] = $to_date;   // End date
//     }

//     // Call facultyFilterQueryAppend to modify the query and parameters
//     $sql_append_data = facultyFilterQueryAppend($sql_session, $array_params, $function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, $class_id, $section_id, $subject_id, $conn_rjllearning, 1, 1, 1, 1, true);
//     $sql_session = $sql_append_data['sql']; // Get the modified SQL
//     $array_params = $sql_append_data['array_params'];

//     // Determine if all records should be fetched or limit should be applied
//     $sql_session .= " order by date_created desc, time_created desc ";
//     $sql_session .= "LIMIT " . $offset . " ," . $limit . "";

//     // Execute the query
//     $stmt = $conn_rjllearning_specific->prepare($sql_session);
//     $stmt->execute($array_params);
//     $session_rows = $stmt->fetchAll();

//     $array_return = [];

//     foreach ($session_rows as $rows) {

//         if ($rows['attachment'] != null and !is_array($rows['attachment'])) {
//             $data_attachment = json_decode($rows['attachment'], true);
//             $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);
//         } else {
//             $final_array_attachment =  null;
//         }

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

//         $section = [];

//         if ($section_id == 'all') {
//             $section[] = array('section_id' => $section_id, 'section_name' => ucwords($section_id));
//         } else {
//             if (is_string($section_id)) {
//                 $section_id = json_decode($section_id, true); // Decode if it's a JSON string
//             }
//             if (!is_array($section_id)) {
//                 $section_id = [$section_id]; // Ensure it's an array
//             }
//             $placeholders = implode(',', array_fill(0, count($section_id), '?'));
//             $sql = "SELECT * FROM section_info WHERE institution_id = ? AND id IN ($placeholders)";
//             $stmt = $conn_rjllearning_specific->prepare($sql);
//             $stmt->execute(array_merge([$institution_id], $section_id));
//             $section_rows = $stmt->fetchAll();
//             foreach ($section_rows as $section_data) {
//                 $section[] = array('section_id' => $section_data['id'], 'section_name' => $section_data['section_name']);
//             }
//         }

//         $class_info = getClass($conn_rjllearning_specific, $institution_id, $rows['class_id']);
//         $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $rows['subject_id']);
//         $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $rows['branch_id']);
//         $array_return[] = array('homework_id' => $rows['id'], 'branch_id' => $branch_info, 'class_info' => $class_info, 'subject_info' => $subject_info, 'section_info' => $section, 'message' => $rows['message'], 'attachment' => $final_array_attachment, 'priority' => $rows['priority'], 'date_created' => $rows['date_created']);
//     }

//     if (count($session_rows) < 50) {

//         return array('total_rows' => $totalrows, 'homework_info' => $array_return, 'maxreach' => 1);
//     } else {
//         return array('total_rows' => $totalrows, 'homework_info' => $array_return, 'maxreach' => 0);
//     }
// }


function getHomework($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $subject_id, $class_id, $section_id, $from_date, $to_date, $limit, $faculty_id, $function_type, $conn_rjllearning, $userid, $offset)
{
    // get roles
    $teacher_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $userid);
    $class_section_subjects  = $teacher_data['class_section_subjects'];
    $class_incharge_roles = $teacher_data['class_incharge_roles'];
    $staff_access_modules = $teacher_data['staff_access_modules'];

    // Check permissions - allow access if faculty has module access OR is class incharge
    $check_faculty_status = checkFacultyModuleGranted($function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, $class_id, $section_id, $subject_id, $conn_rjllearning);
    $has_module_access = ($check_faculty_status == true);
    $is_class_incharge = !empty($class_incharge_roles);
    
    if (!$has_module_access && !$is_class_incharge) {
        errorreturn("Access denied: You do not have the required permissions.");
    }

    $sql_count = "SELECT count(*) as total_rows FROM homework WHERE institution_id = ? AND branch_id = ?";
    $array_params = [$institution_id, $branch_id];

    // Search string filter
    if ($search_string != null) {
        $sql_count .= " AND message LIKE ?";
        $array_params[] = '%' . $search_string . '%';
    }

    // Date range filter
    if ($from_date != null && $to_date != null) {
        $sql_count .= " AND date_created BETWEEN ? AND ?";
        $array_params[] = $from_date;
        $array_params[] = $to_date;
    }

    // Build conditions for both study_related AND class_incharge access
    $conditions = [];
    $condition_params = [];
    
    // 1. Study related access (existing logic)
    if ($has_module_access) {
        $study_sql = "1=1"; // Base condition
        $study_params = [];
        
        $sql_append_data = facultyFilterQueryAppend($study_sql, $study_params, $function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, $class_id, $section_id, $subject_id, $conn_rjllearning, 1, 1, 1, 1, true);
        
        if ($sql_append_data['sql'] != "1=1") {
            $conditions[] = "(" . $sql_append_data['sql'] . ")";
            $condition_params = array_merge($condition_params, $sql_append_data['array_params']);
        }
    }
    
    // 2. Class incharge access (MODIFIED - respect filter parameters)
    if ($is_class_incharge) {
        $incharge_conditions = [];
        $incharge_params = [];
        
        foreach ($class_incharge_roles as $incharge_role) {
            // Check if this incharge role matches the requested filters
            $matches_class = ($class_id == 'all' || $incharge_role['class']['class_id'] == $class_id);
            $matches_section = ($section_id == 'all' || $incharge_role['section']['section_id'] == $section_id);
            
            if ($matches_class && $matches_section) {
                $class_condition = "(class_id LIKE CONCAT('%', ?, '%') OR class_id = 'all')";
                $section_condition = "(section_id LIKE CONCAT('%', ?, '%') OR section_id = 'all')";
                
                $incharge_conditions[] = "($class_condition AND $section_condition)";
                $incharge_params[] = $incharge_role['class']['class_id'];
                $incharge_params[] = $incharge_role['section']['section_id'];
            }
        }
        
        if (!empty($incharge_conditions)) {
            $conditions[] = "(" . implode(" OR ", $incharge_conditions) . ")";
            $condition_params = array_merge($condition_params, $incharge_params);
        }
    }
    
    // Combine all conditions with OR
    if (!empty($conditions)) {
        $sql_count .= " AND (" . implode(" OR ", $conditions) . ")";
        $array_params = array_merge($array_params, $condition_params);
    }

    // Execute count query
    $stmt = $conn_rjllearning_specific->prepare($sql_count);
    $stmt->execute($array_params);
    $result_total = $stmt->fetchAll();
    $totalrows = $result_total[0]['total_rows'];

    // Prepare the main homework query (similar logic as above)
    $array_params = [$institution_id, $branch_id];
    $sql_session = "SELECT * FROM homework WHERE institution_id = ? AND branch_id = ?";

    // Search string filter
    if ($search_string !== null) {
        $sql_session .= " AND message LIKE ?";
        $array_params[] = '%' . $search_string . '%';
    }

    // Date range filter
    if ($from_date !== null && $to_date !== null) {
        $sql_session .= " AND date_created BETWEEN ? AND ?";
        $array_params[] = $from_date;
        $array_params[] = $to_date;
    }

    // Apply the same permission conditions
    if (!empty($conditions)) {
        $sql_session .= " AND (" . implode(" OR ", $conditions) . ")";
        $array_params = array_merge($array_params, $condition_params);
    }

    $sql_session .= " ORDER BY date_created DESC, time_created DESC ";
    $sql_session .= "LIMIT " . $offset . " ," . $limit . "";

    // Execute the query
    $stmt = $conn_rjllearning_specific->prepare($sql_session);
    $stmt->execute($array_params);
    $session_rows = $stmt->fetchAll();

    // Rest of your existing processing code...
    $array_return = [];

    foreach ($session_rows as $rows) {
        // Your existing attachment processing code...
        if ($rows['attachment'] != null and !is_array($rows['attachment'])) {
            $data_attachment = json_decode($rows['attachment'], true);
            $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);
        } else {
            $final_array_attachment =  null;
        }

        // Your existing section processing code...
        $section_id = $rows['section_id'];
        $section = [];

        if ($section_id == 'all') {
            $section[] = array('section_id' => $section_id, 'section_name' => ucwords($section_id));
        } else {
            if (is_string($section_id)) {
                $section_id = json_decode($section_id, true);
            }
            if (!is_array($section_id)) {
                $section_id = [$section_id];
            }
            $placeholders = implode(',', array_fill(0, count($section_id), '?'));
            $sql = "SELECT * FROM section_info WHERE institution_id = ? AND id IN ($placeholders)";
            $stmt = $conn_rjllearning_specific->prepare($sql);
            $stmt->execute(array_merge([$institution_id], $section_id));
            $section_rows = $stmt->fetchAll();
            foreach ($section_rows as $section_data) {
                $section[] = array('section_id' => $section_data['id'], 'section_name' => $section_data['section_name']);
            }
        }

        $class_info = getClass($conn_rjllearning_specific, $institution_id, $rows['class_id']);
        $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $rows['subject_id']);
        $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $rows['branch_id']);
        
        $array_return[] = array(
            'homework_id' => $rows['id'], 
            'branch_id' => $branch_info, 
            'class_info' => $class_info, 
            'subject_info' => $subject_info, 
            'section_info' => $section, 
            'message' => $rows['message'], 
            'attachment' => $final_array_attachment, 
            'priority' => $rows['priority'], 
            'date_created' => $rows['date_created']
        );
    }

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

if ($function_type == "fetch_homework") {

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

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

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

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

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

    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'] = getHomework($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $subject_id, $class_id, $section_id, $from_date, $to_date, $limit, $faculty_id, $function_type, $conn_rjllearning, $userid, $offset);
        successreturn($success);
    } else {
        $success['data'] = getHomework($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $subject_id, $class_id, $section_id, $from_date, $to_date, $limit, $faculty_id, $function_type, $conn_rjllearning, $userid, null);
        successreturn($success);
    }
}
