<?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 . 'user_management/authenticate.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

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

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

// Validate required fields
// if (
//     !isset($postdata['institution_id']) || !checkIfIssetAndNotEmpty($postdata['institution_id']) ||
//     !isset($postdata['academic_session']) || !checkIfIssetAndNotEmpty($postdata['academic_session']) ||
//     !isset($postdata['template_id']) || !checkIfIssetAndNotEmpty($postdata['template_id']) ||
//     !isset($postdata['api_signature']) || !checkIfIssetAndNotEmpty($postdata['api_signature']) || 
//     !isset($postdata['function_type']) || !checkIfIssetAndNotEmpty($postdata['function_type']) || 
//     !isset($postdata['jwt_token']) || !checkIfIssetAndNotEmpty($postdata['jwt_token'])) {
//     errorreturn("All * fields are required.");
// }

$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; // Exit the loop once an error is found
    }
}


// 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_ids = $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,["principal"], 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);

// Assume branch_id is an array
$class_ids = $postdata['class_id'];   // Assume class_id is an array

$branch_ids = ($branch_ids === "all") ? ["all"] : (is_array($branch_ids) ? $branch_ids : [$branch_ids]);
$class_ids = ($class_ids === "all") ? ["all"] : (is_array($class_ids) ? $class_ids : [$class_ids]);

$status = isset($postdata['status']) ? trim($postdata['status']) : null;
$template_id = trim($postdata['template_id']);

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


// Prepare SQL to check if the template exists in the template_info table
$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.");
}

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

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

if ($postdata['function_type'] === "create_marksheet_info") {
    // Insert marksheet details into the marksheet table
    $sql_insert_marksheet = $conn_rjllearning_specific->prepare("INSERT INTO marksheet (
        institution_id, template_id, academic_id, academic_session, marksheet_name, examination_name, notes, added_by, date_created, time_created ,custom_stylesheet_id
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ? , ?)");

    $sql_insert_marksheet->execute([
        $institution_id,
        $template_id,
        $academic_id,
        $academic_session,
        $marksheet_name,
        $examination_name,
        $notes,
        $username,
        date("Y-m-d"),
        time(),
        $custom_stylesheet_id
    ]);

    $marksheet_id = $conn_rjllearning_specific->lastInsertId();

    // Fetch all branches if "all" is specified
    if (in_array("all", $branch_ids)) {
        $sql_fetch_branches = $conn_rjllearning_specific->prepare("SELECT id FROM branch WHERE institution_id = ?");
        $sql_fetch_branches->execute([$institution_id]);
        $branch_ids = $sql_fetch_branches->fetchAll(PDO::FETCH_COLUMN);
    }

    // Fetch all classes if "all" is specified
    if (in_array("all", $class_ids)) {
        $sql_fetch_classes = $conn_rjllearning_specific->prepare("SELECT id FROM class_info WHERE institution_id = ?");
        $sql_fetch_classes->execute([$institution_id]);
        $class_ids = $sql_fetch_classes->fetchAll(PDO::FETCH_COLUMN);
    }

    foreach ($branch_ids as $branch_id) {
        // Check if branch exists
        $sql_check_branch = $conn_rjllearning_specific->prepare("SELECT id FROM branch WHERE id = ? AND institution_id = ?");
        $sql_check_branch->execute([$branch_id, $institution_id]);
        if ($sql_check_branch->rowCount() == 0) {
            errorreturn("Branch ID $branch_id does not exist.");
        }

        foreach ($class_ids as $class_id) {
            // Check if class exists
            $sql_check_class = $conn_rjllearning_specific->prepare("SELECT id FROM class_info WHERE id = ? AND institution_id = ?");
            $sql_check_class->execute([$class_id, $institution_id]);
            if ($sql_check_class->rowCount() == 0) {
                errorreturn("Class ID $class_id does not exist.");
            }

            // Insert into marksheet_info
            $sql_insert_marksheet_info = $conn_rjllearning_specific->prepare("INSERT INTO marksheet_info (
                institution_id, branch_id, marksheet_id, class_id, status
            ) VALUES (?, ?, ?, ?, ?)");

            $sql_insert_marksheet_info->execute([
                $institution_id,
                $branch_id,
                $marksheet_id,
                $class_id,
                $status ?: 0 // Default status to 0 if not provided
            ]);
        }
    }

    successreturn("Marksheet info created successfully with Marksheet ID: $marksheet_id.");
}
?>
