<?php
ini_set('display_errors', 1);

require_once '../../../../resources/base_path_include.php';

require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

//valdation file
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';

//dynemic db
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . 'functions/common_functions.php';

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

if (
    !isset($postdata['institution_id']) || !checkIfIssetAndNotEmpty($postdata['institution_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.");
}

$institution_id = $postdata['institution_id'];

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);

$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

$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 = $postdata['institution_id'];
$branch_id = isset($postdata['branch_id']) && checkIfIssetAndNotEmpty($postdata['branch_id']) ? ($postdata['branch_id']) : 'all';

$name_of_profile = ucwords(strtolower($postdata['name_of_profile']));
$params_link = $postdata['params_link'];
$params_link = array_map('strval', $params_link);
sort($params_link); // Sort the array in ascending order
$params_link_json = json_encode($params_link);


// Check if all IDs in params_link exist in salary_params
$placeholders = implode(',', array_fill(0, count($params_link), '?'));
$sql_check_params = "SELECT id FROM salary_params WHERE id IN ($placeholders) AND institution_id = ?";
$check_stmt = $conn_rjllearning_specific->prepare($sql_check_params);
$check_stmt->execute(array_merge($params_link, [$institution_id]));
$valid_params = $check_stmt->fetchAll(PDO::FETCH_COLUMN);

if (count($valid_params) !== count($params_link)) {
    errorreturn("Some of the provided salary parameter IDs are invalid.");
}

$params_link_json = json_encode($params_link);
$date_now = date('Y-m-d');
$time_now = time();

if ($postdata['function_type'] == "create_payroll_profile") {
    
    $check_duplicate_sql = "SELECT id FROM payroll_profile WHERE institution_id = ? 
                            AND (branch_id = 'all' OR branch_id = ?) 
                            AND name_of_profile = ?";
    $check_stmt = $conn_rjllearning_specific->prepare($check_duplicate_sql);
    $check_stmt->execute([$institution_id, $branch_id, $name_of_profile]);
    $existing_profile = $check_stmt->fetch();

    if ($existing_profile) {
        errorreturn("A Payroll Profile already exists for this Name.");
    }

    try {
        $sql = "INSERT INTO payroll_profile (institution_id, branch_id, name_of_profile, params_link, date_created, created_by, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?)";

        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute([$institution_id, $branch_id, $name_of_profile, $params_link_json, $date_now, $username, $time_now]);

        $id = $conn_rjllearning_specific->lastInsertId();
        successreturn("Payroll Profile added successfully");
    } catch (Exception $e) {
        errorreturn("Error: " . $e->getMessage());
    }
} else if ($postdata['function_type'] == "alter_payroll_profile") {

    if (!isset($postdata['payroll_profile_id']) || !checkIfIssetAndNotEmpty($postdata['payroll_profile_id'])) {
        errorreturn('Error in updating the payroll profile.');
    } else {
        $id = $postdata['payroll_profile_id'];
    }

    $res = $conn_rjllearning_specific->prepare("SELECT id FROM payroll_profile WHERE id = ? AND institution_id = ?");
    $res->execute(array($id, $institution_id));
    $result1 = $res->fetchAll();
    if (count($result1) != 1) {
        errorreturn("Payroll profile does not exist.");
    }

    $sql_payroll_profile = "UPDATE payroll_profile SET branch_id = ?, name_of_profile = ?, 
                            params_link = ?, last_modified_by = ?, last_modified_at = ? 
                            WHERE id = ? AND institution_id = ?";

    $conn_rjllearning_specific->prepare($sql_payroll_profile)->execute(array(
        $branch_id,
        $name_of_profile,
        $params_link_json,
        $username,
        $time_now,
        $id,
        $institution_id
    ));

    successreturn("Updated payroll profile successfully");
}
