<?php
require_once __DIR__ . '/../lib/core.php';
dc_require_login();
dc_require_csrf();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = isset($_POST['action']) ? $_POST['action'] : 'save';
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    if ($action === 'delete' && $id > 0) {
        $stmt = dc_db()->prepare('DELETE FROM door_cert_standards WHERE id=?');
        $stmt->execute(array($id));
        if ($stmt->rowCount() > 0) {
            dc_flash('success', 'Standard deleted. Existing doors keep their saved standard text.');
        } else {
            dc_flash('error', 'Standard was not found or was already deleted.');
        }
        dc_redirect('admin/standards.php');
    }
    $name = trim(isset($_POST['name']) ? $_POST['name'] : '');
    $isActive = !empty($_POST['is_active']) ? 1 : 0;
    if ($name === '') {
        dc_flash('error', 'Enter a standard name.');
    } elseif ($id > 0) {
        $stmt = dc_db()->prepare('UPDATE door_cert_standards SET name=?, is_active=? WHERE id=?');
        $stmt->execute(array($name, $isActive, $id));
        dc_flash('success', 'Standard updated.');
    } else {
        $stmt = dc_db()->prepare('INSERT INTO door_cert_standards (name, is_active) VALUES (?, ?)');
        $stmt->execute(array($name, $isActive));
        dc_flash('success', 'Standard added.');
    }
    dc_redirect('admin/standards.php');
}

$edit = null;
if (isset($_GET['edit'])) {
    $stmt = dc_db()->prepare('SELECT * FROM door_cert_standards WHERE id=?');
    $stmt->execute(array((int)$_GET['edit']));
    $edit = $stmt->fetch();
}
$standards = dc_db()->query('SELECT * FROM door_cert_standards ORDER BY is_active DESC, name')->fetchAll();

dc_admin_header('Standards');
?>
<div class="dc-card">
  <h2><?php echo $edit ? 'Edit Standard' : 'Add Standard'; ?></h2>
  <form method="post">
    <?php echo dc_csrf_field(); ?>
    <input type="hidden" name="id" value="<?php echo dc_h($edit ? $edit['id'] : 0); ?>">
    <label>Standard Name</label>
    <input name="name" value="<?php echo dc_h($edit ? $edit['name'] : ''); ?>" required>
    <label class="dc-check"><input type="checkbox" name="is_active" value="1" <?php echo (!$edit || (int)$edit['is_active'] === 1) ? 'checked' : ''; ?>> Active</label>
    <p><button type="submit">Save Standard</button></p>
  </form>
</div>
<div class="dc-card">
  <h2>Existing Standards</h2>
  <table><tr><th>Standard</th><th>Status</th><th>Used On Doors</th><th></th></tr>
    <?php foreach ($standards as $standard): ?>
      <?php
        $countStmt = dc_db()->prepare('SELECT COUNT(*) FROM door_cert_doors WHERE standards LIKE ?');
        $countStmt->execute(array('%' . $standard['name'] . '%'));
        $used = (int)$countStmt->fetchColumn();
      ?>
      <tr>
        <td><?php echo dc_h($standard['name']); ?></td>
        <td><?php echo (int)$standard['is_active'] === 1 ? 'Active' : 'Inactive'; ?></td>
        <td><?php echo $used; ?></td>
        <td class="dc-row-actions">
          <a href="standards.php?edit=<?php echo (int)$standard['id']; ?>">Edit</a>
          <form method="post" class="dc-inline-form" onsubmit="return confirm('Delete this standard option? Existing doors keep their saved standard text.');">
            <?php echo dc_csrf_field(); ?>
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="id" value="<?php echo (int)$standard['id']; ?>">
            <button type="submit" class="dc-link-button danger">Delete</button>
          </form>
        </td>
      </tr>
    <?php endforeach; ?>
  </table>
</div>
<?php dc_footer(); ?>
