<?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_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . 'functions/common_functions.php';

// Fetch and decode input data
$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();

// Required fields for validation
$requiredFields = ['name', 'api_signature', 'function_type', 'jwt_token'];
foreach ($requiredFields as $field) {
    if (!isset($postdata[$field]) || empty($postdata[$field])) {
        errorreturn("Field '$field' is required.");
    }
}

validateApiSignature($postdata['api_signature']);

// Extract input values
$name = trim($postdata['name']);
$function_type = trim($postdata['function_type']);
$jwt_token = trim($postdata['jwt_token']);
$status = isset($postdata['status']) ? (int) $postdata['status'] : 1;
$id = isset($postdata['id']) ? (int) $postdata['id'] : null;

// Additional parameters with validation
$percentage_bool = isset($postdata['percentage_bool']) ? (int) $postdata['percentage_bool'] : 0;
$percent_amount = isset($postdata['percent_amount']) ? (float) $postdata['percent_amount'] : 0.00;
$calculate_on = isset($postdata['calculate_on']) && in_array($postdata['calculate_on'], ['basic', 'adjusted']) ? $postdata['calculate_on'] : 'basic';
$type = isset($postdata['type']) && in_array($postdata['type'], ['add', 'deduct']) ? $postdata['type'] : 'add';
$applicable_if_amount_lte = isset($postdata['applicable_if_amount_lte']) ? (float) $postdata['applicable_if_amount_lte'] : null;
$applicable_if_amount_gte = isset($postdata['applicable_if_amount_gte']) ? (float) $postdata['applicable_if_amount_gte'] : null;

// Validate JWT Token
$jwt_validate = authenticate_jwt($jwt_token);
if (!$jwt_validate) {
    errorreturn("Invalid JWT token.");
}

$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_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);
if (!$conn_rjllearning_specific) {
    errorreturn("Failed to connect to the database.");
}
$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);

// Main API operations
try {
    if ($function_type === "create_salary_param") {
        // Validate inputs
        if ($percent_amount < 0) errorreturn("Percentage amount cannot be negative.");
        if ($applicable_if_amount_lte !== null && $applicable_if_amount_gte !== null && $applicable_if_amount_lte < $applicable_if_amount_gte) {
            errorreturn("applicable_if_amount_lte should be greater than or equal to applicable_if_amount_gte.");
        }

        $query = "INSERT INTO salary_params 
                  (institution_id, branch_id, name, percentage_bool, percent_amount, calculate_on, type, applicable_if_amount_lte, applicable_if_amount_gte, date_created, time_created, status) 
                  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn_rjllearning_specific->prepare($query);
        if ($stmt->execute([$institution_id, $branch_id, $name, $percentage_bool, $percent_amount, $calculate_on, $type, $applicable_if_amount_lte, $applicable_if_amount_gte, date('Y-m-d'), date('H:i:s'), $status])) {
            successreturn("Salary parameter created successfully.");
        } else {
            errorreturn("Failed to create salary parameter.");
        }
    } elseif ($function_type === "update_salary_param") {
        if (!$id) errorreturn("Field 'id' is required for updating salary parameter.");
        
        // Validate inputs
        if ($percent_amount < 0) errorreturn("Percentage amount cannot be negative.");
        if ($applicable_if_amount_lte !== null && $applicable_if_amount_gte !== null && $applicable_if_amount_lte < $applicable_if_amount_gte) {
            errorreturn("applicable_if_amount_lte should be greater than or equal to applicable_if_amount_gte.");
        }

        $query = "UPDATE salary_params 
                  SET name = ?, percentage_bool = ?, percent_amount = ?, calculate_on = ?, type = ?, applicable_if_amount_lte = ?, applicable_if_amount_gte = ?, status = ? 
                  WHERE id = ? AND institution_id = ? AND branch_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($query);
        if ($stmt->execute([$name, $percentage_bool, $percent_amount, $calculate_on, $type, $applicable_if_amount_lte, $applicable_if_amount_gte, $status, $id, $institution_id, $branch_id])) {
            successreturn("Salary parameter updated successfully.");
        } else {
            errorreturn("Failed to update salary parameter.");
        }
    } elseif ($function_type === "delete_salary_param") {
        if (!$id) errorreturn("Field 'id' is required for deleting salary parameter.");

        $query = "DELETE FROM salary_params WHERE id = ?";
        $stmt = $conn_rjllearning_specific->prepare($query);
        if ($stmt->execute([$id])) {
            successreturn("Salary parameter deleted successfully.");
        } else {
            errorreturn("Failed to delete salary parameter.");
        }
    } else {
        errorreturn("Invalid function_type.");
    }
} catch (PDOException $e) {
    errorreturn("Database Error: " . $e->getMessage());
}
?>
