<?php
/**
 * Network Links Management
 * Aegean Dominance Admin Panel
 */

session_start();
require_once __DIR__ . '/../config/config.php';

$auth = new Auth();
$auth->requireLogin();

$db = Database::getInstance();

// AJAX İşlemleri
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    header('Content-Type: application/json');
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? '';
    
    try {
        switch ($action) {
            case 'delete':
                $id = (int)($input['id'] ?? 0);
                $db->execute("DELETE FROM network_links WHERE id = ?", [$id]);
                echo json_encode(['success' => true, 'message' => 'Link silindi.']);
                break;
                
            case 'toggle':
                $id = (int)($input['id'] ?? 0);
                $db->execute("UPDATE network_links SET is_active = NOT is_active WHERE id = ?", [$id]);
                echo json_encode(['success' => true, 'message' => 'Durum değiştirildi.']);
                break;
                
            default:
                echo json_encode(['success' => false, 'error' => 'Geçersiz işlem.']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

// Form gönderimi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    try {
        $id = (int)($_POST['id'] ?? 0);
        $data = [
            'domain' => trim($_POST['domain'] ?? ''),
            'title' => trim($_POST['title'] ?? ''),
            'anchor_text' => trim($_POST['anchor_text'] ?? ''),
            'target_url' => trim($_POST['target_url'] ?? ''),
            'rel_attribute' => $_POST['rel_attribute'] ?? 'dofollow',
            'display_order' => (int)($_POST['display_order'] ?? 0)
        ];
        
        if ($id > 0) {
            $db->execute(
                "UPDATE network_links SET domain = ?, title = ?, anchor_text = ?, target_url = ?, rel_attribute = ?, display_order = ? WHERE id = ?",
                [$data['domain'], $data['title'], $data['anchor_text'], $data['target_url'], $data['rel_attribute'], $data['display_order'], $id]
            );
        } else {
            $db->execute(
                "INSERT INTO network_links (domain, title, anchor_text, target_url, rel_attribute, display_order) VALUES (?, ?, ?, ?, ?, ?)",
                [$data['domain'], $data['title'], $data['anchor_text'], $data['target_url'], $data['rel_attribute'], $data['display_order']]
            );
        }
        
        header("Location: network.php?success=Kaydedildi");
        exit;
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

$links = $db->fetchAll("SELECT * FROM network_links ORDER BY display_order");

include 'partials/header.php';
?>

<div class="p-6">
    <?php if (isset($_GET['success'])): ?>
    <div class="mb-6 p-4 rounded-lg bg-green-500/10 border border-green-500/30 text-green-400 flex items-center gap-2">
        <i data-lucide="check-circle" class="w-5 h-5"></i>
        <span><?= htmlspecialchars($_GET['success']) ?></span>
    </div>
    <?php endif; ?>
    
    <div class="flex items-center justify-between mb-6">
        <div>
            <h2 class="text-xl font-semibold text-white">Network Linkleri</h2>
            <p class="text-white/60 text-sm">Sister site ve domain ağı yönetimi</p>
        </div>
    </div>
    
    <div class="grid lg:grid-cols-3 gap-6">
        <!-- Link Listesi -->
        <div class="lg:col-span-2 space-y-4">
            <?php foreach ($links as $link): ?>
            <div class="glass-card rounded-xl p-4 flex items-center gap-4">
                <div class="w-10 h-10 rounded-lg bg-gold/20 flex items-center justify-center">
                    <i data-lucide="globe" class="w-5 h-5 text-gold"></i>
                </div>
                
                <div class="flex-1 min-w-0">
                    <div class="flex items-center gap-2">
                        <h3 class="text-white font-medium"><?= htmlspecialchars($link['domain']) ?></h3>
                        <span class="px-2 py-0.5 rounded text-xs <?= $link['rel_attribute'] === 'dofollow' ? 'bg-green-500/20 text-green-400' : 'bg-yellow-500/20 text-yellow-400' ?>">
                            <?= $link['rel_attribute'] ?>
                        </span>
                    </div>
                    <p class="text-white/40 text-sm truncate"><?= htmlspecialchars($link['anchor_text']) ?> → <?= htmlspecialchars($link['target_url']) ?></p>
                </div>
                
                <div class="flex items-center gap-2">
                    <button onclick="toggleLink(<?= $link['id'] ?>)" class="p-2 rounded-lg hover:bg-white/10">
                        <?php if ($link['is_active']): ?>
                        <i data-lucide="toggle-right" class="w-5 h-5 text-green-400"></i>
                        <?php else: ?>
                        <i data-lucide="toggle-left" class="w-5 h-5 text-white/40"></i>
                        <?php endif; ?>
                    </button>
                    <button onclick="deleteLink(<?= $link['id'] ?>)" class="p-2 rounded-lg hover:bg-red-500/20 text-white/60 hover:text-red-400">
                        <i data-lucide="trash-2" class="w-4 h-4"></i>
                    </button>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        
        <!-- Yeni Link Formu -->
        <div class="glass-card rounded-2xl p-6">
            <h3 class="text-lg font-semibold text-white mb-4">Yeni Link Ekle</h3>
            
            <form method="POST" class="space-y-4">
                <div>
                    <label class="block text-white/70 text-sm mb-2">Domain</label>
                    <input type="text" name="domain" required class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-2 text-white focus:border-gold focus:outline-none" placeholder="example.com">
                </div>
                
                <div>
                    <label class="block text-white/70 text-sm mb-2">Title (SEO)</label>
                    <input type="text" name="title" class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-2 text-white focus:border-gold focus:outline-none" placeholder="Site açıklaması">
                </div>
                
                <div>
                    <label class="block text-white/70 text-sm mb-2">Anchor Text</label>
                    <input type="text" name="anchor_text" class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-2 text-white focus:border-gold focus:outline-none" placeholder="Link metni">
                </div>
                
                <div>
                    <label class="block text-white/70 text-sm mb-2">Target URL</label>
                    <input type="url" name="target_url" class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-2 text-white focus:border-gold focus:outline-none" placeholder="https://...">
                </div>
                
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-white/70 text-sm mb-2">Rel</label>
                        <select name="rel_attribute" class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-2 text-white focus:border-gold focus:outline-none">
                            <option value="dofollow">Dofollow</option>
                            <option value="nofollow">Nofollow</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-white/70 text-sm mb-2">Sıra</label>
                        <input type="number" name="display_order" class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-2 text-white focus:border-gold focus:outline-none" value="<?= count($links) + 1 ?>">
                    </div>
                </div>
                
                <button type="submit" class="w-full gold-gradient text-dark-900 font-semibold py-2 px-4 rounded-lg hover:opacity-90">
                    <i data-lucide="plus" class="w-4 h-4 inline mr-2"></i>
                    Ekle
                </button>
            </form>
        </div>
    </div>
</div>

<script>
async function toggleLink(id) {
    const result = await apiRequest('network.php', { action: 'toggle', id });
    if (result.success) location.reload();
}

async function deleteLink(id) {
    const confirmed = await confirmAction('Bu linki silmek istediğinize emin misiniz?');
    if (!confirmed) return;
    const result = await apiRequest('network.php', { action: 'delete', id });
    if (result.success) { showToast(result.message, 'success'); location.reload(); }
}
</script>

<?php include 'partials/footer.php'; ?>
