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

$uploadsDir = __DIR__ . '/uploads/transactions';
$transactionId = intval($_POST['transactionId'] ?? 0);
$fileName      = basename($_POST['fileName'] ?? '');
$file          = $_FILES['file'] ?? null;

if (!$transactionId || !$fileName || !$file) {
    echo json_encode(['success' => false, 'message' => 'Missing required fields.']);
    exit;
}

// Allowed file types
$allowedTypes = ['application/pdf', 'image/jpeg', 'image/png', 'image/jpg'];
if (!in_array($file['type'], $allowedTypes)) {
    echo json_encode(['success' => false, 'message' => 'Invalid file type.']);
    exit;
}

// Create target folder if not exists
$targetDir = "$uploadsDir/transaction_$transactionId/warranty";
if (!is_dir($targetDir)) {
    mkdir($targetDir, 0755, true);
}

// Sanitize file name and keep extension
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$targetFile = "$targetDir/$fileName.$ext";

// Move uploaded file
if (move_uploaded_file($file['tmp_name'], $targetFile)) {
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to move uploaded file.']);
}
