<?php
require_once __DIR__ . '/../../app/helpers/functions.php';
require_once __DIR__ . '/../../app/helpers/csrf.php';
require_once __DIR__ . '/../../app/middleware/auth.php';

session_boot();
require_login();

$conn = require __DIR__ . '/../../app/config/database.php';
require_admin($conn);
$admin = current_user();

/* ===============================
   TOGGLE ENABLE / DISABLE (SAFE)
================================ */
if (is_post() && isset($_POST['toggle_id'])) {
  csrf_verify();

  $id = (int)$_POST['toggle_id'];

  // Do not toggle already-used codes
  $st = $conn->prepare("SELECT used FROM wire_codes WHERE id=? LIMIT 1");
  $st->bind_param("i", $id);
  $st->execute();
  $row = $st->get_result()->fetch_assoc();

  if (!$row) {
    flash('err', 'Code not found');
  } elseif ((int)$row['used'] === 1) {
    flash('err', 'Used codes cannot be disabled');
  } else {
    $conn->query("UPDATE wire_codes SET enabled = IF(enabled=1,0,1) WHERE id=$id");
    flash('msg', 'Code status updated');
  }

  redirect('wire_codes.php');
}

/* ===============================
   CREATE CODE
================================ */
if (is_post() && isset($_POST['create_code'])) {
  csrf_verify();

  $userId = (int)$_POST['user_id'];
  $type   = $_POST['type'];

  if (!in_array($type, ['vat','tax','imf'], true)) {
    flash('err', 'Invalid code type');
    redirect('wire_codes.php');
  }

  $code = strtoupper(bin2hex(random_bytes(4))); // secure 8 chars

  $st = $conn->prepare("
    INSERT INTO wire_codes (user_id, code, type, created_by)
    VALUES (?,?,?,?)
  ");
  $st->bind_param("issi", $userId, $code, $type, $admin['id']);
  $st->execute();

  flash('msg', "Code generated: $code");
  redirect('wire_codes.php');
}

/* ===============================
   LOAD DATA
================================ */
$users = $conn->query("SELECT id, full_name, email FROM users ORDER BY id DESC");

$codes = $conn->query("
  SELECT wc.*, u.full_name
  FROM wire_codes wc
  JOIN users u ON u.id = wc.user_id
  ORDER BY wc.id DESC
");

include __DIR__ . '/../../views/partials/head.php';
include __DIR__ . '/../../views/partials/admin_sidebar.php';
?>

<div class="container py-4">

  <?php if ($m = flash('msg')): ?>
    <div class="alert alert-success"><?= e($m) ?></div>
  <?php endif; ?>

  <?php if ($m = flash('err')): ?>
    <div class="alert alert-danger"><?= e($m) ?></div>
  <?php endif; ?>

  <!-- ================= CREATE CODE ================= -->
  <div class="card ab-card p-4 mb-4" style="max-width:520px">
    <h5 class="fw-bold mb-3">Generate Wire Code</h5>

    <form method="post">
      <?= csrf_field() ?>
      <input type="hidden" name="create_code" value="1">

      <label class="form-label">User</label>
      <select name="user_id" class="form-select mb-2" required>
        <?php while ($u = $users->fetch_assoc()): ?>
          <option value="<?= (int)$u['id'] ?>">
            <?= e($u['full_name']) ?> (<?= e($u['email']) ?>)
          </option>
        <?php endwhile; ?>
      </select>

      <label class="form-label">Code Type</label>
      <select name="type" class="form-select mb-3">
        <option value="vat">VAT Code</option>
        <option value="tax">Tax Code</option>
        <option value="imf">IMF Code</option>
      </select>

      <button class="btn ab-btn text-white w-100">
        Generate Code
      </button>
    </form>
  </div>

  <!-- ================= ISSUED CODES ================= -->
  <div class="card ab-card p-4">
    <h5 class="fw-bold mb-3">Issued Codes</h5>

    <table class="table table-sm align-middle">
      <thead>
        <tr>
          <th>User</th>
          <th>Code</th>
          <th>Type</th>
          <th>Usage</th>
          <th>Status</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <?php while ($c = $codes->fetch_assoc()): ?>
          <tr>
            <td><?= e($c['full_name']) ?></td>

            <td><b><?= e($c['code']) ?></b></td>

            <td><?= strtoupper(e($c['type'])) ?></td>

            <td>
              <?= $c['used']
                ? '<span class="badge bg-secondary">Used</span>'
                : '<span class="badge bg-info">Unused</span>' ?>
            </td>

            <td>
              <?= $c['enabled']
                ? '<span class="badge bg-success">Enabled</span>'
                : '<span class="badge bg-danger">Disabled</span>' ?>
            </td>

            <td>
              <?php if (!$c['used']): ?>
                <form method="post" class="d-inline">
                  <?= csrf_field() ?>
                  <input type="hidden" name="toggle_id" value="<?= (int)$c['id'] ?>">
                  <button class="btn btn-sm btn-outline-secondary">
                    <?= $c['enabled'] ? 'Disable' : 'Enable' ?>
                  </button>
                </form>
              <?php else: ?>
                <span class="text-muted small">Locked</span>
              <?php endif; ?>
            </td>
          </tr>
        <?php endwhile; ?>
      </tbody>
    </table>
  </div>

</div>
