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

// Define paths
$productsFile = '../js/products.json';
$backupDir = '../js/backups/';

// Get all backup files
$backupFiles = glob($backupDir . '*.json');

// Sort by modification time (newest first)
usort($backupFiles, function($a, $b) {
    return filemtime($b) - filemtime($a);
});

// If no backups found
if (empty($backupFiles)) {
    echo json_encode([
        'success' => false,
        'message' => 'No backup files found'
    ]);
    exit;
}

// Get the latest backup
$latestBackup = $backupFiles[0];

// Read backup content
$backupContent = file_get_contents($latestBackup);
$backupProducts = json_decode($backupContent, true);

// Save to products.json
if (file_put_contents($productsFile, json_encode($backupProducts, JSON_PRETTY_PRINT))) {
    echo json_encode([
        'success' => true,
        'message' => 'Products recovered from backup: ' . basename($latestBackup)
    ]);
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Failed to restore products'
    ]);
}
?>