<?php
header('Content-Type: application/json');

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

$transactionId = intval($data['transactionId']);
$folder        = $data['folder'];      // invoices | warranty
$fileName      = basename($data['file']);

// Allowed folders
$allowedFolders = ['invoices', 'warranty'];
if (!in_array($folder, $allowedFolders)) {
    echo json_encode(['success' => false, 'message' => 'Invalid folder']);
    exit;
}

// Paths
$uploadsDir = __DIR__ . "/uploads";
$transactionDir = "$uploadsDir/transactions/transaction_$transactionId/$folder";
$filePath = "$transactionDir/$fileName";

// Ensure file exists
if (!file_exists($filePath)) {
    echo json_encode(['success' => false, 'message' => 'File not found']);
    exit;
}

// Trash folder
$trashDir = "$uploadsDir/trash/" . date('Y-m-d') . "/";
if (!is_dir($trashDir)) {
    mkdir($trashDir, 0755, true); // recursive creation
}

// Unique name to avoid conflict
$trashFilePath = $trashDir . $fileName;
if (file_exists($trashFilePath)) {
    $trashFilePath = $trashDir . time() . "_$fileName";
}

// Move file to trash
if (rename($filePath, $trashFilePath)) {
    echo json_encode(['success' => true, 'message' => 'File moved to trash']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to move file']);
}
