<?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  !checkIfIssetAndNotEmpty($postdata['jwt_token'])) {
    errorreturn("All * fields are required.");
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
//then workspace_id is iin decodede data of jwt use from there
$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);



require_once $base_path_to_learning . 'functions/get_branch_functions.php';


function getSpecificAssignment($conn_rjllearning_specific, $institution_id, $search_string, $branch_id,$check_academic_confirmation, $class_id, $section_id, $subject_id,$userid) {
  $current_date = date('Y-m-d');
    $current_time = date('H:i');

    // Count total rows
    $sql = "SELECT COUNT(*) as total_rows 
            FROM assignments t
            LEFT JOIN assignment_submission s 
            ON t.id = s.assignment_id AND s.student_id = ?
            WHERE t.institution_id = ? and t.academic_id=?
            AND (
                (
                    (t.publish_date < ? OR (t.publish_date = ? AND t.publish_time <= ?))
                    AND (
                        (t.can_submit_after_last_date = 0 
                        AND (t.last_date IS NOT NULL AND t.last_date < ? 
                             OR t.last_submission_time IS NOT NULL AND t.last_submission_time < ?))
                        OR s.assignment_id IS NOT NULL
                    )
                )
            )";
    $array_params = [
        $userid, 
        $institution_id,
        $check_academic_confirmation,
        $current_date, 
        $current_date, 
        $current_time,
        $current_date,
        $current_time
    ];

    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $result_total = $stmt->fetch(PDO::FETCH_ASSOC);
    $totalrows = $result_total['total_rows'];

    // Fetch assignments
    $sql = "SELECT DISTINCT a.* 
            FROM assignments a
            LEFT JOIN assignment_submission s 
            ON a.id = s.assignment_id AND s.student_id = ?
            WHERE a.institution_id = ? and a.academic_id=?
            AND a.branch_id = ? 
            AND a.class_id = ? 
            AND (a.section_id = ? OR a.section_id = 'all')
            AND (
                (
                    (a.publish_date < ? OR (a.publish_date = ? AND a.publish_time <= ?))
                    AND (
                        (a.can_submit_after_last_date = 0 
                        AND (a.last_date < ? OR a.last_submission_time < ?))
                        OR s.status IN (1, 2)
                    )
                )
            )";

    $array_params = [
        $userid, 
        $institution_id,
        $check_academic_confirmation,
        $branch_id, 
        $class_id, 
        $section_id, 
        $current_date, 
        $current_date, 
        $current_time,
        $current_date,
        $current_time
    ];

    if (!empty($search_string)) {
        $sql .= " AND (a.name LIKE ? OR a.description LIKE ?)";
        $array_params[] = '%' . $search_string . '%';
        $array_params[] = '%' . $search_string . '%';
    }

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

    $sql .= " ORDER BY s.date_created DESC, s.time_created DESC";
$stmt = $conn_rjllearning_specific->prepare($sql);
$stmt->execute($array_params);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Process the results
$array_return = [];
foreach ($result as $rows) {
    // Fetch assignment questions
    $sql_questions = "SELECT * FROM assignment_questions WHERE assignment_id = ? AND institution_id = ?";
    $array_params_questions = [$rows['id'], $institution_id];
    $stmt_questions = $conn_rjllearning_specific->prepare($sql_questions);
    $stmt_questions->execute($array_params_questions);
    $result_questions = $stmt_questions->fetchAll(PDO::FETCH_ASSOC);

    // Fetch submission details
    $sql_submission = "SELECT SUM(marks_obtained) AS point_obtained, MAX(status) AS submission_status, date_created, time_created
                       FROM assignment_submission
                       WHERE assignment_id = ? AND institution_id = ? AND student_id = ?";
    $array_params_submission = [$rows['id'], $institution_id, $userid];
    $stmt_submission = $conn_rjllearning_specific->prepare($sql_submission);
    $stmt_submission->execute($array_params_submission);
    $submission_result = $stmt_submission->fetch(PDO::FETCH_ASSOC);

    $point_obtained = $submission_result['point_obtained'] ?? "unchecked";
    $submission_status = $submission_result['submission_status'] ?? 0;
    $date_created = $submission_result['date_created'] ?? null;
    $time_created = $submission_result['time_created'] ?? null;

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

    if ($section_id == 'all') {
        $section_info[] = ['section_id' => $section_id, 'section_name' => ucwords($section_id)];
    } else {
        $sql_section = "SELECT * FROM section_info WHERE institution_id = ? AND id IN ($section_id)";
        $array_params_section = [$institution_id];
        $stmt_section = $conn_rjllearning_specific->prepare($sql_section);
        $stmt_section->execute($array_params_section);
        $section_rows = $stmt_section->fetchAll(PDO::FETCH_ASSOC);

        foreach ($section_rows as $section_data) {
            $section_info[] = ['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 = getBranchInfo($conn_rjllearning_specific, $institution_id, $rows['branch_id']);

    $assignment_questions = [];
    foreach ($result_questions as $temp) {
        $options = $temp['options'] ? json_decode($temp['options'], true) : null;
        // Add question details if needed
    }

    $array_return[] = [
        "assignment_id" => $rows['id'],
        "branch_id" => $branch,
        "class_info" => $class_info,
        "section_info" => $section_info,
        "subject_info" => $subject_info,
        "name" => $rows['name'],
        "description" => $rows['description'],
        "max_points" => $rows['max_points'],
        "marks_obtained" => $point_obtained,
        "publish_date" => $rows['publish_date'],
        "last_date" => $rows['last_date'],
        "can_submit_after_last_date" => $rows['can_submit_after_last_date'],
        "publish_time" => $rows['publish_time'],
        "last_submission_time" => $rows['last_submission_time'],
        "status" => $submission_status,
        "assignment_questions" => $assignment_questions,
        "date_created" => $date_created,
        "time_created" => $time_created
    ];
}

// Return results
return [
    'total_rows' => count($array_return),
    'assignment_info' => $array_return,
];
}
if($postdata['function_type']  == "fetch_students_api_previous_assignments") {  
   

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

  
    // $success['data'] = getSpecificAssignment($conn_rjllearning_specific,$institution_id,$branch_id,$class_id,$section_id,$subject_id,$from_date,$to_date, $limit, $offset) ;
    // successreturn($success);

        $success['data'] = getSpecificAssignment($conn_rjllearning_specific, $institution_id ,$search_string,$branch_id,$check_academic_confirmation,$class_id,$section_id,$subject_id,$userid) ;
        successreturn($success);

}