<?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';

// Validation files
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';
// Dynamic db
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

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

// Check if required fields are present
$required_fields = [ 'class_id', 'subject_id', 'api_signature', 'function_type', 'topic_name', 'description', 'jwt_token'];
foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("All * fields are required.");
    }
}

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

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

// Extract data 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
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["principal"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
}

$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);

require_once $base_path_to_learning . 'functions/get_branch_functions.php';

// Extract and validate input data

$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($academic_id == false) {
    errorreturn("Access denied. Academic session not active.");
}

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

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

$subject_id = trim($postdata['subject_id']);
$topic_name = trim($postdata['topic_name']);
$description = trim($postdata['description']);
$status = isset($postdata['status']) ? trim($postdata['status']) : 1;

// Validate class
$sql_class = $conn_rjllearning_specific->prepare("SELECT * FROM class_info WHERE id = ? AND institution_id = ?");
$sql_class->execute([$class_id, $institution_id]);
if ($sql_class->rowCount() < 1) {
    errorreturn("Class info does not exist.");
}

// Check branch class subject
$check_branch_class = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, $class_id, null, $institution_id);
if ($check_branch_class == false) {
    errorreturn("Access denied.");
}

$function_type = $postdata['function_type'];

if ($function_type == "create_lesson_categories") {
    // Check if lesson category already exists
    $sql_lesson_category = $conn_rjllearning_specific->prepare("SELECT * FROM lesson_categories WHERE institution_id = ? AND class_id = ? AND subject_id = ? AND topic_name = ?");
    $sql_lesson_category->execute([$institution_id, $class_id,$subject_id,$topic_name]);
    if ($sql_lesson_category->rowCount() > 0) {
        errorreturn("Lesson category already exists.");
    }

    // Insert new lesson category
    $sql_insert_lesson_category = $conn_rjllearning_specific->prepare("INSERT INTO lesson_categories (institution_id, branch_id, academic_id, class_id, subject_id, topic_name, description, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $sql_insert_lesson_category->execute([$institution_id, $branch_id, $academic_id, $class_id, $subject_id, $topic_name, $description, $status]);

    successReturn("Lesson category successfully added.");

} elseif ($function_type == "update_lesson_categories") {
    if (!isset($postdata['lesson_category_id']) || empty($postdata['lesson_category_id'])) {
        errorreturn("Lesson Category ID is required for update.");
    }

    $category_id = trim($postdata['lesson_category_id']);

    // Update lesson category
    $sql_update_lesson_category = $conn_rjllearning_specific->prepare("UPDATE lesson_categories SET branch_id = ?, class_id = ?, subject_id = ?, topic_name = ?, description = ?, status = ? WHERE id = ? AND institution_id = ?");
    $sql_update_lesson_category->execute([$branch_id, $class_id, $subject_id, $topic_name, $description, $status, $category_id, $institution_id]);

    if ($sql_update_lesson_category->rowCount() > 0) {
        successReturn("Lesson category successfully updated.");
    } else {
        errorreturn("No lesson category found for the provided ID and institution.");
    }
}
?>
