<?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 = [
    'institution_id',
    '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;

// Validate user access and get specific database name
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin'],null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}


$institution_id = trim($postdata['institution_id']);
$custom_stylesheet_id = empty($postdata['custom_stylesheet_id'])
    ? null
    : trim($postdata['custom_stylesheet_id']);


$check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($check_academic_confirmation != true) {
    errorreturn("Access denied. Academic session not active.");
}
$branch_ids = $postdata['branch_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.");
}

// 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_session']) ? trim($postdata['academic_session']) : date("Y");
$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") {
    $date = date("Y-m-d");
    compareDatesAcademicSession($conn_rjllearning_specific, $institution_id, $date, null, true);
    // 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,
        time(),
        $custom_stylesheet_id
    ]);

    $marksheet_id = $conn_rjllearning_specific->lastInsertId();

    // Fetch all branches if "all" is specified
if (in_array("all", $branch_ids)) {
    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 the 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) {
        // If the branch doesn't exist, skip to the next branch
        continue;
    }

    foreach ($class_ids as $class_id) {
        // Check if class exists and is linked to the current branch
        $sql_check_class = $conn_rjllearning_specific->prepare("SELECT id FROM class_info WHERE id = ? AND institution_id = ? AND (branch_id LIKE ? OR branch_id = 'all')");
        $sql_check_class->execute([$class_id, $institution_id, '%' . $branch_id . '%']);

        if ($sql_check_class->rowCount() == 0) {
            // If the class doesn't match the branch or isn't valid, skip to the next class
            continue;
        }

        // Insert valid class and branch combination 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
        ]);
    }
}
}
elseif (!in_array("all", $branch_ids) && !in_array("all", $class_ids)) {
    // Process for specific branch and class IDs
    foreach ($branch_ids as $branch_id) {
        $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) {
            // If the branch doesn't exist, skip to the next branch
            continue;
        }

        foreach ($class_ids as $class_id) {
            // Check if class exists and is linked to the current branch
            $sql_check_class = $conn_rjllearning_specific->prepare("SELECT id FROM class_info WHERE id = ? AND institution_id = ? AND (branch_id LIKE ? OR branch_id = 'all')");
            $sql_check_class->execute([$class_id, $institution_id, '%' . $branch_id . '%']);

            if ($sql_check_class->rowCount() == 0) {
                // If the class doesn't match the branch or isn't valid, skip to the next class
                continue;
            }

            // Insert valid class and branch combination 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
            ]);
        }
    }
}
else {
    // Check if branch_ids array contains specific IDs, not just "all"
    if (!in_array("all", $branch_ids)) {
        // Combine the branch IDs into a string for the WHERE clause (using IN to match multiple IDs)
      $branch_ids_str = implode(',', $branch_ids); // Convert branch IDs array into a comma-separated string

// Process each class
foreach ($class_ids as $class_id) {
    // Check how many branch_ids are provided
    $num_branch_ids = count($branch_ids);

    // Initialize the LIKE clause part of the query
    $like_clauses = [];

    // If there are branch IDs, prepare the LIKE condition for each branch
    if ($num_branch_ids > 0) {
        foreach ($branch_ids as $branch_id) {
            // Append LIKE for each branch_id
            $like_clauses[] = "branch_id LIKE '%$branch_id%'";
        }
    }

    // Prepare the full query using the constructed LIKE clause for each branch
    $sql_check_class = $conn_rjllearning_specific->prepare(
        "SELECT id, branch_id 
         FROM class_info 
         WHERE institution_id = ? 
         AND (" . implode(" AND ", $like_clauses) . " OR branch_id = 'all')"
    );

    // Execute the query with the institution_id
    $sql_check_class->execute([$institution_id]);

    // Get all valid class IDs with their respective branch_ids
    $valid_classes = $sql_check_class->fetchAll(PDO::FETCH_ASSOC);


            // If no valid classes found, skip this iteration
            if (empty($valid_classes)) {
                continue;
            }
          foreach($branch_ids as $branch_id){
            // Insert for each valid class found for this branch
            foreach ($valid_classes as $valid_class) {
                // Insert valid class and branch combination 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 (?, ?, ?, ?, ?)"
                );

                // Insert the correct branch_id from the current valid class
                $sql_insert_marksheet_info->execute([
                    $institution_id,
                    $branch_id, // Use the branch_id from the valid class
                    $marksheet_id,
                    $valid_class['id'], // Use the class_id from the valid class
                    $status ?: 0  // Default status to 0 if not provided
                ]);
            }
        }
}
    }




}
// Optionally return success message after processing
successreturn("Marksheet info created successfully with Marksheet ID: $marksheet_id.");
}
?>
