<?php
/**
 * Gerenciamento de Domínios Personalizados - SuperAdmin
 * Lista lojas com domínios pendentes de ativação
 */
// require_once __DIR__ . '/../../includes/auth.php'; // Removido - usar config.php
require_once __DIR__ . '/../../../includes/config.php';

if (!isSuperAdmin()) { header('Location: /pages/login.php'); exit; }
$pdo = getDB();

// Buscar lojas com domínios personalizados configurados
$stmt = $pdo->query("
    SELECT s.id, s.name, s.slug, s.subdomain, s.custom_domain, s.domain_type, 
           s.status, s.created_at, u.email as owner_email
    FROM stores s
    LEFT JOIN users u ON s.owner_id = u.id
    WHERE s.custom_domain IS NOT NULL 
      AND s.custom_domain != ''
      AND s.deleted_at IS NULL
    ORDER BY s.created_at DESC
");
$stores = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Função para verificar se DNS está apontando corretamente
function checkDNS($domain) {
    $domain = preg_replace('/^www\./', '', $domain);
    $serverIP = '187.33.241.55';
    
    // Verificar registro A
    $aRecords = @dns_get_record($domain, DNS_A);
    $hasA = false;
    if ($aRecords) {
        foreach ($aRecords as $record) {
            if (isset($record['ip']) && $record['ip'] === $serverIP) {
                $hasA = true;
                break;
            }
        }
    }
    
    // Verificar registro CNAME (para www)
    $cnameRecords = @dns_get_record('www.' . $domain, DNS_CNAME);
    $hasCname = false;
    if ($cnameRecords) {
        foreach ($cnameRecords as $record) {
            if (isset($record['target']) && strpos($record['target'], 'duolead.com.br') !== false) {
                $hasCname = true;
                break;
            }
        }
    }
    
    return [
        'a_record' => $hasA,
        'cname_record' => $hasCname,
        'ready' => $hasA
    ];
}

$pageTitle = 'Domínios Personalizados';
include __DIR__ . '/../includes/header.php';
?>

<div class="container">
    <div class="page-header">
        <h1><i class="fas fa-globe"></i> Domínios Personalizados</h1>
        <p>Gerencie os domínios personalizados das lojas</p>
    </div>

    <div class="card">
        <div class="card-header">
            <h3>Lojas com Domínio Personalizado (<?= count($stores) ?>)</h3>
        </div>
        <div class="card-body">
            <?php if (empty($stores)): ?>
                <p class="text-muted">Nenhuma loja configurou domínio personalizado ainda.</p>
            <?php else: ?>
                <table class="table">
                    <thead>
                        <tr>
                            <th>Loja</th>
                            <th>Domínio</th>
                            <th>Status DNS</th>
                            <th>Tipo</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($stores as $store): 
                            $dns = checkDNS($store['custom_domain']);
                        ?>
                        <tr>
                            <td>
                                <strong><?= htmlspecialchars($store['name']) ?></strong><br>
                                <small class="text-muted"><?= htmlspecialchars($store['owner_email'] ?? 'N/A') ?></small>
                            </td>
                            <td>
                                <code><?= htmlspecialchars($store['custom_domain']) ?></code>
                            </td>
                            <td>
                                <?php if ($dns['ready']): ?>
                                    <span class="badge badge-success">
                                        <i class="fas fa-check"></i> DNS OK
                                    </span>
                                <?php else: ?>
                                    <span class="badge badge-warning">
                                        <i class="fas fa-clock"></i> Aguardando DNS
                                    </span>
                                    <br>
                                    <small>
                                        A: <?= $dns['a_record'] ? '✓' : '✗' ?> |
                                        CNAME: <?= $dns['cname_record'] ? '✓' : '✗' ?>
                                    </small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="badge badge-<?= $store['domain_type'] === 'custom' ? 'primary' : 'secondary' ?>">
                                    <?= htmlspecialchars($store['domain_type']) ?>
                                </span>
                            </td>
                            <td>
                                <a href="https://<?= htmlspecialchars($store['custom_domain']) ?>" 
                                   target="_blank" class="btn btn-sm btn-outline-primary">
                                    <i class="fas fa-external-link-alt"></i> Testar
                                </a>
                                <a href="<?= htmlspecialchars($store['subdomain']) ?>.duolead.com.br" 
                                   target="_blank" class="btn btn-sm btn-outline-secondary">
                                    Subdomínio
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>

    <div class="card mt-4">
        <div class="card-header">
            <h3>🔧 Como Ativar um Domínio</h3>
        </div>
        <div class="card-body">
            <ol>
                <li><strong>Verifique o DNS</strong>: O cliente deve configurar:
                    <ul>
                        <li><code>A</code> → <code>187.33.241.55</code></li>
                        <li><code>CNAME www</code> → <code>duolead.com.br</code></li>
                    </ul>
                </li>
                <li><strong>Adicione no cPanel</strong>:
                    <ul>
                        <li>Acesse o cPanel</li>
                        <li>Vá em <strong>Domains → Addon Domains</strong></li>
                        <li>Adicione o domínio apontando para <code>/home/socialar/duolead.com.br</code></li>
                    </ul>
                </li>
                <li><strong>Gere o SSL</strong>:
                    <ul>
                        <li>No cPanel, vá em <strong>SSL/TLS Status</strong></li>
                        <li>Selecione o novo domínio e clique em "Run AutoSSL"</li>
                    </ul>
                </li>
            </ol>
        </div>
    </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
