<?php
defined('ABSPATH') || exit;
// phpcs:disable WordPress.Security.NonceVerification,WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound,WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
$current = 'fortisrestore-' . $page;
$titles = ['backups' => 'Backups', 'restore' => 'Restore', 'settings' => 'Settings'];
if (!empty($_GET['fortis_notice'])) {
    echo '<div class="notice notice-' . (sanitize_key(wp_unslash($_GET['fortis_type'] ?? '')) === 'error' ? 'error' : 'success') . ' is-dismissible"><p>' . esc_html(sanitize_text_field(wp_unslash($_GET['fortis_notice']))) . '</p></div>';
}
?>
<div class="wrap fortis-wrap">
<?php require __DIR__ . '/sidebar.php'; ?>
<main>
<header><div><small>FORTISRESTORE FREE</small><h1><?php echo  esc_html($titles[$page] ?? 'FortisRestore') ?></h1><p>Backup. Protect. Restore.</p></div><span class="fortis-status">FREE</span></header>

<?php if ($page === 'backups'): $active = $job->active(); ?>
<section class="fortis-panel"><div class="fortis-panel-head"><div><h2>Encrypted recovery points</h2><p><?php echo  count($archives) ?> local WordPress recovery point<?php echo  count($archives) === 1 ? '' : 's' ?>.</p></div><button id="fortis-create" <?php echo  $active ? 'disabled' : '' ?>>Create Backup</button></div><div id="fortis-progress" class="fortis-progress" <?php echo  $active ? '' : 'hidden' ?> data-job="<?php echo  esc_attr($active['id'] ?? '') ?>"><div><span style="width:<?php echo  (int) ($active['percent'] ?? 0) ?>%"></span></div><p><?php echo  esc_html($active['message'] ?? 'Preparing backup') ?></p></div><div class="fortis-table"><table><thead><tr><th>Archive</th><th>Date</th><th>Size</th><th>Status</th><th></th></tr></thead><tbody><?php if (!$archives): ?><tr><td colspan="5" class="empty">No WordPress backups yet.</td></tr><?php endif; ?><?php foreach ($archives as $archive): ?><tr><td><b><?php echo  esc_html($archive['name']) ?></b></td><td><?php echo  esc_html(gmdate('M j, Y g:i A', $archive['created'])) ?> UTC</td><td><?php echo  esc_html(size_format($archive['size'], 2)) ?></td><td><span class="verified"><?php echo  $archive['verified'] ? 'Verified' : 'Invalid' ?></span></td><td><a href="<?php echo  esc_url(wp_nonce_url(admin_url('admin-post.php?action=fortis_download&file=' . rawurlencode($archive['name'])), 'fortis_download')) ?>">Download</a><a class="delete" onclick="return confirm('Delete this backup?')" href="<?php echo  esc_url(wp_nonce_url(admin_url('admin-post.php?action=fortis_delete&file=' . rawurlencode($archive['name'])), 'fortis_delete')) ?>">Delete</a></td></tr><?php endforeach; ?></tbody></table></div></section>

<?php elseif ($page === 'restore'): ?>
<section class="fortis-panel fortis-form-panel"><div class="fortis-panel-head"><div><h2>Import recovery point</h2><p>Upload an existing WordPress .fts archive and verify it with its recovery key.</p></div></div><form method="post" enctype="multipart/form-data" action="<?php echo  esc_url(admin_url('admin-post.php')) ?>"><input type="hidden" name="action" value="fortis_upload"><?php wp_nonce_field('fortis_upload'); ?><div class="fortis-fields"><label>Fortis archive<input type="file" name="archive" accept=".fts" required></label><label>Original recovery key<input type="password" name="recovery_key" required></label></div><div class="fortis-submit"><button>Upload &amp; Verify</button></div></form></section>
<section class="fortis-panel fortis-form-panel"><div class="fortis-panel-head"><div><h2>Resumable staging restore</h2><p>Every recovery phase is saved. Leave this screen and Fortis will resume safely when you return.</p></div><span class="fortis-status">RECOVERY 2.0</span></div><form id="fortis-restore-form"><div class="fortis-fields"><label>Recovery point<select name="archive" required><?php foreach ($archives as $archive): ?><option value="<?php echo  esc_attr($archive['name']) ?>"><?php echo  esc_html($archive['name']) ?></option><?php endforeach; ?></select></label><label>Staging folder name<input name="target" placeholder="fortis-staging-test" pattern="[a-z0-9][a-z0-9-]{2,63}" required><small>Created safely inside the WordPress uploads staging area.</small></label><label>Empty destination database<input name="database" placeholder="account_wordpress_staging" required></label></div><div class="fortis-submit"><p>The database must already exist, contain zero tables, and be accessible to this WordPress database user.</p><button id="fortis-restore-start" <?php echo $restoreActive || !FortisRestore_Free::requirements_ok() ? 'disabled' : '' ?>><?php echo $restoreActive ? 'Restore Running' : 'Start Restore' ?></button></div></form><div id="fortis-restore-progress" class="fortis-progress fortis-restore-progress" <?php echo $restoreActive ? '' : 'hidden' ?> data-job="<?php echo esc_attr($restoreActive['id'] ?? '') ?>"><div><span style="width:<?php echo (int) ($restoreActive['percent'] ?? 0) ?>%"></span></div><p><?php echo esc_html($restoreActive['message'] ?? 'Preparing restore') ?></p><div class="fortis-restore-meta"><small data-phase><?php echo esc_html(ucwords(str_replace('_', ' ', $restoreActive['phase'] ?? 'preflight'))) ?></small><small data-percent><?php echo (int) ($restoreActive['percent'] ?? 0) ?>%</small><button type="button" id="fortis-restore-cancel" <?php echo $restoreActive ? '' : 'hidden' ?>>Cancel &amp; Clean Up</button></div></div></section>
<section class="fortis-danger"><div><h2>Safe recovery rules</h2><p>Fortis blocks the live database, refuses non-empty destinations, verifies the result, and removes partial data after failure or cancellation.</p></div><span>STAGING FIRST</span></section>

<?php else: $backup = $settings['backup']; $checks = [
    ['PHP 8.1+', PHP_VERSION_ID >= 80100, PHP_VERSION],
    ['AES-256 ZIP', class_exists('ZipArchive') && defined('ZipArchive::EM_AES_256'), 'Required'],
    ['OpenSSL', extension_loaded('openssl'), 'Required'],
    ['Writable secure storage', is_writable($job->backup_dir()), $job->backup_dir()],
    ['Free disk space', (@disk_free_space($job->backup_dir()) ?: 0) > 268435456, size_format((int) (@disk_free_space($job->backup_dir()) ?: 0), 2)],
]; ?>
<section class="fortis-panel"><div class="fortis-panel-head"><div><h2>System readiness</h2><p>Fortis checks this server before relying on it for recovery.</p></div></div><div class="fortis-table"><table><thead><tr><th>Requirement</th><th>Detected</th><th>Status</th></tr></thead><tbody><?php foreach ($checks as $check): ?><tr><td><b><?php echo  esc_html($check[0]) ?></b></td><td><?php echo  esc_html($check[2]) ?></td><td><span class="verified"><?php echo  $check[1] ? 'Ready' : 'Action needed' ?></span></td></tr><?php endforeach; ?></tbody></table></div></section>
<section class="fortis-panel fortis-form-panel"><div class="fortis-panel-head"><div><h2>Backup scope</h2><p>Exclude disposable or site-specific paths without weakening the recovery point.</p></div></div><form method="post" action="<?php echo  esc_url(admin_url('admin-post.php')) ?>"><input type="hidden" name="action" value="fortis_save_backup_settings"><?php wp_nonce_field('fortis_save_backup_settings'); ?><div class="fortis-fields"><label class="fortis-check"><input type="checkbox" name="exclude_cache" value="1" <?php echo  checked(!empty($backup['exclude_cache']), true, false) ?>> Exclude WordPress cache</label><label class="fortis-check"><input type="checkbox" name="exclude_upgrade" value="1" <?php echo  checked(!empty($backup['exclude_upgrade']), true, false) ?>> Exclude upgrade workspace</label><label>Additional relative paths<textarea name="exclusions" rows="5" placeholder="wp-content/uploads/temp"><?php echo  esc_textarea(implode("\n", (array) ($backup['exclusions'] ?? []))) ?></textarea></label></div><div class="fortis-submit"><p>One path per line, relative to the WordPress root.</p><button>Save Backup Scope</button></div></form></section>
<section class="fortis-panel fortis-recovery-panel"><div class="fortis-panel-head"><div><h2>Your Recovery Key</h2><p>Keep it separate from your backups.</p></div><span class="fortis-status">AES-256</span></div><div class="fortis-recovery-actions"><a class="fortis-primary-link" href="<?php echo  esc_url(wp_nonce_url(admin_url('admin-post.php?action=fortis_recovery_key'), 'fortis_recovery_key')) ?>">Download Recovery Key</a></div></section>
<?php endif; ?>
</main></div>
