<?php
/**
 * dns.php — DNS Servers: list, add, edit, and delete with NXS Panel dynamic light/dark style.
 */

declare(strict_types=1);

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

require_once __DIR__ . '/lib/auth.php';
require_once __DIR__ . '/lib/db.php';
require_once __DIR__ . '/lib/helpers.php';
require_once __DIR__ . '/lib/i18n.php';

require_login();

$pdo = db();
$flash = '';
$flashType = 'ok';

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    csrf_check();
    $action = (string) ($_POST['action'] ?? '');

    try {
        if ($action === 'create' || $action === 'update') {
            $title = trim((string) ($_POST['title'] ?? ''));
            $url   = trim((string) ($_POST['url'] ?? ''));

            if ($title === '' || $url === '') {
                $flash = __('title_url_required', 'Title and URL are required.');
                $flashType = 'error';
            } else {
                if ($action === 'create') {
                    $ins = $pdo->prepare('INSERT INTO dns (title, url, created_at) VALUES (?, ?, ?)');
                    $ins->execute([$title, $url, now_iso()]);
                    $flash = __('dns_created', 'DNS created successfully.');
                } else {
                    $editId = (int) ($_POST['id'] ?? 0);
                    if ($editId > 0) {
                        $oldStmt = $pdo->prepare('SELECT url FROM dns WHERE id = ? LIMIT 1');
                        $oldStmt->execute([$editId]);
                        $oldUrl = $oldStmt->fetchColumn();

                        $upd = $pdo->prepare('UPDATE dns SET title = ?, url = ? WHERE id = ?');
                        $upd->execute([$title, $url, $editId]);

                        if ($oldUrl && $oldUrl !== $url) {
                            $plUpd = $pdo->prepare('UPDATE playlists SET url = ? WHERE url = ?');
                            $plUpd->execute([$url, $oldUrl]);
                            $affected = $plUpd->rowCount();

                            $flash = "DNS updated successfully. Updated {$affected} playlist(s) to the new DNS URL.";
                        } else {
                            $flash = __('dns_updated', 'DNS updated successfully.');
                        }
                    }
                }
            }
        } elseif ($action === 'delete') {
            $delId = (int) ($_POST['id'] ?? 0);
            if ($delId > 0) {
                $del = $pdo->prepare('DELETE FROM dns WHERE id = ?');
                $del->execute([$delId]);
                $flash = __('dns_deleted', 'DNS deleted successfully.');
            }
        }
    } catch (Throwable $ex) {
        error_log('[dns] ' . $ex->getMessage());
        $flash = __('operation_failed', 'Could not complete the operation: ') . $ex->getMessage();
        $flashType = 'error';
    }
}

$editing = null;
$editId = (int) ($_GET['edit'] ?? 0);
if ($editId > 0) {
    $stmt = $pdo->prepare('SELECT id, title, url FROM dns WHERE id = ? LIMIT 1');
    $stmt->execute([$editId]);
    $editing = $stmt->fetch() ?: null;
}

$dnsList = $pdo->query('SELECT id, title, url, created_at FROM dns ORDER BY title ASC, id ASC')->fetchAll();

$pageTitle = __('dns_servers', 'DNS Servers') . '';
require __DIR__ . '/lib/header.php';
?>

<!-- NXS Panel Dynamic Theme Stilleri (Light & Dark Uyumlu) -->
<style>
    .glass-card {
        background: #ffffff;
        border: 1px solid #e5e7eb;
        border-radius: 16px;
        overflow: hidden;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.02);
        margin-bottom: 24px;
        transition: background 0.3s ease, border-color 0.3s ease;
    }

    .glass-card-header {
        padding: 16px 24px;
        border-bottom: 1px solid #e5e7eb;
        background: #f8fafc;
        transition: background 0.3s ease, border-color 0.3s ease;
    }

    .glass-card-header h2 {
        margin: 0;
        font-size: 15px;
        font-weight: 700;
        color: #111827;
    }

    .glass-card-body {
        padding: 24px;
    }

    .glass-input {
        background: #f9fafb !important;
        border: 1px solid #d1d5db !important;
        color: #111827 !important;
        border-radius: 10px !important;
        padding: 11px 16px !important;
        font-size: 14px !important;
        transition: all 0.25s ease !important;
    }

    .glass-input:focus {
        border-color: #7c3aed !important;
        box-shadow: 0 0 10px rgba(124, 58, 237, 0.2) !important;
        background: #ffffff !important;
    }

    .glass-alert-success {
        background: #ecfdf5;
        border: 1px solid #a7f3d0;
        color: #059669;
        border-radius: 12px;
        padding: 14px 20px;
    }

    .glass-alert-danger {
        background: #fef2f2;
        border: 1px solid #fecaca;
        color: #dc2626;
        border-radius: 12px;
        padding: 14px 20px;
    }

    .titan-table {
        margin-bottom: 0;
        color: #1f2937;
    }

    .titan-table th {
        font-size: 0.75rem;
        font-weight: 700;
        letter-spacing: 0.8px;
        text-transform: uppercase;
        color: #4b5563;
        background: #f8fafc;
        border-bottom: 2px solid #e5e7eb;
        padding: 14px 24px;
        white-space: nowrap;
        transition: background 0.3s ease, color 0.3s ease, border-color 0.3s ease;
    }

    .titan-table td {
        border-bottom: 1px solid #f3f4f6;
        padding: 16px 24px;
        vertical-align: middle;
        font-size: 0.9rem;
        color: #374151;
        white-space: nowrap;
        transition: background 0.3s ease, color 0.3s ease, border-color 0.3s ease;
    }

    .titan-table tbody tr:hover {
        background: #fdfdfd;
    }

    .url-code {
        font-family: 'SFMono-Regular', Consolas, Menlo, monospace;
        background: #f3f4f6;
        padding: 4px 10px;
        border-radius: 6px;
        border: 1px solid #e5e7eb;
        color: #7c3aed;
        font-weight: 600;
        font-size: 0.85rem;
    }

    /* Yazılı ve Renkli Aksiyon Butonları */
    .btn-action-text {
        padding: 6px 12px;
        display: inline-flex;
        align-items: center;
        gap: 6px;
        border-radius: 8px;
        border: none;
        color: #fff;
        font-size: 13px;
        font-weight: 600;
        transition: opacity 0.2s;
        text-decoration: none;
    }

    .btn-action-text:hover {
        opacity: 0.85;
        color: #fff;
    }

    .btn-submit-main {
        background: #7c3aed;
        border: none;
        color: #fff;
        padding: 10px 24px;
        border-radius: 10px;
        font-weight: 600;
        font-size: 14px;
        transition: all 0.2s ease;
        box-shadow: 0 4px 12px rgba(124, 58, 237, 0.25);
    }
    .btn-submit-main:hover {
        background: #6d28d9;
        color: #fff;
        transform: translateY(-1px);
    }

    .actions-group {
        display: inline-flex;
        gap: 6px;
        align-items: center;
    }

    /* --- Dark Mode (Koyu Tema) Uyarlamaları --- */
    [data-bs-theme="dark"] .glass-card {
        background: #171426 !important;
        border-color: rgba(255, 255, 255, 0.08) !important;
        color: #f3f4f6 !important;
    }

    [data-bs-theme="dark"] .glass-card-header {
        background: #141122 !important;
        border-bottom-color: rgba(255, 255, 255, 0.08) !important;
    }

    [data-bs-theme="dark"] .glass-card-header h2 {
        color: #f3f4f6 !important;
    }

    [data-bs-theme="dark"] .glass-input {
        background: #141122 !important;
        border-color: rgba(255, 255, 255, 0.1) !important;
        color: #f3f4f6 !important;
    }

    [data-bs-theme="dark"] .glass-input:focus {
        background: #171426 !important;
        border-color: #7c3aed !important;
    }

    [data-bs-theme="dark"] .titan-table th {
        background: #141122 !important;
        color: #9ca3af !important;
        border-bottom-color: rgba(255, 255, 255, 0.08) !important;
    }

    [data-bs-theme="dark"] .titan-table td {
        background: #171426 !important;
        color: #f3f4f6 !important;
        border-bottom-color: rgba(255, 255, 255, 0.08) !important;
    }

    [data-bs-theme="dark"] .titan-table tbody tr:hover {
        background: rgba(255, 255, 255, 0.02) !important;
    }

    [data-bs-theme="dark"] .url-code {
        background: rgba(255, 255, 255, 0.05) !important;
        border-color: rgba(255, 255, 255, 0.1) !important;
        color: #a78bfa !important;
    }

    [data-bs-theme="dark"] .text-muted {
        color: #9ca3af !important;
    }

    [data-bs-theme="dark"] .text-dark {
        color: #f3f4f6 !important;
    }
</style>

<div class="d-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 fw-bold text-dark"><?= __('dns_servers', 'DNS Servers') ?></h1>
</div>

<?php if ($flash !== ''): ?>
    <div class="mb-4 <?= $flashType === 'ok' ? 'glass-alert-success' : 'glass-alert-danger' ?>" role="alert">
        <?= e($flash) ?>
    </div>
<?php endif; ?>

<!-- Add / Edit DNS Card -->
<div class="glass-card">
    <div class="glass-card-header">
        <h2><?= $editing ? __('edit_dns', 'Edit DNS Server') : __('add_dns', 'Add New DNS Server') ?></h2>
    </div>
    <div class="glass-card-body">
        <form method="post" action="dns.php">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="<?= $editing ? 'update' : 'create' ?>">
            <?php if ($editing): ?>
                <input type="hidden" name="id" value="<?= (int) $editing['id'] ?>">
            <?php endif; ?>
            
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label text-muted fs-7 fw-bold mb-2" for="title"><?= __('title', 'Title') ?></label>
                    <input type="text" class="form-control glass-input" id="title" name="title" value="<?= e($editing['title'] ?? '') ?>" placeholder="PANEL NAME" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label text-muted fs-7 fw-bold mb-2" for="url"><?= __('server_url', 'Server URL') ?></label>
                    <input type="text" class="form-control glass-input" id="url" name="url" value="<?= e($editing['url'] ?? '') ?>" placeholder="http://..." required>
                </div>
            </div>
            
            <div class="mt-4 d-flex gap-2">
                <button class="btn btn-submit-main" type="submit"><?= $editing ? __('save_changes', 'Save Changes') : __('add_dns_btn', 'Add DNS') ?></button>
                <?php if ($editing): ?>
                    <a class="btn btn-outline-secondary" href="dns.php"><?= __('cancel', 'Cancel') ?></a>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>

<!-- DNS Servers List Table -->
<div class="glass-card">
    <div class="glass-card-header">
        <h2><?= count($dnsList) ?> <?= count($dnsList) === 1 ? __('server_configured', 'Server Configured') : __('servers_configured', 'Servers Configured') ?></h2>
    </div>

    <?php if (count($dnsList) === 0): ?>
        <div class="p-5 text-center">
            <i class="la la-server fs-1 text-muted d-block mb-2"></i>
            <p class="text-muted mb-0"><?= __('no_dns_servers_configured', 'No DNS servers added yet. Add one using the form above.') ?></p>
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table align-middle titan-table text-nowrap">
                <thead>
                    <tr>
                        <th><?= __('title', 'Title') ?></th>
                        <th><?= __('url', 'URL') ?></th>
                        <th><?= __('created_at', 'Created At') ?></th>
                        <th class="text-end"><?= __('actions', 'Actions') ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($dnsList as $dns): ?>
                        <tr>
                            <td><strong class="text-dark fs-6"><?= e($dns['title']) ?></strong></td>
                            <td><span class="url-code"><?= e($dns['url']) ?></span></td>
                            <td class="text-muted fs-7"><?= e($dns['created_at'] ?: '—') ?></td>
                            <td class="text-end">
                                <div class="actions-group">
                                    <!-- Users Butonu (Mor) -->
                                    <a class="btn-action-text" style="background-color: #7c3aed;" href="dns_users.php?dns_id=<?= (int) $dns['id'] ?>">
                                        <i class="la la-users"></i> <?= __('users', 'Users') ?>
                                    </a>
                                    <!-- Edit Butonu (Sarı/Turuncu) -->
                                    <a class="btn-action-text" style="background-color: #f59e0b;" href="dns.php?edit=<?= (int) $dns['id'] ?>">
                                        <i class="la la-edit"></i> <?= __('edit', 'Edit') ?>
                                    </a>
                                    <!-- Delete Butonu (Kırmızı) -->
                                    <form method="post" action="dns.php" onsubmit="return confirm('<?= __('confirm_delete_dns', 'Are you sure you want to delete this DNS server?') ?>');" class="d-inline m-0">
                                        <?= csrf_field() ?>
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= (int) $dns['id'] ?>">
                                        <button class="btn-action-text bg-danger" type="submit">
                                            <i class="la la-trash"></i> <?= __('delete', 'Delete') ?>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<?php require __DIR__ . '/lib/footer.php'; ?>