<?php

ini_set('display_errors', 1);

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 . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
require_once $base_path_to_learning_resources . "includes/specific_db_config.php";
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 . "user_management/functions/functions.php";

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

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

if (
    !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_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  !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;

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

$institution_id = trim($postdata['institution_id']);

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 checkMarksheetCompletion($conn_rjllearning_specific,$institution_id,$branch_id,$class_id,$marksheet_id) {
  
    // Step 1: Fetch all students for the given institution, branch, and class
   $student_query = "SELECT COUNT(*) AS total_students FROM students WHERE institution_id = ? ";
   $query_params = [$institution_id];
    
    if ($branch_id !== 'all') {
        $student_query .= " AND branch_id = ?";
        $query_params[] = $branch_id;
    }
    
    if ($class_id !== 'all') {
        $student_query .= " AND class_id = ?";
        $query_params[] = $class_id;
    }
    // echo $student_query;die();
    $stmt_students = $conn_rjllearning_specific->prepare($student_query);
    $stmt_students->execute($query_params);
    $student_data = $stmt_students->fetch(PDO::FETCH_ASSOC); // Fetch only a single row
    // print_r($student_data);die();
    if (!$student_data || $student_data['total_students'] == 0) {
        errorreturn('No students found for the specified filters.');
    }
    
    $total_students = $student_data['total_students'];
    // echo "Total Students: " . $total_students;


    // Step 2: Fetch marksheet_id and status from marksheet_info table
    $marksheet_query = "SELECT  marksheet_id, status 
                        FROM marksheet_info 
                        WHERE institution_id = ? and id=?";
    $marksheet_params = [$institution_id,$marksheet_id];

    if ($branch_id !== 'all') {
        $marksheet_query .= " AND branch_id = ?";
        $marksheet_params[] = $branch_id;
    }
    if ($class_id !== 'all') {
        $marksheet_query .= " AND class_id = ?";
        $marksheet_params[] = $class_id;
    }

    $stmt_marksheet = $conn_rjllearning_specific->prepare($marksheet_query);
    $stmt_marksheet->execute($marksheet_params);
    $marksheets = $stmt_marksheet->fetchAll(PDO::FETCH_ASSOC);

    if (!$marksheets) {
        return errorreturn('No marksheets found for the specified filters.');
    }

    // Step 3: Check each marksheet for completion in student_marksheet_data
    $results = [];
    foreach ($marksheets as $marksheet) {
        $marksheet_id = $marksheet['marksheet_id'];

        $student_marksheet_query = "SELECT COUNT(*) AS total_marked 
                                    FROM student_marksheet_data 
                                    WHERE institution_id = ? 
                                      AND branch_id = ?
                                      AND class_id = ?
                                      AND marksheet_id = ?";
        $stmt_student_marksheet = $conn_rjllearning_specific->prepare($student_marksheet_query);
        $stmt_student_marksheet->execute([
            $institution_id,
            ($branch_id !== 'all' ? $branch_id : null),
            ($class_id !== 'all' ? $class_id : null),
            $marksheet_id
        ]);

        $marksheet_data = $stmt_student_marksheet->fetch(PDO::FETCH_ASSOC);
        $total_marked = $marksheet_data['total_marked'] ?? 0;

        // Step 4: Compare the counts and store results
        $results[] = [
            'marksheet_id' => $marksheet_id,
            'status' => $marksheet['status'],
            'total_students' => $total_students,
            'total_marked' => $total_marked,
            'completion_status' => ($total_marked === $total_students) ? 'Complete' : 'Incomplete'
        ];
    }

    // Step 5: Return results
    return $results;
}


if ($postdata['function_type'] == "fetch_publish_marksheets") {
    $marksheet_id= trim($postdata['marksheet_id']);
    $branch_id = isset($postdata['branch_id']) ? trim($postdata['branch_id']) : 'all';
    $class_id = isset($postdata['class_id']) ? trim($postdata['class_id']) : 'all';

// Log the values for debugging

    $marksheets = checkMarksheetCompletion($conn_rjllearning_specific,$institution_id,$branch_id,$class_id,$marksheet_id) ;
    successreturn($marksheets);
}
