<?php
// Restore data dari backup file

if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

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

$backupDir = 'backup_data';
$dataDir = 'data';

if (!isset($_FILES['backup']) || $_FILES['backup']['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['error' => 'File upload gagal']);
    exit;
}

$uploadedFile = $_FILES['backup']['tmp_name'];
$zipFile = $backupDir . '/temp_restore.zip';

// Copy file yang di-upload ke backup folder
if (!move_uploaded_file($uploadedFile, $zipFile)) {
    echo json_encode(['error' => 'Gagal menyimpan file']);
    exit;
}

// Extract file backup
$zip = new ZipArchive();
if ($zip->open($zipFile) !== TRUE) {
    unlink($zipFile);
    echo json_encode(['error' => 'Gagal membuka file backup']);
    exit;
}

// Extract ke folder data
if (!$zip->extractTo($dataDir)) {
    $zip->close();
    unlink($zipFile);
    echo json_encode(['error' => 'Gagal extract file backup']);
    exit;
}

$zip->close();
unlink($zipFile);

echo json_encode([
    'success' => true,
    'message' => 'Data berhasil di-restore! Halaman akan refresh otomatis.'
]);
?>
