<?php
/**
 * Test Data Reset Page — Super Admin only
 * Wipes all KPI entries and activity log records so the system is clean for go-live.
 * Accessible only to Sara (super admin). Protected by double-confirm.
 */
$active = 'home';
$pageTitle = 'Reset Test Data';
$admin = \App\Core\Permission::requireSuperAdmin();

use App\Core\Database;

$message = null;
$counts  = [];

// Always show current counts
try {
    $db = Database::connection();
    $counts = [
        'kpi_scheduling_entries' => (int)$db->query("SELECT COUNT(*) FROM kpi_scheduling_entries")->fetchColumn(),
        'cesar_kpi_entries'      => (int)$db->query("SELECT COUNT(*) FROM cesar_kpi_entries")->fetchColumn(),
        'activity_log'           => (int)$db->query("SELECT COUNT(*) FROM activity_log")->fetchColumn(),
        'kpi_entry_audit'        => (int)$db->query("SELECT COUNT(*) FROM kpi_entry_audit")->fetchColumn(),
    ];
} catch (\Throwable $e) {
    $counts = [];
}

// Handle POST reset
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $confirm1 = trim($_POST['confirm_phrase'] ?? '');
    $confirm2 = (bool)($_POST['confirm_checkbox'] ?? false);
    $tables   = $_POST['tables'] ?? [];

    if ($confirm1 !== 'RESET ALL TEST DATA' || !$confirm2) {
        $message = ['type' => 'error', 'text' => 'Confirmation phrase did not match or checkbox was not checked. Nothing was deleted.'];
    } elseif (empty($tables)) {
        $message = ['type' => 'error', 'text' => 'No tables selected. Nothing was deleted.'];
    } else {
        $deleted = [];
        $allowed = ['kpi_scheduling_entries', 'cesar_kpi_entries', 'activity_log', 'kpi_entry_audit'];
        try {
            $db = Database::connection();
            $db->exec("SET FOREIGN_KEY_CHECKS = 0");
            foreach ($tables as $t) {
                if (!in_array($t, $allowed, true)) continue;
                $n = (int)$db->query("SELECT COUNT(*) FROM `$t`")->fetchColumn();
                $db->exec("TRUNCATE TABLE `$t`");
                $deleted[] = "$t ($n rows deleted)";
            }
            $db->exec("SET FOREIGN_KEY_CHECKS = 1");

            // Log this action to audit_log (separate table, not cleared)
            try {
                $db->prepare(
                    "INSERT INTO audit_log (actor_type, actor_id, actor_name, entity, entity_id, action, new_values, created_at)
                     VALUES ('superadmin', :aid, :aname, 'test_data_reset', '0', 'delete', :val, NOW())"
                )->execute([
                    'aid'   => $admin['user_id'],
                    'aname' => $admin['name'],
                    'val'   => json_encode(['tables_cleared' => $deleted]),
                ]);
            } catch (\Throwable $e) { /* audit_log may have different schema - silent */ }

            $message = ['type' => 'success', 'text' => 'Successfully cleared: ' . implode(', ', $deleted)];

            // Refresh counts
            $counts = [
                'kpi_scheduling_entries' => 0,
                'cesar_kpi_entries'      => 0,
                'activity_log'           => in_array('activity_log', $tables) ? 0 : $counts['activity_log'],
                'kpi_entry_audit'        => in_array('kpi_entry_audit', $tables) ? 0 : $counts['kpi_entry_audit'],
            ];
        } catch (\Throwable $e) {
            $message = ['type' => 'error', 'text' => 'Error during reset: ' . $e->getMessage()];
        }
    }
}

require __DIR__ . '/../layout/admin_header.php';
?>
<style>
.reset-card { background:#fff;border:1.5px solid var(--border);border-radius:16px;padding:28px 32px;max-width:680px;margin-bottom:22px; }
.reset-card h3 { font-size:15px;font-weight:800;margin:0 0 6px;color:var(--navy-900); }
.count-row { display:flex;justify-content:space-between;align-items:center;padding:10px 0;border-bottom:1px solid var(--border); }
.count-row:last-child { border-bottom:none; }
.count-badge { font-size:18px;font-weight:800;color:var(--navy-900); }
.count-badge.zero { color:var(--success); }
.danger-zone { background:#fef2f2;border:1.5px solid #fca5a5;border-radius:16px;padding:28px 32px;max-width:680px; }
.danger-zone h3 { color:#991b1b;font-size:15px;font-weight:800;margin:0 0 14px; }
</style>

<div class="topbar">
  <div>
    <h1>🧹 Reset Test Data</h1>
    <div class="crumbs">Admin → Test Data Reset</div>
    <div style="font-size:13px;color:#dc2626;font-weight:600;margin-top:4px;">⚠️ This page permanently deletes data. Only use before go-live.</div>
  </div>
  <div class="user-chip"><span class="dot"></span> <?= htmlspecialchars($admin['name']) ?></div>
</div>

<?php if ($message): ?>
<div style="padding:14px 20px;border-radius:12px;margin-bottom:20px;max-width:680px;
  background:<?= $message['type']==='success' ? '#ecfdf5' : '#fef2f2' ?>;
  border:1px solid <?= $message['type']==='success' ? '#6ee7b7' : '#fca5a5' ?>;
  color:<?= $message['type']==='success' ? '#065f46' : '#991b1b' ?>;font-size:14px;font-weight:600;">
  <?= $message['type'] === 'success' ? '✅ ' : '❌ ' ?><?= htmlspecialchars($message['text']) ?>
</div>
<?php endif; ?>

<!-- Current Counts -->
<div class="reset-card">
  <h3>Current Data Counts</h3>
  <p style="font-size:13px;color:var(--text-muted);margin:0 0 16px;">These are the records currently in the system. Green = already empty.</p>
  <?php foreach ([
    'kpi_scheduling_entries' => 'Scheduling KPI Entries (Karan & Harpreet)',
    'cesar_kpi_entries'      => 'Operations Manager KPI Entries (César)',
    'activity_log'           => 'Activity Log',
    'kpi_entry_audit'        => 'KPI Audit Trail',
  ] as $table => $label): ?>
  <div class="count-row">
    <span style="font-size:13px;color:var(--text);"><?= $label ?></span>
    <span class="count-badge <?= ($counts[$table] ?? 0) === 0 ? 'zero' : '' ?>">
      <?= number_format($counts[$table] ?? 0) ?> rows
    </span>
  </div>
  <?php endforeach; ?>
</div>

<!-- What is NOT deleted -->
<div class="reset-card" style="background:#f0fdf4;border-color:#6ee7b7;">
  <h3 style="color:#065f46;">✅ What will NOT be deleted</h3>
  <ul style="font-size:13px;color:#065f46;margin:8px 0 0;padding-left:20px;line-height:2;">
    <li>User accounts (managers, Sara, employees)</li>
    <li>Departments and projects</li>
    <li>Sites list (387+ sites)</li>
    <li>Role assignments and permissions</li>
    <li>System settings and configuration</li>
    <li>Audit log (permanent record — cannot be deleted)</li>
  </ul>
</div>

<!-- Danger Zone Reset Form -->
<div class="danger-zone">
  <h3>🗑️ Delete Test Data</h3>
  <p style="font-size:13px;color:#7f1d1d;margin:0 0 20px;line-height:1.6;">
    Select which tables to clear, then type the confirmation phrase exactly and check the box.
    <strong>This cannot be undone.</strong>
  </p>

  <form method="POST" action="/admin/reset-test-data"
        onsubmit="return document.getElementById('confirmPhrase').value === 'RESET ALL TEST DATA' || (alert('Confirmation phrase does not match.') && false);">

    <div style="margin-bottom:18px;">
      <div style="font-size:12px;font-weight:700;text-transform:uppercase;color:#991b1b;margin-bottom:10px;letter-spacing:.05em;">Select tables to clear:</div>
      <?php foreach ([
        'kpi_scheduling_entries' => 'Scheduling KPI Entries (Karan & Harpreet) — ' . number_format($counts['kpi_scheduling_entries'] ?? 0) . ' rows',
        'cesar_kpi_entries'      => 'Operations Manager KPI Entries (César) — ' . number_format($counts['cesar_kpi_entries'] ?? 0) . ' rows',
        'activity_log'           => 'Activity Log — ' . number_format($counts['activity_log'] ?? 0) . ' rows',
        'kpi_entry_audit'        => 'KPI Audit Trail — ' . number_format($counts['kpi_entry_audit'] ?? 0) . ' rows',
      ] as $t => $lbl): ?>
      <label style="display:flex;align-items:center;gap:10px;margin-bottom:8px;font-size:13px;cursor:pointer;">
        <input type="checkbox" name="tables[]" value="<?= $t ?>" style="width:16px;height:16px;">
        <?= htmlspecialchars($lbl) ?>
      </label>
      <?php endforeach; ?>
    </div>

    <div style="margin-bottom:14px;">
      <label style="display:block;font-size:12px;font-weight:700;text-transform:uppercase;color:#991b1b;margin-bottom:6px;letter-spacing:.05em;">
        Type exactly: <code style="background:#fff;padding:2px 8px;border-radius:6px;font-size:13px;">RESET ALL TEST DATA</code>
      </label>
      <input type="text" name="confirm_phrase" id="confirmPhrase" autocomplete="off"
             placeholder="RESET ALL TEST DATA"
             style="width:100%;padding:12px 16px;border:1.5px solid #fca5a5;border-radius:10px;font-size:14px;font-family:monospace;">
    </div>

    <div style="margin-bottom:20px;">
      <label style="display:flex;align-items:center;gap:10px;font-size:13px;cursor:pointer;color:#7f1d1d;">
        <input type="checkbox" name="confirm_checkbox" value="1" style="width:16px;height:16px;">
        I understand this is irreversible and the selected data will be permanently deleted
      </label>
    </div>

    <button type="submit" style="background:#dc2626;color:#fff;border:none;border-radius:10px;padding:13px 28px;font-size:14px;font-weight:700;cursor:pointer;">
      🗑️ Delete Selected Test Data
    </button>
  </form>
</div>

<div style="max-width:680px;margin-top:20px;padding:14px 18px;background:#fffbeb;border:1px solid #fcd34d;border-radius:12px;font-size:13px;color:#92400e;">
  <strong>Recommended go-live checklist:</strong><br>
  1. Clear all KPI entries (both tables)<br>
  2. Clear the activity log<br>
  3. Clear the KPI audit trail<br>
  4. Log out and log back in as each user to confirm clean state<br>
  5. Confirm the team can submit their first real KPI entry
</div>

<?php require __DIR__ . '/../layout/admin_footer.php'; ?>
