<?php
define('AES_KEY', 'ROBI');
define('AES_IV', '1234567890123456');

function auth_encode($data){
    $dataToEncrypt = $data;
    $key = AES_KEY;
    $iv = AES_IV;
    $encryptedData = openssl_encrypt($dataToEncrypt, 'aes-256-cbc', $key, 0, $iv);
    return urlencode(base64_encode($encryptedData));
}

function url_encode($data){
    $dataToEncrypt = $data;
    $key = AES_KEY;
    $iv = AES_IV;
    $encryptedData = openssl_encrypt($dataToEncrypt, 'aes-256-cbc', $key, 0, $iv);
    return urlencode(base64_encode($encryptedData));
}

function url_decode($data){
    $encryptedData = base64_decode(urldecode($data));
    $key = AES_KEY;
    $iv = AES_IV;
    $decryptedData = openssl_decrypt($encryptedData, 'aes-256-cbc', $key, 0, $iv);
    return $decryptedData;
}



// New SHA-256 functions
function auth_encode_sha256($data){
    // Generate SHA-256 hash of the data
    $hashedData = hash('sha256', $data);
    return urlencode($hashedData);
}

function url_encode_sha256($data){
    // Generate SHA-256 hash of the data
    $hashedData = hash('sha256', $data);
    return urlencode($hashedData);
}

// Since SHA-256 is a one-way function, we can only verify, not decode
function url_verify_sha256($data, $hashedData){
    // Generate SHA-256 hash of the input data
    $computedHash = hash('sha256', $data);
    // Compare with the provided hash (URL decode first)
    $decodedHash = urldecode($hashedData);
    // Return true if they match, false otherwise
    return hash_equals($computedHash, $decodedHash);
}

// function has_permission($fileName, $userLevel){
//     // echo $fileName;
//     // Array mapping file names to required user levels
//     $permissions = array(
//         'admin_page.php' => 3,
//         'moderator_page.php' => 3,
//         'user_page.php' => 3,
//         'alternative_mail_setup.php' => 3,
//         'check_password_vendor.php' => 3,
//         'company_info.php' => 3,
//         'cost_avoidance.php' => 3,
//         'currency_info.php' => 3,
//         'error_log' => 3,
//         'event_commodity.php' => 3,
//         'event_sub_commodity.php' => 3,
//         'get_master_vendor_ajax.php' => 3,
//         'group_create.php' => 3,
//         'item_group.php' => 3,
//         'action_logs.php' => 3,
//         'item_info.php' => 3,
//         'item_sub_group.php' => 3,
//         'mail_logs.php' => 3,
//         'mail_template.php' => 3,
//         'pass_var.php' => 3,
//         'sourcing_type.php' => 3,
//         'unit_management.php' => 3,
//         'update_pass_change_link.php' => 3,
//         'update_pass_change_link_vendor.php' => 3,
//         'user_department.php' => 3,
//         'user_division.php' => 3,
//         'user_info.php' => 3,
//         'user_info_self.php' => 3,
//         'user_p_update.php' => 3,
//         'vendor_category.php' => 3,
//         'vendor_info.php' => 3,
//         'vendor_info_old.php' => 3,
//         'vendor_massage.php' => 3
//     );

//     // Check if the file exists in the permissions array
//     if(array_key_exists($fileName, $permissions)){

//         // If the user's level is greater than or equal to the required level, return true
//         if($userLevel == $permissions[$fileName]){
//             return true;
//         }
//     }

//     // If no permission or level is insufficient, return false
//     return false;
// }


function has_permission($fileName, $userLevel, $conn) {
    $role_sql = "SELECT allowed_page FROM user_role WHERE id = '$userLevel' LIMIT 1";
    $role_result = mysqli_query($conn, $role_sql);
    
    if (mysqli_num_rows($role_result) > 0) {
        $role_data = mysqli_fetch_assoc($role_result);
        
        $allowed_pages = json_decode($role_data['allowed_page'], true);
  
        if (in_array($fileName, $allowed_pages)) {
            return true;
        }
    }
    
    return false;
  }
function logChanges($table,$conn, $conditionField, $conditionValue, $postData, $logTable) {
    // Create the SQL query to fetch the current data based on the condition
    $ssql = "SELECT * FROM $table WHERE $conditionField = '$conditionValue'";
    $qrry = mysqli_query($conn,$ssql);
    
    // Initialize an empty array to hold the rows
    $rows = [];
    while ($row = mysqli_fetch_assoc($qrry)) {
        $rows[] = $row;
    }
    
    // Loop through the rows and compare the values
    foreach ($rows as $row) {
        foreach ($row as $column => $value1) {
            // Check if the value in the database is different from the $_POST value
            if($column !='edit_at' and $column !='edit_by'){
            if ($value1 != $postData[$column]) {
                if (isset($postData[$column]) && $postData[$column] != '') {
                    // Prepare the log insert query for the provided log table
                    $log_insert = "INSERT INTO $logTable SET 
                        tr_no = '$conditionValue', 
                        change_field = '$column', 
						previous_value='$value1',
                        change_value = '" . $postData[$column] . "', 
                        entry_at = '" . date('Y-m-d H:i:s') . "', 
                        entry_by = '" . $_SESSION['user']['id'] . "', 
                        tr_from = '$table'";
                    
                    // Execute the query to log the change
                    mysqli_query($conn,$log_insert);
                }
            }
        }
        }
    }
}
function logInitialInsert($table,$conn, $conditionField, $conditionValue, $logTable) {
    // Create the SQL query to fetch the current data based on the condition
    $ssql = "SELECT * FROM $table WHERE $conditionField = '$conditionValue'";
    $qrry = mysqli_query($conn,$ssql);
    
    // Initialize an empty array to hold the rows
    $rows = [];
    while ($row = mysqli_fetch_assoc($qrry)) {
        $rows[] = $row;
    }
    
    // Loop through the rows and compare the values
    foreach ($rows as $row) {
        foreach ($row as $column => $value1) {
            // Check if the value in the database is different from the $_POST value


                    // Prepare the log insert query for the provided log table
                    $log_insert = "INSERT INTO $logTable SET 
                        tr_no = '$conditionValue', 
                        change_field = '$column', 
						previous_value='N/A',
                        change_value = '$value1', 
                        entry_at = '" . date('Y-m-d H:i:s') . "', 
                        entry_by = '" . $_SESSION['user']['id'] . "', 
                        tr_from = '$table'";
                    
                    // Execute the query to log the change
                    mysqli_query($conn,$log_insert);
                
            
        }
    }
}


?>