<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
require_roles(['super_admin','clinic_admin']);
require_permission('system.data_integrity.view', ['super_admin','clinic_admin']);
require_once DENTAL_ROOT . '/app/data_integrity.php';
require_once DENTAL_ROOT . '/app/module_helpers.php';

$pdo = db();
$readOnlyPreview = function_exists('task_preview_mode') && task_preview_mode();
$canMaintain = actual_role() === 'super_admin' && active_role() === 'super_admin' && !$readOnlyPreview;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        verify_csrf();
        if ($readOnlyPreview) throw new RuntimeException('Return to the signed-in administrator workspace before recording or maintaining integrity evidence.');
        $action = trim((string)($_POST['action'] ?? ''));
        if ($action === 'record_snapshot') {
            $snapshot = dental_data_integrity_snapshot($pdo);
            $id = dental_data_integrity_record_snapshot($pdo,$snapshot);
            audit_required('data_integrity_snapshot_recorded','system',$id,[
                'overall'=>(string)$snapshot['overall'],
                'counts'=>(array)$snapshot['counts'],
                'fingerprint'=>(string)$snapshot['fingerprint'],
            ]);
            flash((string)$snapshot['overall']==='blocked'?'error':'success','Data-integrity evidence snapshot recorded.');
        } elseif ($action === 'recover_stale') {
            if (!$canMaintain) throw new RuntimeException('Only the signed-in Superuser workspace can recover stale request-ledger entries.');
            $count = dental_data_integrity_recover_stale_operations($pdo);
            audit_required('data_integrity_stale_operations_recovered','system',null,['count'=>$count]);
            flash('success',$count . ' stale request-ledger entr' . ($count===1?'y was':'ies were') . ' marked failed and made retryable.');
        } elseif ($action === 'purge_metadata') {
            if (!$canMaintain) throw new RuntimeException('Only the signed-in Superuser workspace can purge old request-integrity metadata.');
            $days = max(30,min(3650,(int)($_POST['retention_days'] ?? 90)));
            $count = dental_data_integrity_purge_operation_metadata($pdo,$days);
            audit_required('data_integrity_operation_metadata_purged','system',null,['count'=>$count,'retention_days'=>$days]);
            flash('success',$count . ' completed request-ledger entr' . ($count===1?'y was':'ies were') . ' removed. Clinical and financial records were not changed.');
        } else {
            throw new RuntimeException('Unknown data-integrity action.');
        }
    } catch (Throwable $exception) {
        flash('error',$exception->getMessage());
    }
    header('Location: data-integrity-center');
    exit;
}

$snapshot = dental_data_integrity_snapshot($pdo);
$history = dental_data_integrity_recent_snapshots($pdo,20);
$tableReady = dental_data_integrity_table_ready();

if ((string)($_GET['export'] ?? '') === 'csv') {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="dentalcare-data-integrity-' . date('Ymd-His') . '.csv"');
    echo "\xEF\xBB\xBF";
    $out = fopen('php://output','wb');
    fputcsv($out,['Generated','Release','Installed','Overall','Fingerprint']);
    fputcsv($out,[(string)$snapshot['generated_at'],(string)$snapshot['release'],(string)$snapshot['installed'],(string)$snapshot['overall'],(string)$snapshot['fingerprint']]);
    fputcsv($out,[]);
    fputcsv($out,['Category','Check','Status','Metric','Detail']);
    foreach ((array)$snapshot['checks'] as $check) {
        fputcsv($out,[(string)$check['category'],(string)$check['label'],(string)$check['status'],(string)$check['metric'],(string)$check['detail']]);
    }
    fclose($out);
    exit;
}

require DENTAL_ROOT . '/app/layout.php';
$statusLabel = ['pass'=>'Ready','review'=>'Review required','blocked'=>'Blocked'][(string)$snapshot['overall']] ?? 'Review required';
render_header('Data Integrity Center');
?>
<section class="admin-hero card">
    <div>
        <span class="eyebrow">System &amp; Recovery</span>
        <h2>Production Data Integrity Center</h2>
        <p>Verify database transaction support, strict SQL behavior, parent-child relationships, duplicate identifiers, joined-query safety, and critical workflow transaction boundaries. Live checks are read-only.</p>
        <div class="status-actions">
            <a class="btn ghost" href="transaction-integrity">Transaction Integrity</a>
            <a class="btn ghost" href="operational-health">Operational Health</a>
            <a class="btn ghost" href="data-integrity-center?export=csv">Export live evidence</a>
        </div>
    </div>
    <div class="admin-hero-icon"><?=dental_icon('shield')?></div>
</section>

<section class="stats mini-stats">
    <?php stat_card('Overall',$statusLabel,'Generated ' . date('M j, Y g:i A',strtotime((string)$snapshot['generated_at']))); ?>
    <?php stat_card('Passed',(string)$snapshot['counts']['pass'],'Contracts and checks clear'); ?>
    <?php stat_card('Review',(string)$snapshot['counts']['review'],'Authorized reconciliation needed'); ?>
    <?php stat_card('Blocked',(string)$snapshot['counts']['blocked'],'Core database/query contract failure'); ?>
</section>

<?php if(!$tableReady):?>
<div class="alert warning"><strong>Evidence history is not installed.</strong> Live checks remain available, but snapshot recording requires the v1.0.0.0 migration. <a href="system-setup?tab=updates">Open Updates &amp; Database</a>.</div>
<?php endif;?>

<section class="card">
    <div class="card-head"><div><h2>Live integrity contracts</h2><p>Blocked findings affect safe transactional operation. Review findings identify records or server settings requiring controlled follow-up; this page never edits business records.</p></div>
    <div class="button-row">
        <?php if($tableReady):?><form method="post"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="record_snapshot"><button class="btn primary">Record evidence</button></form><?php endif;?>
    </div></div>
    <div class="table-wrap"><table><thead><tr><th>Category</th><th>Check</th><th>Status</th><th>Metric</th><th>Details</th><th>Action</th></tr></thead><tbody>
    <?php foreach((array)$snapshot['checks'] as $check):$state=(string)$check['status'];$badge=$state==='pass'?'badge success':($state==='blocked'?'badge danger':'badge warning');$link=trim((string)($check['link']??''));?>
    <tr>
        <td><?=e((string)$check['category'])?></td>
        <td><strong><?=e((string)$check['label'])?></strong></td>
        <td><span class="<?=$badge?>"><?=e(ucfirst($state))?></span></td>
        <td><?=e((string)$check['metric'])?></td>
        <td><?=e((string)$check['detail'])?></td>
        <td><?=$link!==''?'<a class="btn ghost compact" href="'.e($link).'">Open</a>':'—'?></td>
    </tr>
    <?php endforeach;?>
    </tbody></table></div>
</section>

<section class="card">
    <div class="card-head"><div><h2>Safe request-ledger maintenance</h2><p>These actions affect only duplicate-submission metadata. They do not delete or alter appointments, clinical records, invoices, payments, inventory, or audit entries.</p></div></div>
    <?php if($canMaintain):?>
    <div class="form-grid">
        <form method="post" class="card compact-card"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="recover_stale"><h3>Recover expired processing rows</h3><p>Marks expired request-ledger rows as failed so the same operation can be retried safely.</p><button class="btn primary" data-confirm="Recover expired request-ledger entries? Business records will not be changed.">Recover stale entries</button></form>
        <form method="post" class="card compact-card"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="purge_metadata"><h3>Retain request metadata</h3><label>Keep completed entries for<select name="retention_days"><option value="90">90 days</option><option value="180">180 days</option><option value="365">365 days</option></select></label><button class="btn ghost" data-confirm="Remove completed request-integrity metadata older than the selected retention period?">Apply retention</button></form>
    </div>
    <?php else:?><div class="alert info">Maintenance actions require the signed-in Superuser workspace. Clinic administrators retain full read and evidence-snapshot access.</div><?php endif;?>
</section>

<section class="card">
    <div class="card-head"><div><h2>Recorded evidence</h2><p>Each snapshot stores the result set and a SHA-256 fingerprint for release and recovery review.</p></div></div>
    <div class="table-wrap"><table><thead><tr><th>Recorded</th><th>Release alignment</th><th>Status</th><th>Counts</th><th>Fingerprint</th><th>Recorded by</th></tr></thead><tbody>
    <?php foreach($history as $row):$state=(string)$row['overall_status'];$badge=$state==='pass'?'badge success':($state==='blocked'?'badge danger':'badge warning');?>
    <tr><td><?=e(date('M j, Y g:i A',strtotime((string)$row['created_at'])))?></td><td><?=e((string)$row['installed_version'])?> / <?=e((string)$row['release_version'])?></td><td><span class="<?=$badge?>"><?=e(ucfirst($state))?></span></td><td><?=(int)$row['pass_count']?> pass · <?=(int)$row['review_count']?> review · <?=(int)$row['blocked_count']?> blocked</td><td><code><?=e(substr((string)$row['fingerprint_sha256'],0,16))?>…</code></td><td><?=e((string)($row['creator_name']?:'System'))?></td></tr>
    <?php endforeach;if(!$history):?><tr><td colspan="6" class="muted">No data-integrity evidence snapshots have been recorded.</td></tr><?php endif;?>
    </tbody></table></div>
</section>
<?php render_footer(); ?>
