<?php

// Set up error reporting
ini_set('display_errors', 1);

// Include necessary files
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_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';

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

// Check if JSON is valid
$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();

// $postdata = $_POST;
// print_r($postdata);die();
$required_fields = ['assignment_id','api_signature', 'function_type', 'jwt_token'];
foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("Missing required field: $field");
    }
}
validateApiSignature($postdata['api_signature']);

// Authenticate user and get user details
$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;

// Validate user access to specific database
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["principal"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
// Include necessary function files
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);

// $assignment_submission_id = $postdata['assignment_submission_id'];
$assignment_id = trim($postdata['assignment_id']);
$student_id = trim($postdata['student_id']);
// $assignment_questions_id = trim($postdata['assignment_questions_id']);
$remarks = (isset($postdata['remarks']) and !empty($postdata['remarks'])) ? trim($postdata['remarks']) : null;
$points = (isset($postdata['points']) and !empty($postdata['points'])) ? trim($postdata['points']) : null;
// $marks_obtained = (isset($postdata['marks_obtained']) and !empty($postdata['marks_obtained'])) ? trim($postdata['marks_obtained']) : null;
$marks_array = $postdata['marks_array'];
$status = $postdata['status'] ?? 2; // 2 status checked


//check assignment_id  exists or not
$assignmentExistenceQuery = "SELECT id,max_points FROM  assignments WHERE id  = ? AND institution_id = ? AND branch_id = ?";
$assignmentExistenceStmt = $conn_rjllearning_specific->prepare($assignmentExistenceQuery);
$assignmentExistenceStmt->execute([$assignment_id,$institution_id, $branch_id]);
$resultassignmentExistence = $assignmentExistenceStmt->fetchAll();
if (count($resultassignmentExistence) < 1) {
    errorreturn("Assignment not exists.");
}
$max_points = $resultassignmentExistence[0]['max_points'];


$assignmentQuery = "SELECT id, marks_obtained FROM assignment_submission WHERE institution_id = ? AND branch_id = ? AND assignment_id = ?";
$assignmentStmt = $conn_rjllearning_specific->prepare($assignmentQuery);
$assignmentStmt->execute([$institution_id, $branch_id, $assignment_id]);

// Fetch the results
$result = $assignmentStmt->fetchAll();

if (count($result) < 1) {
    errorreturn("Assignment submission questions do not exist.");
}

// Accessing the marks_obtained from the fetched result
$marks_obtained = $result[0]['marks_obtained'];




$total_points=$points+$marks_obtained;

// Check if the given points are not greater than the assignment's max points
if ($total_points > $max_points) {
    errorreturn("Assignment points cannot be greater than the maximum points.");
}

if ($postdata['function_type'] == 'alter_assignment_submission') {

    // Update marks for each question
    if (is_array($marks_array)) {
        
        foreach ($marks_array as $tempMarks) {
            $assignment_questions_id = $tempMarks['assignment_questions_id'];
            $assignment_submission_id = $tempMarks['assignment_submission_id'];
            $marks_obtained = (isset($tempMarks['marks_obtained']) ? trim($tempMarks['marks_obtained']) : null);

          
              
            // Update marks_obtained for each assignment question
            $updateAssignment = "UPDATE assignment_submission SET marks_obtained = ? WHERE id = ? AND assignment_questions_id = ? AND institution_id = ?";
            $conn_rjllearning_specific->prepare($updateAssignment)->execute([$marks_obtained, $assignment_submission_id, $assignment_questions_id, $institution_id]);
        }
    }
    
    // Now update the overall remarks, points, and status for the assignment submission
    $updateAssignmentQuery = "UPDATE assignment_submission SET remarks = ?, points = ?, last_modified_by = ?, status = ? WHERE student_id = ? AND assignment_id = ? AND institution_id = ?";
    $conn_rjllearning_specific->prepare($updateAssignmentQuery)->execute([$remarks, $points, $username, $status,$student_id, $assignment_id, $institution_id]);

    // Return success after both operations are completed
    successreturn("Assignment submission updated successfully");
}



