<?php
// Domains & DNS — server renders the shell only; all mutations go through
// /api/dns-ajax.php (see js/dns-manager.js). Multi-entry MX/NS/SRV handled
// RRset-aware server-side.
require_once('/docker/whp/web/libs/mysqlmgmt.php');
require_once('/docker/whp/web/libs/pdns-integration.php');

$is_root = (defined('AUTH_USER') && AUTH_USER === 'root');
$MySQLMgmt = new mysqlmgmt();
$db = $MySQLMgmt->getMySQLConnection();

// Server settings: default TTL now falls back to 300 (was 3600).
$server_settings = [];
if (file_exists('/docker/whp/settings.json')) {
    $server_settings = json_decode((string)@file_get_contents('/docker/whp/settings.json'), true) ?: [];
}
$default_ttl = max(300, intval($server_settings['default_ttl'] ?? 300));

try { $pdns = $db ? new PowerDNSIntegration($db) : null; } catch (Exception $e) { $pdns = null; }

// Load domains for the current user (root sees all).
$domains = [];
if ($db) {
    if ($is_root) {
        $stmt = $db->query("SELECT d.id, d.domain_name, d.active, d.username AS owner FROM whp.domains d ORDER BY d.domain_name ASC");
        $domains = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $stmt = $db->prepare("SELECT d.id, d.domain_name, d.active, d.username AS owner FROM whp.domains d WHERE d.username = ? ORDER BY d.domain_name ASC");
        $stmt->execute([AUTH_USER]);
        $domains = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

$available_users = [];
if ($is_root && $db) {
    $available_users = $db->query("SELECT username FROM whp.client_allowances ORDER BY username ASC")->fetchAll(PDO::FETCH_COLUMN);
}

$selected_domain = $_GET['domain'] ?? '';
$current = null;
foreach ($domains as $d) { if ($d['domain_name'] === $selected_domain) { $current = $d; break; } }
if ($selected_domain && !$current) { $selected_domain = ''; } // not yours / not found

$record_types = ['A','AAAA','CNAME','MX','TXT','NS','PTR','SRV','CAA','SSHFP','TLSA'];
$csrf = function_exists('get_csrf_token') ? get_csrf_token() : '';
?>
<div id="dns-app"
     data-csrf="<?php echo htmlspecialchars($csrf); ?>"
     data-is-root="<?php echo $is_root ? '1' : '0'; ?>"
     data-default-ttl="<?php echo (int)$default_ttl; ?>"
     data-selected="<?php echo htmlspecialchars($selected_domain); ?>">

  <style>
    /* Fixed layout so the table fills the card width exactly: fixed-width
       control columns, Name a share, and Content takes the remainder and
       truncates long values (TXT/DKIM/SPF) to one line — full value on hover. */
    #dns-records-table { width: 100%; min-width: 720px; table-layout: fixed; }
    #dns-records-table th, #dns-records-table td { vertical-align: middle; }
    #dns-records-table th:nth-child(1), #dns-records-table td:nth-child(1) { width: 40px; }
    #dns-records-table th:nth-child(2), #dns-records-table td:nth-child(2) { width: 96px; }
    #dns-records-table th:nth-child(3), #dns-records-table td:nth-child(3) { width: 22%; }
    #dns-records-table th:nth-child(5), #dns-records-table td:nth-child(5) { width: 72px; }
    #dns-records-table th:nth-child(6), #dns-records-table td:nth-child(6) { width: 84px; }
    #dns-records-table th:nth-child(7), #dns-records-table td:nth-child(7) { width: 140px; }
    #dns-records-table td.dns-name span,
    #dns-records-table td.dns-content code {
      display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
    }
    #dns-records-table td.dns-content code { cursor: help; color: var(--whp-accent); }
    /* Landing: same fill treatment — control columns fixed-width, the Domain
       column takes the remainder and truncates long names (full name on hover). */
    #dns-domains-table { width: 100%; table-layout: fixed; }
    #dns-domains-table th.col-recs,    #dns-domains-table td.col-recs    { width: 130px; }
    #dns-domains-table th.col-owner,   #dns-domains-table td.col-owner   { width: 150px; }
    #dns-domains-table th.col-status,  #dns-domains-table td.col-status  { width: 130px; }
    #dns-domains-table th.col-actions, #dns-domains-table td.col-actions { width: 210px; }
    #dns-domains-table td.dns-dom-name span {
      display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
    }
  </style>

  <!-- LANDING: domains table -->
  <div id="dns-landing" class="<?php echo $selected_domain ? 'd-none' : ''; ?>">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <input type="text" id="dns-domain-search" class="form-control" style="max-width:280px" placeholder="Search domains…">
      <button class="btn btn-primary btn-sm" id="dns-add-domain-btn"><i class="fa fa-plus"></i> Add Domain</button>
    </div>
    <div class="card">
      <div class="card-body p-0">
        <div class="table-responsive">
        <table class="table table-striped mb-0" id="dns-domains-table">
          <thead><tr>
            <th>Domain</th><th class="col-recs">DNS Records</th>
            <?php if ($is_root): ?><th class="col-owner">Owner</th><?php endif; ?>
            <th class="col-status">Status</th><th class="col-actions text-end">Actions</th>
          </tr></thead>
          <tbody>
          <?php foreach ($domains as $d): ?>
            <tr data-domain="<?php echo htmlspecialchars($d['domain_name']); ?>" data-id="<?php echo (int)$d['id']; ?>">
              <td class="fw-semibold dns-dom-name"><span title="<?php echo htmlspecialchars($d['domain_name']); ?>"><?php echo htmlspecialchars($d['domain_name']); ?></span></td>
              <td class="col-recs"><a href="?page=domains&domain=<?php echo urlencode($d['domain_name']); ?>" class="text-decoration-none"><span class="badge bg-secondary dns-rec-count">DNS</span></a></td>
              <?php if ($is_root): ?><td class="col-owner text-truncate"><?php echo htmlspecialchars($d['owner']); ?></td><?php endif; ?>
              <td class="col-status"><?php echo $d['active'] ? '<span class="text-success">● Active</span>' : '<span class="text-muted">● Inactive</span>'; ?></td>
              <td class="col-actions text-end">
                <a class="btn btn-primary btn-sm" href="?page=domains&domain=<?php echo urlencode($d['domain_name']); ?>">Manage DNS <i class="fa fa-arrow-right"></i></a>
                <button class="btn btn-outline-danger btn-sm dns-delete-domain" data-domain="<?php echo htmlspecialchars($d['domain_name']); ?>" data-id="<?php echo (int)$d['id']; ?>"><i class="fa fa-trash"></i></button>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
        </div>
        <?php if (empty($domains)): ?><div class="alert alert-info m-3">No domains yet — add your first with the button above.</div><?php endif; ?>
      </div>
    </div>
  </div>

  <!-- DRILL-IN: DNS records for one domain -->
  <div id="dns-records-view" class="<?php echo $selected_domain ? '' : 'd-none'; ?>">
    <nav class="mb-2" style="font-size:.85rem;opacity:.8">
      <a href="?page=domains" id="dns-breadcrumb-back" class="text-decoration-none">Domains &amp; DNS</a>
      &rsaquo; <span id="dns-crumb-domain"><?php echo htmlspecialchars($selected_domain); ?></span> &rsaquo; DNS Records
    </nav>
    <div class="card">
      <div class="card-header d-flex justify-content-between align-items-center">
        <strong>DNS Records — <span id="dns-current-domain"><?php echo htmlspecialchars($selected_domain); ?></span></strong>
        <div>
          <select id="dns-type-filter" class="form-select form-select-sm d-inline-block" style="width:auto"><option value="">All types</option><?php foreach ($record_types as $t): ?><option value="<?php echo $t; ?>"><?php echo $t; ?></option><?php endforeach; ?></select>
          <button class="btn btn-primary btn-sm" id="dns-add-record-btn"><i class="fa fa-plus"></i> Add Record</button>
        </div>
      </div>
      <div id="dns-bulk-bar" class="card-header bg-primary text-white d-none d-flex justify-content-between align-items-center">
        <span><span id="dns-bulk-count">0</span> selected</span>
        <span>
          <button class="btn btn-sm btn-light" id="dns-bulk-ttl">Change TTL</button>
          <button class="btn btn-sm btn-light" id="dns-bulk-toggle">Enable/Disable</button>
          <button class="btn btn-sm btn-danger" id="dns-bulk-delete">Delete</button>
          <button class="btn btn-sm btn-outline-light" id="dns-bulk-clear">Clear</button>
        </span>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
        <table class="table table-hover mb-0" id="dns-records-table">
          <thead><tr>
            <th style="width:32px"><input type="checkbox" id="dns-select-all"></th>
            <th class="dns-sort" data-sort="type">Type</th>
            <th class="dns-sort" data-sort="name">Name</th>
            <th class="dns-sort" data-sort="content">Content</th>
            <th>Prio</th><th class="dns-sort" data-sort="ttl">TTL</th><th class="text-end">Actions</th>
          </tr></thead>
          <tbody id="dns-records-body"><tr><td colspan="7" class="text-center text-muted p-4">Loading…</td></tr></tbody>
        </table>
        </div>
      </div>
    </div>
  </div>
</div>

<div id="dns-toast" class="position-fixed bottom-0 end-0 p-3" style="z-index:1080"></div>

<script>
  window.DNS_RECORD_TYPES = <?php echo json_encode($record_types); ?>;
  window.DNS_USERS = <?php echo json_encode($available_users); ?>;
</script>
<script src="/js/dns-manager.js"></script>
