<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

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 . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning . 'admin_api/modules/students/student_functions.php';
require_once $base_path_to_learning_resources . 'lib/cron_jobs/function/function.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
require_once $base_path_to_learning . "faculty_api/faculty_function/common_faculty_function.php";
require_once $base_path_to_learning . "principal_api/principal_function/principal_function.php";

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$postdata = $_POST;

$required_fields = [
    'api_signature',
    'function_type',
    'jwt_token',
    'transaction_type',
    'first_party_type'
];

foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("Missing or empty field: " . $field);
    }
}

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

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;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['teacher'], null);
if (!$specific_db_name) {
    errorreturn("Access denied.");
}
$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);

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

$transaction_type = trim($postdata['transaction_type']);
$item_id = trim($postdata['item_id']);
$quantity = trim($postdata['quantity']);

$inventory_query = "
    SELECT 
        COALESCE(SUM(CASE WHEN transaction_type = 'purchase' AND branch_id = ? THEN quantity ELSE 0 END), 0) AS purchase_qty,
        COALESCE(SUM(CASE WHEN transaction_type = 'sales' AND branch_id = ? THEN quantity ELSE 0 END), 0) AS sales_qty,
        COALESCE(SUM(CASE WHEN transaction_type = 'transfer' AND branch_id = ? THEN quantity ELSE 0 END), 0) AS transferred_out_qty,
        COALESCE(SUM(CASE WHEN transaction_type = 'transfer' AND second_party = ? THEN quantity ELSE 0 END), 0) AS transferred_in_qty
    FROM inventory_transactions
    WHERE item_id = ? AND institution_id = ?
";

$inv_stmt = $conn_rjllearning_specific->prepare($inventory_query);
$inv_stmt->execute([
    $branch_id, 
    $branch_id,      
    $branch_id,      
    $branch_id,      
    $item_id,        
    $institution_id  
]);

$inv_row = $inv_stmt->fetch();

$purchase_qty        = $inv_row['purchase_qty'] ?? 0;
$sales_qty           = $inv_row['sales_qty'] ?? 0;
$transferred_out_qty = $inv_row['transferred_out_qty'] ?? 0;
$transferred_in_qty  = $inv_row['transferred_in_qty'] ?? 0;

// Compute current quantity
$current_quantity = $purchase_qty + $transferred_in_qty - $sales_qty - $transferred_out_qty;

if (($transaction_type === 'sales' || $transaction_type === 'transfer') && $quantity > $current_quantity)
{
    errorreturn("Insufficient stock. Available quantity: " . $current_quantity);
}

$amount = trim($postdata['amount']);
$first_party = trim($postdata['first_party']);   //student_id or verndor_name
$first_party_type = trim($postdata['first_party_type']);  //vendor or student

if (!in_array($first_party_type, ['vendors', 'students'], true)) {
    errorreturn("Invalid first_party_type value. It must be vendors or students.");
}

$remarks = (isset($postdata['remarks']) and !empty($postdata['remarks'])) ? trim($postdata['remarks']) : null;
$attachment = (isset($_FILES['attachment']) and !empty($_FILES['attachment'])) ? $_FILES['attachment'] : null;

$otp_authorisation = (isset($postdata['otp_authorisation']) and !empty($postdata['otp_authorisation'])) ? trim($postdata['otp_authorisation']) : null;
$payment_bool = isset($postdata['payment_bool']) ? $postdata['payment_bool'] : 0; // 1 for paid, 0 for unpaid

// Define allowed payment methods
$allowed_payment_methods = [
    'cheque',
    'upi',
    'credit_card',
    'debit_card',
    'internet_banking',
    'qr_code',
    'cash',
    'others'
];

// Ensure payment_method is formatted using ucwords
$payment_method = isset($postdata['payment_method']) && $postdata['payment_method'] !== ''
    ? $postdata['payment_method']
    : null;

if (!in_array($payment_method, $allowed_payment_methods, true) and $payment_method != null) {
    errorreturn("Invalid payment_method. Allowed values are: " . implode(', ', $allowed_payment_methods) . ".");
}

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

$function_type =$postdata['function_type'];
$Faculty_Codes = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE userid = ? AND institution_id = ? AND branch_id = ?");
$Faculty_Codes->execute(array($userid, $institution_id, $branch_id));

// Fetch a single row instead of all
$result_faculty = $Faculty_Codes->fetch(PDO::FETCH_ASSOC);

// Check if the faculty exists
if ($result_faculty === false) {
    errorreturn("Faculty Not Found.");
}

$faculty_id = $result_faculty['id'];
$faculty_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $userid);
    
$class_section_subjects  = $faculty_data['class_section_subjects'];
$class_incharge_roles = $faculty_data['class_incharge_roles'];
$staff_access_modules = $faculty_data['staff_access_modules'];

$check_faculty_status = checkFacultyModuleGranted($function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, null, null, null, $conn_rjllearning);
// if($check_faculty_status == false){
//     errorreturn("Access denied: You do not have the required permissions.");
// }

if ($postdata['function_type'] == "validate_inventorysale_otp") {
    if ($transaction_type === 'sales') {
        $conn_rjllearning_specific->beginTransaction(); // Start transaction
        try {
            // Skip OTP validation if first_party_type is vendors
            if ($first_party_type !== 'vendors') {
                $sql = "SELECT otp_setting FROM institution_global_settings WHERE institution_id = ? AND branch_id = ?";
                $stmt = $conn_rjllearning_specific->prepare($sql);
                $stmt->execute([$institution_id, $branch_id]);
                $otp_setting = $stmt->fetch(PDO::FETCH_ASSOC);

                $otp_settings_array = json_decode($otp_setting['otp_setting'], true);

                if (isset($otp_settings_array['inventory_sale_otp']) && in_array($otp_settings_array['inventory_sale_otp'], [1, 2, 3])) {
                    if (empty($postdata['otp'])) {
                        errorreturn("OTP is required for inventory sale requests.");
                    }

                    $otp = $postdata['otp'];

                    $sql = "SELECT otp, user_token FROM otp_store WHERE otp = ? AND otp_type = 'inventory_sale_otp' AND status = 0";
                    $stmt = $conn_rjllearning->prepare($sql);
                    $stmt->execute([$otp]);
                    $stored_otp_data = $stmt->fetch();

                    if (!$stored_otp_data) {
                        errorreturn("Invalid OTP");
                    }

                    $update_sql = "UPDATE otp_store SET status = 1 WHERE otp = ? AND username = ? AND otp_type = 'inventory_sale_otp'";
                    $update_stmt = $conn_rjllearning->prepare($update_sql);
                    $update_stmt->execute([$otp, $username]);
                }
            }

            $sql = "INSERT INTO inventory_transactions (institution_id, branch_id, transaction_type, item_id, quantity, date, otp_authorisation, created_by, created_at,status)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?,?)";
            $stmt = $conn_rjllearning_specific->prepare($sql);
            $stmt->execute([
                $institution_id,
                $branch_id,
                $transaction_type,
                $item_id,
                $quantity,
                date('Y-m-d'),
                $otp_authorisation,
                $username,
                time(),
                1
            ]);

            $lastInsertId = $conn_rjllearning_specific->lastInsertId();

            $sql = "SELECT id FROM unmarked_transaction_type_group WHERE institution_id = ?  AND group_name = 'sales_category'";
            $stmt = $conn_rjllearning_specific->prepare($sql);
            $stmt->execute([$institution_id]);
            $category = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$category) {
                $sql = "INSERT INTO unmarked_transaction_type_group (institution_id, group_name, created_by, date_created, time_created, status) 
                        VALUES (?, 'sales_category', ?, ?, ?,?)";
                $stmt = $conn_rjllearning_specific->prepare($sql);
                $stmt->execute([$institution_id, $username, date('Y-m-d'), time(), 1]);
                $category_id = $conn_rjllearning_specific->lastInsertId();
            } else {
                $category_id = $category['id'];
            }

            $sql = "INSERT INTO unmarked_transaction (institution_id, branch_id,category_id,transaction_type_group, amount, vendor_name, first_party_type, remarks, date, attachment, 
                    inventory_transaction_id,payment_bool,payment_method,paid_on, date_created, time_created, last_edit, created_by, last_edit_at, approved_by, recorded_in_finware, status)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?,?,?)";
            $stmt = $conn_rjllearning_specific->prepare($sql);
            $stmt->execute([
                $institution_id,
                $branch_id,
                $category_id,
                $transaction_type,
                $amount,
                $first_party,
                $first_party_type,
                $remarks,
                date('Y-m-d'),
                null,
                $lastInsertId,
                $payment_bool,
                $payment_method,
                date('Y-m-d'),
                date('Y-m-d'),
                time(),
                date('Y-m-d'),
                $username,
                time(),
                $username,
                0,
                '1'
            ]);
            $conn_rjllearning_specific->commit(); // Commit transaction
            successreturn("Successfully added inventory sale request.");
        } catch (PDOException $e) {
            $conn_rjllearning_specific->rollBack(); // Rollback transaction on error
            errorreturn("Database error: " . $e->getMessage());
        }
    } elseif ($transaction_type === 'purchase') {
        $conn_rjllearning_specific->beginTransaction(); // Start transaction

        try {
            $sql = "INSERT INTO inventory_transactions (institution_id, branch_id, transaction_type, item_id, quantity, date, created_by, created_at,status)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?,?)";
            $stmt = $conn_rjllearning_specific->prepare($sql);
            $stmt->execute([
                $institution_id,
                $branch_id,
                $transaction_type,
                $item_id,
                $quantity,
                date('Y-m-d'),
                $username,
                time(),
                1
            ]);

            $lastInsertId = $conn_rjllearning_specific->lastInsertId();

            $sql = "SELECT id FROM unmarked_transaction_type_group WHERE institution_id = ?  AND group_name = 'purchase_category'";
            $stmt = $conn_rjllearning_specific->prepare($sql);
            $stmt->execute([$institution_id]);
            $category = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$category) {
                $sql = "INSERT INTO unmarked_transaction_type_group (institution_id, group_name, created_by, date_created, time_created, status) 
                        VALUES (?, 'purchase_category', ?, ?, ?,?)";
                $stmt = $conn_rjllearning_specific->prepare($sql);
                $stmt->execute([$institution_id, $username, date('Y-m-d'), time(), 1]);
                $category_id = $conn_rjllearning_specific->lastInsertId();
            } else {
                $category_id = $category['id'];
            }

            if (!empty($attachment)) {
                $currentYear = date('Y');
                $currentMonth = date('n');
                $currentDay = date('d');

                $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id . "/" . $branch_id . "/inventory_transaction/" . $currentYear . "/" . $currentMonth . "/";

                $file_name = $attachment['name'];
                $fileTmpName = $attachment["tmp_name"];
                $fileSize = $attachment["size"];
                $fileType = $attachment["type"];
                $file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                $maxFileSize = 2 * 1024 * 1024; // 2MB

                $allowedTypes = [
                    'image/jpeg',
                    'image/png',
                    'image/gif',
                    'image/heic',
                    'application/pdf',
                    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                    'application/vnd.ms-excel',
                    'application/msword',
                    'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                ];
                $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];

                checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
            }

            $sql = "INSERT INTO unmarked_transaction (institution_id, branch_id,category_id,transaction_type_group, amount, vendor_name, first_party_type, remarks, date, attachment, 
                    inventory_transaction_id,payment_bool,payment_method,paid_on, date_created, time_created, last_edit, created_by, last_edit_at, approved_by, recorded_in_finware, status)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?,?,?)";
            $stmt = $conn_rjllearning_specific->prepare($sql);
            $stmt->execute([
                $institution_id,
                $branch_id,
                $category_id,
                $transaction_type,
                $amount,
                $first_party,
                $first_party_type,
                $remarks,
                date('Y-m-d'),
                null,
                $lastInsertId,
                $payment_bool,
                $payment_method,
                date('Y-m-d'),
                date('Y-m-d'),
                time(),
                date('Y-m-d'),
                $username,
                time(),
                $username,
                0,
                '1'
            ]);

            $lastInsertIdUnmarked = $conn_rjllearning_specific->lastInsertId();

            if (!empty($attachment)) {
                $image_name = $lastInsertIdUnmarked . "_" . uniqid() . "." . $file_extension;
                $attachment_path = $directoryPathMain . $image_name;

                // Upload to S3
                try {
                    $s3_learning_bucket->putObject([
                        'Bucket' => $learning_bucketName,
                        'Key' => $attachment_path,
                        'SourceFile' => $fileTmpName,
                    ]);
                } catch (Exception $e) {
                    errorreturn($e->getMessage());
                }

                $attachment = json_encode(["filepath" => $attachment_path, "original_name" => $file_name]);

                // Update the previously inserted row with the attachment path
                try {
                    $update_sql = "UPDATE unmarked_transaction SET attachment = ? WHERE id = ?";
                    $update_stmt = $conn_rjllearning_specific->prepare($update_sql);
                    $update_stmt->execute([$attachment, $lastInsertIdUnmarked]);
                } catch (PDOException $e) {
                    errorreturn("File update error: " . $e->getMessage());
                }
            }
            $conn_rjllearning_specific->commit(); // Commit transaction
            successreturn("Successfully added inventory purchase request.");
        } catch (PDOException $e) {
            $conn_rjllearning_specific->rollBack(); // Rollback transaction on error
            errorreturn("Database error: " . $e->getMessage());
        }
    } else {
        errorreturn("Invalid transaction type.");
    }
} elseif ($postdata['function_type'] == "update_inventorysale_otp") {
    if (empty($postdata['transaction_id'])) {
        errorreturn("Transaction ID is required for updates.");
    }

    $inventory_transaction_id = $postdata['transaction_id'];

    $date = isset($postdata['date']) ? trim($postdata['date']) : null;

    if ($transaction_type === 'sales') {
        $conn_rjllearning_specific->beginTransaction(); // Start transaction
        try {
            // Skip OTP validation if first_party_type is vendors
            if ($first_party_type !== 'vendors') {
                $sql = "SELECT otp_setting FROM institution_global_settings WHERE institution_id = ? AND branch_id = ?";
                $stmt = $conn_rjllearning_specific->prepare($sql);
                $stmt->execute([$institution_id, $branch_id]);
                $otp_setting = $stmt->fetch(PDO::FETCH_ASSOC);

                $otp_settings_array = json_decode($otp_setting['otp_setting'], true);

                if (isset($otp_settings_array['inventory_sale_otp']) && in_array($otp_settings_array['inventory_sale_otp'], [1, 2, 3])) {
                    if (empty($postdata['otp'])) {
                        errorreturn("OTP is required for inventory sale updates.");
                    }

                    $otp = $postdata['otp'];

                    $sql = "SELECT otp, user_token FROM otp_store WHERE otp = ? AND otp_type = 'inventory_sale_otp' AND status = 0";
                    $stmt = $conn_rjllearning->prepare($sql);
                    $stmt->execute([$otp]);
                    $stored_otp_data = $stmt->fetch();

                    if (!$stored_otp_data) {
                        errorreturn("Invalid OTP");
                    }

                    $update_sql = "UPDATE otp_store SET status = 1 WHERE otp = ? AND username = ? AND otp_type = 'inventory_sale_otp'";
                    $update_stmt = $conn_rjllearning->prepare($update_sql);
                    $update_stmt->execute([$otp, $username]);
                }
            }

            $sql = "UPDATE inventory_transactions SET item_id = ?, quantity = ?, otp_authorisation = ?";
            $array_params = [$item_id, $quantity, $otp_authorisation];

            if ($date !== null) {
                $sql .= ", date = ?";
                $array_params[] = $date;
            }

            $sql .= " WHERE id = ? AND institution_id = ? AND branch_id = ?";
            $array_params[] = $inventory_transaction_id;
            $array_params[] = $institution_id;
            $array_params[] = $branch_id;

            $stmt = $conn_rjllearning_specific->prepare($sql);
            $stmt->execute($array_params);

            $sql = "UPDATE unmarked_transaction SET amount = ?, remarks = ?, payment_bool = ?, payment_method = ?, last_edit = ?,
                    last_edit_at = ?, approved_by = ?";
            $array_params = [
                $amount,
                $remarks,
                $payment_bool,
                $payment_method,
                $username,
                time(),
                $username
            ];

            if ($date !== null) {
                $sql .= ", date = ?";
                $array_params[] = $date;
            }

            $sql .= " WHERE inventory_transaction_id = ? AND institution_id = ? AND branch_id = ?";
            $array_params[] = $inventory_transaction_id;
            $array_params[] = $institution_id;
            $array_params[] = $branch_id;

            $stmt = $conn_rjllearning_specific->prepare($sql);
            $stmt->execute($array_params);
            $conn_rjllearning_specific->commit(); // Commit transaction
            successreturn("Successfully updated inventory sale request.");
        } catch (PDOException $e) {
            $conn_rjllearning_specific->rollBack(); // Rollback transaction on error
            errorreturn("Database error: " . $e->getMessage());
        }
    } elseif ($transaction_type === 'purchase') {
        $conn_rjllearning_specific->beginTransaction(); // Start transaction
        try {
            $remove_bool = (isset($postdata['remove_bool']) and !empty($postdata['remove_bool'])) ? trim($postdata['remove_bool']) : 0;
            $sql_image = $conn_rjllearning_specific->prepare("SELECT attachment FROM unmarked_transaction WHERE inventory_transaction_id = ? AND institution_id = ? AND branch_id = ?");
            $sql_image->execute([$inventory_transaction_id, $institution_id, $branch_id]);
            $result_image = $sql_image->fetchAll();
            // if ($remove_bool == 1 && count($result_image) == 1) {
            //     $existing_attachment = $result_image[0]['attachment'];
            //     $data_attachment = json_decode($existing_attachment, true);
            //     $existing_attachment = $result_image[0]['attachment'] ?? null;
            //     $data_attachment = !empty($existing_attachment) ? json_decode($existing_attachment, true) : null;
            //     $filePath = $data_attachment['filepath'];
            //     awsS3UserUploadDelete($s3_learning_bucket, $learning_bucketName, $conn_rjllearning_specific, $institution_id, $filePath, null, null);
            //     $sql = "UPDATE unmarked_transaction SET attachment = NULL WHERE inventory_transaction_id = ? AND institution_id = ? AND branch_id = ?";
            //     $conn_rjllearning_specific->prepare($sql)->execute([$inventory_transaction_id, $institution_id, $branch_id]);
            // }
            
            if ($remove_bool == 1 && count($result_image) == 1) {
                $existing_attachment = $result_image[0]['attachment'] ?? null;

                if ($existing_attachment) {
                    $data_attachment = json_decode($existing_attachment, true);

                    // Add this check before accessing the array
                    if ($data_attachment && isset($data_attachment['filepath'])) {
                        $filePath = $data_attachment['filepath'];
                        awsS3UserUploadDelete($s3_learning_bucket, $learning_bucketName, $conn_rjllearning_specific, $institution_id, $filePath, null, null);

                        $sql = "UPDATE unmarked_transaction SET attachment = NULL WHERE inventory_transaction_id = ? AND institution_id = ? AND branch_id = ?";
                        $conn_rjllearning_specific->prepare($sql)->execute([$inventory_transaction_id, $institution_id, $branch_id]);
                    } else {
                        // Handle case where filepath doesn't exist in the data
                        errorreturn("Invalid attachment data structure for transaction ID: $inventory_transaction_id");
                    }
                }
            }

            $sql = "UPDATE inventory_transactions SET item_id = ?, quantity = ?";
            $array_params = [$item_id, $quantity];

            if ($date !== null) {
                $sql .= ", date = ?";
                $array_params[] = $date;
            }

            $sql .= " WHERE id = ? AND institution_id = ? AND branch_id = ?";
            $array_params[] = $inventory_transaction_id;
            $array_params[] = $institution_id;
            $array_params[] = $branch_id;

            $stmt = $conn_rjllearning_specific->prepare($sql);
            $stmt->execute($array_params);

            $sql = "UPDATE unmarked_transaction SET amount = ?, remarks = ?, payment_bool = ?, payment_method = ?, last_edit = ?,
                    last_edit_at = ?, approved_by = ?";
            $array_params = [
                $amount,
                $remarks,
                $payment_bool,
                $payment_method,
                $username,
                time(),
                $username
            ];

            if ($date !== null) {
                $sql .= ", date = ?";
                $array_params[] = $date;
            }

            $sql .= " WHERE inventory_transaction_id = ? AND institution_id = ? AND branch_id = ?";
            $array_params[] = $inventory_transaction_id;
            $array_params[] = $institution_id;
            $array_params[] = $branch_id;

            $stmt = $conn_rjllearning_specific->prepare($sql);
            $stmt->execute($array_params);

            if (!empty($_FILES['attachment'])) {
                $attachment = $_FILES['attachment'];
                $currentYear = date('Y');
                $currentMonth = date('n');
                $currentDay = date('d');
                $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id . "/" . $branch_id . "/inventory_transaction/" . $currentYear . "/" . $currentMonth . "/";

                $file_name = $attachment['name'];
                $file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                $image_name = $inventory_transaction_id . "_" . uniqid() . "." . $file_extension;
                $attachment_path = $directoryPathMain . $image_name;
                awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $attachment, $attachment_path);
                $attachment = json_encode(["filepath" => $attachment_path, "original_name" => $file_name]);
                $update_sql = "UPDATE unmarked_transaction SET attachment = ? WHERE inventory_transaction_id = ?";
                $update_stmt = $conn_rjllearning_specific->prepare($update_sql);
                $update_stmt->execute([$attachment, $inventory_transaction_id]);
            }

            $conn_rjllearning_specific->commit(); // Commit transaction
            successreturn("Successfully updated inventory purchase request.");
        } catch (PDOException $e) {
            $conn_rjllearning_specific->rollBack(); // Rollback transaction on error
            errorreturn("Database error: " . $e->getMessage());
        }
    }
} else {
    errorreturn("Invalid transaction type.");
}