<?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';
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['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 . '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 = $postdata['function_type'];

function fetch_homework_for_classincharge($conn_rjllearning_specific, $conn_rjllearning, $institution_id, $branch_id, $userid, $function_type, $from_date, $to_date)
{
    $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'];

    if ($class_incharge_roles === null || empty($class_incharge_roles)) {
        errorreturn("User is not a class incharge or no classes assigned");
    }

    // Prepare base query for homework
    $homeworkQuery = "SELECT h.* FROM homework h WHERE h.institution_id = ? AND h.branch_id = ? AND (";
    $homeworkParams = [$institution_id, $branch_id];
    $classConditions = [];

    // Prepare student IDs query for gate passes
    $studentQuery = "SELECT s.id FROM students s WHERE s.institution_id = ? AND s.branch_id = ? AND s.can_activate = 1 AND s.status = 1 AND (";
    $studentParams = [$institution_id, $branch_id];
    $studentClassConditions = [];

    foreach ($class_incharge_roles as $role) {
        $class_id = $role['class']['class_id'];
        $section_id = $role['section']['section_id'];

        if ($section_id == 'all') {
            $classConditions[] = "h.class_id = ?";
            $homeworkParams[] = $class_id;
        } else {
            $classConditions[] = "(h.class_id = ? AND (h.section_id = 'all' OR JSON_CONTAINS(h.section_id, ?)))";
            $homeworkParams[] = $class_id;
            $homeworkParams[] = json_encode([$section_id]);
        }

        if ($section_id == 'all') {
            $studentClassConditions[] = "s.class_id = ?";
            $studentParams[] = $class_id;
        } else {
            $studentClassConditions[] = "(s.class_id = ? AND s.section_id = ?)";
            $studentParams[] = $class_id;
            $studentParams[] = $section_id;
        }
    }

    $homeworkQuery .= implode(" OR ", $classConditions) . ")";
    $studentQuery .= implode(" OR ", $studentClassConditions) . ")";

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

    $homeworkQuery .= " ORDER BY h.date_created DESC, h.time_created DESC";

    try {
        // Fetch homework
        $stmt = $conn_rjllearning_specific->prepare($homeworkQuery);
        $stmt->execute($homeworkParams);
        $homework_results = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $array_return = [];

        foreach ($homework_results 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;
            }

            $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $rows['branch_id']);
            $class_info = getClass($conn_rjllearning_specific, $institution_id, $rows['class_id']);
            $subject_info = !empty($rows['subject_id']) ? getSubject($conn_rjllearning_specific, $institution_id, $rows['subject_id']) : null;

            // Handle section information based on homework's section_id
            $section_info = ['section_id' => null, 'section_name' => null];

            if ($rows['section_id'] == 'all') {
                // Find matching class incharge role to get section info
                foreach ($class_incharge_roles as $role) {
                    if ($role['class']['class_id'] == $rows['class_id']) {
                        $section_info = [
                            'section_id' => $role['section']['section_id'],
                            'section_name' => $role['section']['section_name']
                        ];
                        break;
                    }
                }
            } else {
                // For JSON array of sections, get info for the first section
                $section_ids = json_decode($rows['section_id'], true);
                if (json_last_error() === JSON_ERROR_NONE && is_array($section_ids) && !empty($section_ids)) {
                    $first_section_id = $section_ids[0];
                    $section_info = getSection($conn_rjllearning_specific, $institution_id, $first_section_id);
                }
            }

            // Build the return array
            $array_return[] = [
                'id' => $rows['id'],
                'institution_id' => $rows['institution_id'],
                'branch_id' => $branch_info,
                'class_id' => $class_info,
                'section_id' => $section_info,
                'subject_id' => $subject_info,
                'message' => $rows['message'],
                'attachment' => $final_array_attachment,
                'date_created' => $rows['date_created'],
                'time_created' => $rows['time_created'],
                'added_by' => $rows['added_by'],
                'priority' => $rows['priority']
            ];
        }
        $stmt = $conn_rjllearning_specific->prepare($studentQuery);
        $stmt->execute($studentParams);
        $studentIds = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
        
        return [
            'homework' => $array_return
        ];
    } catch (PDOException $e) {
        error_log("Database error in fetchClassInchargeHomework: " . $e->getMessage());
        return [
            'message' => 'Failed to fetch data'
        ];
    }
}

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

    if (isset($postdata['from_date']) and !empty($postdata['from_date'])) {
        $from_date = trim($postdata['from_date']);
    } else {
        $from_date = date('Y-m-d');
    }
    if (isset($postdata['to_date']) and !empty($postdata['to_date'])) {
        $to_date = trim($postdata['to_date']);
    } else {
        $to_date = date('Y-m-d');
    }

    if ($from_date > $to_date) {
        errorreturn('Invalid Date format');
    }

    $success = fetch_homework_for_classincharge($conn_rjllearning_specific, $conn_rjllearning, $institution_id, $branch_id, $userid, $function_type, $from_date, $to_date);
    successreturn($success);
}
