<?php
// rename_file.php
header('Content-Type: application/json');
$data = json_decode(file_get_contents('php://input'), true);

$transactionId = $data['transactionId'];
$folder = $data['folder']; // invoices | warranty
$oldName = $data['oldName'];
$newName = $data['newName'];

$baseDir = __DIR__ . "/uploads/transactions/transaction_$transactionId/";
$transactionDir = realpath($baseDir . $folder) . '/';

$oldFilePath = $transactionDir . basename($oldName);
$newFilePath = $transactionDir . basename($newName);

// ðŸ”¹ Debug output
error_log("Transaction ID received: $transactionId");
error_log("Old file: $oldName");
error_log("New file: $newName");

// ✅ Debug: show the full path PHP is checking
error_log("Old file path: $oldFilePath");
if (!file_exists($oldFilePath)) {
    echo json_encode(['success' => false, 'message' => 'File not found', 'transactionId' => $transactionId]);
    exit;
}

if (rename($oldFilePath, $newFilePath)) {
    echo json_encode(['success' => true, 'transactionId' => $transactionId]);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to rename', 'transactionId' => $transactionId]);
}
