<?php
require_once __DIR__ . '/config/config.php';
require_role(['superadmin']); // hard-coded to true superadmin only - deliberately NOT permission-grantable
$u = current_user();

// Tables grouped by what they represent. Master/setup data (items, suppliers,
// outlets, departments, users, chart of accounts, approval workflow config,
// role/user permissions, waste reasons, ar_customers) is never touched here.
$INVENTORY_TABLES = [
    'purchase_requisition_items', 'purchase_requisitions',
    'purchase_order_items', 'purchase_orders',
    'goods_received_items', 'goods_received_notes',
    'return_to_supplier_items', 'return_to_supplier',
    'store_requisition_items', 'store_requisitions',
    'waste_items', 'waste_records',
    'stock_transactions', 'item_batches',
    'main_store_stock', 'outlet_stock',
    'approval_logs',
];
$ACCOUNTING_TABLES = [
    'journal_entry_lines', 'journal_entries',
    'ap_payments', 'ap_bills',
    'ar_receipts', 'ar_invoices',
];

function table_count(PDO $pdo, $table) {
    try { return (int)$pdo->query("SELECT COUNT(*) FROM $table")->fetchColumn(); }
    catch (Exception $e) { return 0; }
}

$requiredPhrase = 'RESET ALL DATA';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $doInventory = isset($_POST['reset_inventory']);
    $doAccounting = isset($_POST['reset_accounting']);
    $phrase = trim($_POST['confirm_phrase'] ?? '');

    if ($phrase !== $requiredPhrase) {
        $error = 'The confirmation phrase did not match exactly. Nothing was deleted.';
    } elseif (!$doInventory && !$doAccounting) {
        $error = 'Select at least one category to reset.';
    } else {
        $tables = [];
        if ($doInventory) $tables = array_merge($tables, $INVENTORY_TABLES);
        if ($doAccounting) $tables = array_merge($tables, $ACCOUNTING_TABLES);
        $tables[] = 'notifications'; // always cleared alongside any reset - old ones point at records being removed

        try {
            $pdo->exec('SET FOREIGN_KEY_CHECKS = 0');
            foreach (array_unique($tables) as $t) {
                $pdo->exec("TRUNCATE TABLE `$t`");
            }
            $pdo->exec('SET FOREIGN_KEY_CHECKS = 1');

            flash('success', 'Test data cleared. Document numbers (PR-, SR-, PO-, etc.) will start fresh from 0001. Master data (items, suppliers, outlets, users, chart of accounts, permissions, approval workflow) was left untouched.');
            redirect('dashboard.php');
        } catch (Exception $ex) {
            $pdo->exec('SET FOREIGN_KEY_CHECKS = 1');
            $error = 'Reset failed: ' . $ex->getMessage();
        }
    }
}

$invCounts = [];
foreach ($INVENTORY_TABLES as $t) { $invCounts[$t] = table_count($pdo, $t); }
$accCounts = [];
foreach ($ACCOUNTING_TABLES as $t) { $accCounts[$t] = table_count($pdo, $t); }
$notifCount = table_count($pdo, 'notifications');

$labels = [
    'purchase_requisition_items' => 'Purchase requisition items', 'purchase_requisitions' => 'Purchase requisitions',
    'purchase_order_items' => 'Purchase order items', 'purchase_orders' => 'Purchase orders',
    'goods_received_items' => 'Goods received items', 'goods_received_notes' => 'Goods received notes',
    'return_to_supplier_items' => 'Return-to-supplier items', 'return_to_supplier' => 'Return-to-supplier records',
    'store_requisition_items' => 'Store requisition items', 'store_requisitions' => 'Store requisitions',
    'waste_items' => 'Waste line items', 'waste_records' => 'Waste records',
    'stock_transactions' => 'Stock ledger entries', 'item_batches' => 'Expiry batches',
    'main_store_stock' => 'Main store stock balances', 'outlet_stock' => 'Outlet stock balances',
    'approval_logs' => 'Approval history entries',
    'journal_entry_lines' => 'Journal entry lines', 'journal_entries' => 'Journal entries',
    'ap_payments' => 'Supplier payments', 'ap_bills' => 'Supplier bills',
    'ar_receipts' => 'Customer receipts', 'ar_invoices' => 'Customer invoices',
];

$pageTitle = 'Reset Test Data';
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-2">Reset Test Data</h1>
<p class="text-slate-500 text-sm mb-6 max-w-2xl">
  Superadmin-only. This permanently deletes all requisitions, purchase orders, goods received notes,
  stock movements, waste records, and (optionally) accounting entries created while testing - so you can
  go live with a clean slate. It does <strong>not</strong> touch your setup: items, categories, units,
  suppliers, outlets, departments, users, permissions, the approval workflow configuration, or the chart
  of accounts.
</p>

<div class="bg-amber-50 border border-amber-300 rounded-xl p-4 mb-6 text-sm text-amber-800">
  ⚠️ <strong>This cannot be undone.</strong> Take a database backup first if there's any chance you'll want
  this data later (phpMyAdmin → Export). Document numbers (PR-2026-0001, etc.) will restart from 0001 for
  whichever categories you clear.
</div>

<?php if ($error): ?>
  <div class="bg-red-50 border border-red-200 text-red-700 text-sm px-4 py-2.5 rounded-lg mb-6"><?= e($error) ?></div>
<?php endif; ?>

<form method="POST" id="resetForm" class="space-y-6">
  <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
    <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-5">
      <label class="flex items-center gap-2 font-semibold mb-3">
        <input type="checkbox" name="reset_inventory" id="chkInventory" checked>
        Inventory & Requisition Data
      </label>
      <ul class="text-sm text-slate-600 space-y-1">
        <?php foreach (['purchase_requisitions','purchase_orders','goods_received_notes','return_to_supplier','store_requisitions','waste_records','stock_transactions','item_batches'] as $t): ?>
          <li class="flex justify-between border-b border-slate-100 py-1">
            <span><?= e($labels[$t]) ?></span>
            <span class="font-mono text-slate-400"><?= number_format($invCounts[$t]) ?></span>
          </li>
        <?php endforeach; ?>
      </ul>
    </div>

    <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-5">
      <label class="flex items-center gap-2 font-semibold mb-3">
        <input type="checkbox" name="reset_accounting" id="chkAccounting" checked>
        Accounting Data (Journal Entries, AP, AR)
      </label>
      <ul class="text-sm text-slate-600 space-y-1">
        <?php foreach (['journal_entries','ap_bills','ap_payments','ar_invoices','ar_receipts'] as $t): ?>
          <li class="flex justify-between border-b border-slate-100 py-1">
            <span><?= e($labels[$t]) ?></span>
            <span class="font-mono text-slate-400"><?= number_format($accCounts[$t]) ?></span>
          </li>
        <?php endforeach; ?>
      </ul>
      <p class="text-xs text-slate-400 mt-3">Leave this unchecked if you want to keep your accounting entries and only clear inventory/requisition test data.</p>
    </div>
  </div>

  <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-5">
    <p class="text-sm text-slate-600 mb-3">
      Notifications (<?= number_format($notifCount) ?> total) will also be cleared, since they link to the records being removed.
    </p>
    <label class="text-sm font-medium block mb-1">
      Type <code class="bg-slate-100 px-1.5 py-0.5 rounded"><?= e($requiredPhrase) ?></code> to confirm
    </label>
    <input type="text" name="confirm_phrase" id="confirmPhrase" autocomplete="off"
      class="w-full max-w-sm border border-slate-300 rounded-lg px-3 py-2 text-sm" placeholder="<?= e($requiredPhrase) ?>">
  </div>

  <button type="submit" id="resetBtn" disabled
    class="bg-red-600 text-white text-sm font-medium px-5 py-2.5 rounded-lg opacity-50 cursor-not-allowed">
    Permanently Delete Selected Data
  </button>
</form>

<script>
const phraseInput = document.getElementById('confirmPhrase');
const resetBtn = document.getElementById('resetBtn');
const requiredPhrase = <?= json_encode($requiredPhrase) ?>;
function updateButtonState() {
  const matches = phraseInput.value === requiredPhrase;
  resetBtn.disabled = !matches;
  resetBtn.classList.toggle('opacity-50', !matches);
  resetBtn.classList.toggle('cursor-not-allowed', !matches);
}
phraseInput.addEventListener('input', updateButtonState);

document.getElementById('resetForm').addEventListener('submit', function (e) {
  if (!confirm('This will permanently delete the selected data. This cannot be undone. Continue?')) {
    e.preventDefault();
  }
});
</script>
<?php include __DIR__ . '/includes/footer.php'; ?>
