<?php
/**
 * Restore a historical upload as the active dataset.
 *
 * IMPORTANT (bug fix): when archiving the CURRENT data during a restore,
 * we tag those archive rows with archived_reason = 'restore_overwrite'.
 * The restore SELECT then filters to archived_reason IN ('replace_all',
 * 'replace_by_period', 'upsert') only — so subsequent restores of the
 * same upload don't pick up duplicates.
 */
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/report-engine.php';

$me = require_login('internal');
if (!user_has_role((int) $me['id'], 'sysadmin')) {
    flash('error', 'Only sysadmin can restore snapshots.');
    redirect('/admin/report-builder.php');
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') redirect('/admin/report-builder.php');
csrf_check_or_die();

$reportId = (int) input('report_id');
$uploadId = (int) input('upload_id');
$pdo = db();

$u = $pdo->prepare('SELECT * FROM report_uploads WHERE id=? AND report_id=?');
$u->execute([$uploadId, $reportId]);
$upload = $u->fetch();
if (!$upload) { flash('error','Upload not found.'); redirect('/admin/upload.php?report_id=' . $reportId); }

$pdo->beginTransaction();
try {
    /* 1. Archive whatever is currently active, with a special marker so future
     *    restores DO NOT pull it back as if it were original-upload data. */
    $pdo->prepare('INSERT INTO report_data_archive
        (report_id, upload_id, original_upload_id, row_index, period_label, key_hash, data_json, is_active, archived_at, archived_reason, created_at)
        SELECT report_id, ?, upload_id, row_index, period_label, key_hash, data_json, 0, NOW(), "restore_overwrite", created_at
        FROM report_data WHERE report_id=?')
        ->execute([$uploadId, $reportId]);

    $pdo->prepare('DELETE FROM report_data WHERE report_id=?')->execute([$reportId]);

    /* 2. Re-activate snapshot rows from archive — ONLY rows that came from
     *    a real upload event (not from a previous restore_overwrite). */
    $pdo->prepare("INSERT INTO report_data
        (report_id, upload_id, row_index, period_label, key_hash, data_json, is_active, created_at)
        SELECT report_id, ?, row_index, period_label, key_hash, data_json, 1, created_at
        FROM report_data_archive
        WHERE report_id=? AND original_upload_id=?
              AND archived_reason IN ('replace_all','replace_by_period','upsert')")
        ->execute([$uploadId, $reportId, $uploadId]);

    $pdo->commit();
} catch (Throwable $t) {
    $pdo->rollBack();
    flash('error', 'Restore failed: ' . $t->getMessage());
    redirect('/admin/upload.php?report_id=' . $reportId);
}

audit_log('report.snapshot.restore', 'report', $reportId, null, ['restored_from' => $uploadId]);

try {
    $engine = new ReportEngine($reportId);
    $engine->materializeOutputs($uploadId);
} catch (Throwable $t) { /* non-fatal */ }

flash('success', 'Snapshot restored. Outputs re-generated.');
redirect('/admin/report-view.php?id=' . $reportId);
