<?php
// Enable error display for debugging
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 . '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";
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";


// Decode JSON input data
$postdata = json_decode(file_get_contents("php://input"), true);

// Check if no data was received
checkIfNoPhpContentsReceive();

// Validate required fields
$requiredFields = [
    'academic_id',
    'template_id',
    'api_signature',
    'function_type',
    'jwt_token'
];

foreach ($requiredFields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("All * fields are required.$field");
        break;
    }
}

// Validate API signature
validateApiSignature($postdata['api_signature']);

// Authenticate JWT token
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);

// Extract user details from JWT token
$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 and get specific database name
$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);

// Extract necessary fields from $postdata
$class_id = trim($postdata['class_id']);
$status = isset($postdata['status']) ? trim($postdata['status']) : null;
$template_id = trim($postdata['template_id']);
$function_type = trim($postdata['function_type']);
$last_updated_time = date("Y-m-d H:i:s");

$examination_name = isset($postdata['examination_name']) ? ucwords(trim($postdata['examination_name'])) : 'Semester';
$notes = isset($postdata['notes']) && !empty($postdata['notes']) ? ucwords(strtolower(trim($postdata['notes']))) : null;

if (empty($template_id)) {
    errorreturn("Template ID is required.");
}
$custom_stylesheet_id = empty($postdata['custom_stylesheet_id'])
    ? null
    : trim($postdata['custom_stylesheet_id']);


$academic_id = isset($postdata['academic_id']) ? $postdata['academic_id'] : errorreturn("Kindly choose valid academic session.");
$academic_session = GetAcademicSessionName($conn_rjllearning_specific, $institution_id, $academic_id);

if(empty($academic_session)){
    errorreturn("Please enter a valid academic id.");
} else {
    $academic_session = $academic_session['name'];
}

// Check if template exists
$sql_check_template = $conn_rjllearning->prepare("SELECT id FROM template_info WHERE id = ?");
$sql_check_template->execute([$template_id]);
if ($sql_check_template->rowCount() === 0) {
    errorreturn("Template with ID $template_id does not exist.");
}

// Verify faculty existence
$sql_faculty = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE userid = ? AND institution_id = ? AND branch_id = ?");
$sql_faculty->execute([$userid, $institution_id, $branch_id]);
$result_faculty = $sql_faculty->fetch(PDO::FETCH_ASSOC);
if (!$result_faculty) {
    errorreturn("Faculty not found.");
}

$faculty_id = $result_faculty['id'];

// Check faculty permissions
$teacher_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $userid);
$check_faculty_status=checkFacultyModuleGranted($function_type, $teacher_data['class_section_subjects'], $teacher_data['class_incharge_roles'], $teacher_data['staff_access_modules'], $class_id, null, null, $conn_rjllearning);
if($check_faculty_status == false){
        errorreturn("Access denied: You do not have the required permissions.");
    }
// Process marksheet creation
if ($function_type === "create_marksheet_info") {
 try {
    // Insert into marksheet table
    $sql_marksheet = $conn_rjllearning_specific->prepare("
        INSERT INTO marksheet (institution_id, template_id, academic_id, academic_session, examination_name, notes, added_by, date_created, time_created ,custom_stylesheet_id) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ? ,?)");
    
    $sql_marksheet->execute([
        $institution_id,
        $template_id,
        $academic_id,
        $academic_session,
        $examination_name,
        $notes,
        $username,
        date("Y-m-d"),
        date("H:i:s"),
        $custom_stylesheet_id
    ]);
    
    $marksheet_id = $conn_rjllearning_specific->lastInsertId();

    // Insert into marksheet_info table
    $sql_marksheet_info = $conn_rjllearning_specific->prepare("
        INSERT INTO marksheet_info (institution_id, branch_id, marksheet_id, class_id, status) 
        VALUES (?, ?, ?, ?, ?)");
    
    $sql_marksheet_info->execute([
        $institution_id,
        $branch_id,
        $marksheet_id,
        $class_id,
        $status ?: 0
    ]);

    successreturn("Marksheet info created successfully with Marksheet ID: $marksheet_id.");
} catch (Exception $e) {
    errorreturn("Error creating marksheet: " . $e->getMessage());
}

}
