<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
require_roles('super_admin');
if (active_role() !== 'super_admin') {
    http_response_code(403);
    exit('Switch Task View back to Superuser before importing or resetting data.');
}
require DENTAL_ROOT . '/app/Services/DataImportService.php';
require DENTAL_ROOT . '/app/layout.php';

$pdo = db();
$tab = (string) ($_GET['tab'] ?? 'import');
if (!in_array($tab, ['import','history','reset'], true)) $tab = 'import';

function data_tools_schema_ready(PDO $pdo): bool
{
    $required = ['data_import_batches','demo_record_registry','data_reset_logs'];
    $marks = implode(',', array_fill(0, count($required), '?'));
    $names = array_map(static fn(string $name): string => table($name), $required);
    $stmt = $pdo->prepare('SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=? AND table_name IN (' . $marks . ')');
    $stmt->execute(array_merge([(string) app_config('database.name')], $names));
    return (int) $stmt->fetchColumn() === count($required);
}

if (!data_tools_schema_ready($pdo)) {
    flash('error', 'Apply Version 0.5.2 from System Setup before using Data Import & Reset.');
    header('Location: system_setup.php?tab=updates');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        verify_csrf();
        $action = (string) ($_POST['action'] ?? '');
        if ($action === 'preview_import') {
            $stored = DataImportService::storeUpload($_FILES['import_file'] ?? []);
            $parsed = DataImportService::parse($stored['path'], $stored['original']);
            $report = $parsed['report'];
            $counts = [];
            foreach ($report['datasets'] as $type => $dataset) $counts[$type] = (int) $dataset['row_count'];
            $stmt = $pdo->prepare('INSERT INTO `' . table('data_import_batches') . '` (file_name,stored_name,file_type,status,source_count_json,report_json,created_by,created_at) VALUES (?,?,?,"previewed",?,?,?,NOW())');
            $stmt->execute([$stored['original'],$stored['stored'],$stored['extension'],json_encode($counts),json_encode($report, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),(int) current_user()['id']]);
            $batchId = (int) $pdo->lastInsertId();
            audit('data_import_previewed','data_import_batch',$batchId,['file'=>$stored['original'],'counts'=>$counts,'valid'=>$report['valid']]);
            flash($report['valid'] ? 'success' : 'warning', $report['valid'] ? 'Import preview is ready. Review the datasets before importing.' : 'The file was read, but validation errors must be corrected before import.');
            header('Location: data_tools.php?tab=import&batch_id=' . $batchId);
            exit;
        }
        if ($action === 'run_import') {
            $batchId = (int) ($_POST['batch_id'] ?? 0);
            $selected = array_values(array_intersect(['staff','dentists','returning_patients','new_patients'], array_map('strval', (array) ($_POST['datasets'] ?? []))));
            if ($batchId <= 0 || !$selected) throw new RuntimeException('Select at least one validated dataset to import.');
            $stmt = $pdo->prepare('SELECT * FROM `' . table('data_import_batches') . '` WHERE id=?');
            $stmt->execute([$batchId]);
            $batch = $stmt->fetch();
            if (!$batch) throw new RuntimeException('The import batch no longer exists.');
            $pdo->prepare('UPDATE `' . table('data_import_batches') . '` SET status="importing" WHERE id=?')->execute([$batchId]);
            $parsed = DataImportService::parse(DataImportService::storedPath((string) $batch['stored_name']), (string) $batch['file_name']);
            if (!($parsed['report']['valid'] ?? false)) throw new RuntimeException('The import file contains validation errors. Upload a corrected copy.');
            $result = DataImportService::import($pdo, $parsed['datasets'], $batchId, $selected);
            $status = $result['errors'] ? ((array_sum($result['imported']) > 0) ? 'partial' : 'failed') : 'completed';
            $pdo->prepare('UPDATE `' . table('data_import_batches') . '` SET status=?,imported_count_json=?,skipped_count_json=?,report_json=?,completed_at=NOW() WHERE id=?')->execute([
                $status,json_encode($result['imported']),json_encode($result['skipped']),json_encode($result,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE),$batchId
            ]);
            audit('data_import_completed','data_import_batch',$batchId,['status'=>$status,'imported'=>$result['imported'],'skipped'=>$result['skipped'],'errors'=>count($result['errors'])]);
            flash($status === 'completed' ? 'success' : ($status === 'partial' ? 'warning' : 'error'), 'Import finished with status: ' . ucfirst($status) . '.');
            header('Location: data_tools.php?tab=history&batch_id=' . $batchId);
            exit;
        }
        if (in_array($action, ['reset_demo','reset_activity','factory_reset'], true)) {
            $type = ['reset_demo'=>'demo_only','reset_activity'=>'clinic_activity','factory_reset'=>'factory_defaults'][$action];
            $phrases = ['demo_only'=>'REMOVE DEMO DATA','clinic_activity'=>'RESET CLINIC ACTIVITY','factory_defaults'=>'RESET DENTALCARE DATA'];
            $entered = trim((string) ($_POST['confirmation_phrase'] ?? ''));
            if (!hash_equals($phrases[$type], $entered)) throw new RuntimeException('The confirmation phrase does not match.');
            DataImportService::verifyPassword($pdo, (string) ($_POST['current_password'] ?? ''));
            $summary = DataImportService::reset($pdo, $type);
            flash('success', 'Data reset completed. Automatic backup: ' . $summary['backup'] . '.');
            header('Location: data_tools.php?tab=reset');
            exit;
        }
    } catch (Throwable $exception) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        flash('error', $exception->getMessage());
        header('Location: data_tools.php?tab=' . urlencode($tab) . (isset($_POST['batch_id']) ? '&batch_id=' . (int) $_POST['batch_id'] : ''));
        exit;
    }
}

$batchId = (int) ($_GET['batch_id'] ?? 0);
$batch = null;
$preview = null;
if ($batchId > 0) {
    $stmt = $pdo->prepare('SELECT b.*,u.name creator FROM `' . table('data_import_batches') . '` b LEFT JOIN `' . table('users') . '` u ON u.id=b.created_by WHERE b.id=?');
    $stmt->execute([$batchId]);
    $batch = $stmt->fetch();
    if ($batch) $preview = json_decode((string) ($batch['report_json'] ?? ''), true);
}

$history = $pdo->query('SELECT b.*,u.name creator FROM `' . table('data_import_batches') . '` b LEFT JOIN `' . table('users') . '` u ON u.id=b.created_by ORDER BY b.created_at DESC LIMIT 30')->fetchAll();
$resetLogs = $pdo->query('SELECT r.*,u.name performer FROM `' . table('data_reset_logs') . '` r LEFT JOIN `' . table('users') . '` u ON u.id=r.performed_by ORDER BY r.created_at DESC LIMIT 20')->fetchAll();
$demoCounts = [
    'patients' => (int) $pdo->query('SELECT COUNT(*) FROM `' . table('patients') . '` WHERE is_demo=1')->fetchColumn(),
    'users' => (int) $pdo->query('SELECT COUNT(*) FROM `' . table('users') . '` WHERE is_demo=1')->fetchColumn(),
    'requests' => (int) $pdo->query('SELECT COUNT(*) FROM `' . table('appointment_requests') . '` WHERE is_demo=1')->fetchColumn(),
];

render_header('Data Import & Reset');
?>
<div class="tabs setup-tabs">
    <a class="<?= $tab==='import'?'active':'' ?>" href="data_tools.php?tab=import">Import Data</a>
    <a class="<?= $tab==='history'?'active':'' ?>" href="data_tools.php?tab=history">Import History</a>
    <a class="<?= $tab==='reset'?'active':'' ?>" href="data_tools.php?tab=reset">Data Reset</a>
</div>

<?php if ($tab === 'import'): ?>
<section class="card import-hero">
    <div class="card-head"><div><h2>Import demo or clinic records</h2><p>Upload the DentalCare Excel workbook, CSV pack, or an individual CSV file. Records are previewed and validated before they are saved.</p></div></div>
    <form method="post" enctype="multipart/form-data" class="form-grid">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="action" value="preview_import">
        <label class="wide">Excel, CSV, or ZIP file
            <input type="file" name="import_file" accept=".xlsx,.csv,.zip" required>
            <small>Maximum 25 MB. The official demo workbook and CSV pack are supported directly.</small>
        </label>
        <div class="wide actions"><button class="btn primary" type="submit">Upload and preview</button></div>
    </form>
    <div class="alert info"><strong>Recommended order:</strong> Staff → Dentists → Returning Patients → New Patient Requests. A complete workbook or ZIP pack follows this order automatically.</div>
</section>

<?php if ($batch && $preview): ?>
<section class="card">
    <div class="card-head"><div><h2>Preview: <?= e($batch['file_name']) ?></h2><p><?= e((string)($preview['total_rows'] ?? 0)) ?> recognized rows · uploaded by <?= e($batch['creator'] ?? 'Superuser') ?></p></div><span class="badge"><?= e($batch['status']) ?></span></div>
    <?php if (!empty($preview['errors'])): ?><div class="alert error"><strong>Import blocked.</strong><ul><?php foreach ($preview['errors'] as $error): ?><li><?= e($error) ?></li><?php endforeach; ?></ul></div><?php endif; ?>
    <div class="dataset-grid">
        <?php foreach (($preview['datasets'] ?? []) as $type => $dataset): ?>
        <article class="dataset-card">
            <div><h3><?= e($dataset['label'] ?? $type) ?></h3><span><?= (int)($dataset['row_count'] ?? 0) ?> rows</span></div>
            <?php if (!empty($dataset['errors'])): ?><ul class="validation-errors"><?php foreach (array_slice($dataset['errors'],0,8) as $error): ?><li><?= e($error) ?></li><?php endforeach; ?></ul><?php else: ?><span class="status-ok">Ready to import</span><?php endif; ?>
            <?php if (!empty($dataset['sample'])): ?><div class="table-wrap preview-table"><table><thead><tr><?php foreach (array_slice($dataset['headers'],0,6) as $header): ?><th><?= e(str_replace('_',' ',$header)) ?></th><?php endforeach; ?></tr></thead><tbody><?php foreach ($dataset['sample'] as $sample): ?><tr><?php foreach (array_slice($dataset['headers'],0,6) as $header): ?><td><?= e((string)($sample[$header]??'')) ?></td><?php endforeach; ?></tr><?php endforeach; ?></tbody></table></div><?php endif; ?>
        </article>
        <?php endforeach; ?>
    </div>
    <?php if (!empty($preview['valid'])): ?>
    <form method="post" class="import-confirm-form">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="action" value="run_import">
        <input type="hidden" name="batch_id" value="<?= (int)$batch['id'] ?>">
        <h3>Select datasets to import</h3>
        <div class="check-grid"><?php foreach (($preview['datasets'] ?? []) as $type=>$dataset): ?><label class="check-option"><input type="checkbox" name="datasets[]" value="<?=e($type)?>" checked><span><?=e($dataset['label']??$type)?> <small><?= (int)($dataset['row_count']??0) ?> rows</small></span></label><?php endforeach; ?></div>
        <div class="alert warning">Duplicate employee numbers, email addresses, patient numbers, and request references are skipped rather than overwritten. The real Superuser account is never imported or replaced.</div>
        <button class="btn primary" type="submit">Import selected records</button>
    </form>
    <?php endif; ?>
</section>
<?php endif; ?>

<?php elseif ($tab === 'history'): ?>
<section class="card table-wrap"><div class="card-head"><div><h2>Import history</h2><p>Review source files, result counts, skipped duplicates, and row-level errors.</p></div></div>
<table><thead><tr><th>File</th><th>Status</th><th>Source</th><th>Imported</th><th>Skipped</th><th>By</th><th>Date</th><th></th></tr></thead><tbody>
<?php foreach ($history as $item): $source=json_decode((string)$item['source_count_json'],true)?:[];$imported=json_decode((string)$item['imported_count_json'],true)?:[];$skipped=json_decode((string)$item['skipped_count_json'],true)?:[]; ?>
<tr><td><strong><?=e($item['file_name'])?></strong><small><?=e(strtoupper($item['file_type']))?></small></td><td><span class="badge"><?=e($item['status'])?></span></td><td><?=array_sum($source)?></td><td><?=array_sum($imported)?></td><td><?=array_sum($skipped)?></td><td><?=e($item['creator']??'System')?></td><td><?=e(date('M j, Y g:i A',strtotime($item['created_at'])))?></td><td><a href="data_tools.php?tab=history&batch_id=<?=(int)$item['id']?>">Details</a></td></tr>
<?php endforeach; ?><?php if(!$history):?><tr><td colspan="8" class="muted">No import batches yet.</td></tr><?php endif;?></tbody></table></section>
<?php if($batch&&$preview):?><section class="card"><div class="card-head"><div><h2>Batch result</h2><p><?=e($batch['file_name'])?></p></div><span class="badge"><?=e($batch['status'])?></span></div><?php if(isset($preview['details'])):?><div class="table-wrap"><table><thead><tr><th>Dataset</th><th>Row</th><th>Status</th><th>Result</th></tr></thead><tbody><?php foreach($preview['details'] as $detail):?><tr><td><?=e(str_replace('_',' ',$detail['type']))?></td><td><?=e((string)$detail['row'])?></td><td><span class="badge"><?=e($detail['status'])?></span></td><td><?=e($detail['message'])?></td></tr><?php endforeach;?></tbody></table></div><?php else:?><pre class="report-json"><?=e(json_encode($preview,JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES))?></pre><?php endif;?></section><?php endif;?>

<?php else: ?>
<section class="stats"><div class="stat-card"><span>Demo patients</span><strong><?= $demoCounts['patients'] ?></strong><small>Marked safe for demo removal</small></div><div class="stat-card"><span>Demo staff and dentists</span><strong><?= $demoCounts['users'] ?></strong><small>Real Superuser excluded</small></div><div class="stat-card"><span>Demo appointment requests</span><strong><?= $demoCounts['requests'] ?></strong><small>Public test requests</small></div></section>
<div class="reset-grid">
<section class="card reset-card safe"><h2>Remove demo data only</h2><p>Deletes imported demo patients, appointment requests, staff, dentists, and their linked demo records. Real records remain.</p><ul><li>Creates an automatic database backup</li><li>Preserves clinic setup and real accounts</li><li>Skips the signed-in Superuser</li></ul><button class="btn ghost" data-open="reset-demo">Remove demo data</button></section>
<section class="card reset-card caution"><h2>Reset clinic activity</h2><p>Deletes patient and transactional activity while preserving staff accounts, Dentist professional records, clinic settings, services, facilities/chairs, inventory catalog, licensing, SMTP, branding, and permissions.</p><ul><li>Patients and guardians</li><li>Appointments, queue, and clinical records</li><li>Invoices, payments, recalls, and stock transactions</li></ul><button class="btn warning" data-open="reset-activity">Reset clinic activity</button></section>
<section class="card reset-card danger"><h2>Restore factory defaults</h2><p>Clears operational records and removes all non-Superuser accounts and patient/transaction activity while preserving the clinic service catalog and facility/chair directory. The current Superuser and protected installation settings remain.</p><ul><li>Preserves database connection and license</li><li>Preserves SMTP, branding, branches, roles, and permissions</li><li>Re-seeds any missing default services and facilities without wiping existing active services/chairs</li></ul><button class="btn danger" data-open="reset-factory">Restore factory defaults</button></section>
</div>
<section class="card table-wrap"><h2>Reset history</h2><table><thead><tr><th>Reset type</th><th>Automatic backup</th><th>Performed by</th><th>Date</th></tr></thead><tbody><?php foreach($resetLogs as $log):?><tr><td><strong><?=e(ucwords(str_replace('_',' ',$log['reset_type'])))?></strong></td><td><?=e($log['backup_file'])?></td><td><?=e($log['performer']??'System')?></td><td><?=e(date('M j, Y g:i A',strtotime($log['created_at'])))?></td></tr><?php endforeach;?><?php if(!$resetLogs):?><tr><td colspan="4" class="muted">No resets have been performed.</td></tr><?php endif;?></tbody></table></section>

<?php
$dialogs=[
 ['reset-demo','reset_demo','Remove demo data only','REMOVE DEMO DATA','This removes only records marked as demo.'],
 ['reset-activity','reset_activity','Reset clinic activity','RESET CLINIC ACTIVITY','This permanently removes all patient and transactional activity.'],
 ['reset-factory','factory_reset','Restore factory defaults','RESET DENTALCARE DATA','This removes all non-Superuser accounts and custom operational data.'],
];foreach($dialogs as [$id,$action,$title,$phrase,$message]):?>
<dialog id="<?=e($id)?>"><form method="post" class="form-grid destructive-form"><button type="button" class="dialog-close" data-close>×</button><h2 class="wide"><?=e($title)?></h2><div class="alert warning wide"><?=e($message)?> An automatic SQL backup is created first.</div><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="<?=e($action)?>"><label class="wide">Current Superuser password<input type="password" name="current_password" autocomplete="current-password" required></label><label class="wide">Type <code><?=e($phrase)?></code><input name="confirmation_phrase" autocomplete="off" required></label><button class="btn danger" type="submit">Confirm <?=e($title)?></button></form></dialog>
<?php endforeach; ?>
<?php endif; ?>
<?php render_footer(); ?>
