<?php
require_once 'check_auth.php';

$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = isset($_POST['action']) ? $_POST['action'] : '';
    
    if ($action == 'add' || $action == 'update') {
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        $name = cleanInput($_POST['name'] ?? '');
        $platform = cleanInput($_POST['platform'] ?? '');
        $pixel_code = $_POST['pixel_code'] ?? '';
        $placement = cleanInput($_POST['placement'] ?? 'all');
        $position = cleanInput($_POST['position'] ?? 'head');
        $status = isset($_POST['status']) ? 1 : 0;
        $sort_order = isset($_POST['sort_order']) ? (int)$_POST['sort_order'] : 0;
        
        if (empty($name)) {
            $error = 'Lütfen bir isim girin!';
        } elseif (empty($pixel_code)) {
            $error = 'Lütfen piksel kodunu girin!';
        } else {
            try {
                if ($action == 'add') {
                    $stmt = $pdo->prepare("INSERT INTO ad_pixels (name, platform, pixel_code, placement, position, status, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$name, $platform, $pixel_code, $placement, $position, $status, $sort_order]);
                    $success = 'Reklam pikseli başarıyla eklendi!';
                } else {
                    $stmt = $pdo->prepare("UPDATE ad_pixels SET name = ?, platform = ?, pixel_code = ?, placement = ?, position = ?, status = ?, sort_order = ? WHERE id = ?");
                    $stmt->execute([$name, $platform, $pixel_code, $placement, $position, $status, $sort_order, $id]);
                    $success = 'Reklam pikseli başarıyla güncellendi!';
                }
            } catch(PDOException $e) {
                $error = 'Hata: ' . $e->getMessage();
            }
        }
    }
    
    if ($action == 'delete') {
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        try {
            $stmt = $pdo->prepare("DELETE FROM ad_pixels WHERE id = ?");
            $stmt->execute([$id]);
            $success = 'Reklam pikseli silindi!';
        } catch(PDOException $e) {
            $error = 'Silme hatası: ' . $e->getMessage();
        }
    }
    
    if ($action == 'toggle') {
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        try {
            $stmt = $pdo->prepare("UPDATE ad_pixels SET status = IF(status = 1, 0, 1) WHERE id = ?");
            $stmt->execute([$id]);
            $success = 'Durum güncellendi!';
        } catch(PDOException $e) {
            $error = 'Hata: ' . $e->getMessage();
        }
    }
}

$edit = null;
if (isset($_GET['edit']) && (int)$_GET['edit'] > 0) {
    $stmt = $pdo->prepare("SELECT * FROM ad_pixels WHERE id = ? LIMIT 1");
    $stmt->execute([(int)$_GET['edit']]);
    $edit = $stmt->fetch();
}

$stmt = $pdo->query("SELECT * FROM ad_pixels ORDER BY sort_order ASC, id DESC");
$pixels = $stmt->fetchAll();

$page_title = 'Reklam Piksel Yönetimi';
$placements = [
    'all' => 'Tüm Sayfalarda',
    'home' => 'Sadece Ana Sayfa',
    'success' => 'Sadece Başarı Sayfası'
];
$positions = [
    'head' => ['label' => 'Head (</head> öncesi)', 'icon' => 'fa-code', 'desc' => 'Facebook, TikTok, Google Analytics vb. pikseller için ÖNERİLEN'],
    'body-top' => ['label' => 'Body Başında (<body> sonrası)', 'icon' => 'fa-arrow-up', 'desc' => '<noscript> ve <img> fallback kodları için'],
    'body-bottom' => ['label' => 'Body Sonunda (</body> öncesi)', 'icon' => 'fa-arrow-down', 'desc' => 'Özel JS kodları, 3. parti chat vb. için']
];
?>
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo $page_title; ?> - Max Power Admin</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<style>
body { background-color: #f5f7fa; }
.sidebar {
    background: linear-gradient(180deg, #2c3e50 0%, #34495e 100%);
    min-height: 100vh;
}
.sidebar .nav-link {
    color: rgba(255,255,255,0.85);
    padding: 12px 20px;
    border-radius: 8px;
    margin: 4px 0;
}
.sidebar .nav-link:hover, .sidebar .nav-link.active {
    background: rgba(255,255,255,0.1);
    color: #fff;
}
.topbar {
    background: #fff;
    border-bottom: 1px solid #eee;
    padding: 15px 0;
}
.card { border: none; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
.card .card-header { background: #fff; border-bottom: 1px solid #eee; border-radius: 12px 12px 0 0 !important; padding: 20px; }
.form-label { font-weight: 600; color: #495057; }
.form-control, .form-select { padding: 10px 15px; border-radius: 8px; }
.badge-placement {
    padding: 5px 10px;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: 600;
}
.platform-icon {
    width: 36px;
    height: 36px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1rem;
    color: white;
    flex-shrink: 0;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row">
    <div class="col-md-2 col-lg-2 px-0 sidebar">
        <div class="p-4 text-center border-bottom border-secondary">
            <h5 class="text-white mb-0 fw-bold"><i class="fas fa-bolt me-2 text-warning"></i>Max Power</h5>
            <p class="text-white-50 small mb-0 mt-1">Admin Paneli</p>
        </div>
        <nav class="nav flex-column p-3">
            <a href="index.php" class="nav-link">
                <i class="fas fa-list-alt me-2"></i> Siparişler
            </a>
            <a href="ads.php" class="nav-link active">
                <i class="fas fa-ad me-2"></i> Reklam Pikselleri
            </a>
            <a href="logout.php" class="nav-link mt-3" style="color:#ff6b6b;">
                <i class="fas fa-sign-out-alt me-2"></i> Çıkış
            </a>
        </nav>
    </div>
    
    <div class="col-md-10 col-lg-10 px-0">
        <div class="topbar px-4">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb mb-1 small">
                            <li class="breadcrumb-item"><a href="index.php" class="text-decoration-none">Anasayfa</a></li>
                            <li class="breadcrumb-item active" aria-current="page">Reklam Piksel Yönetimi</li>
                        </ol>
                    </nav>
                    <h4 class="mb-0 fw-bold"><i class="fas fa-ad me-2 text-danger"></i>Reklam Piksel Yönetimi</h4>
                </div>
                <span class="text-muted small"><i class="fas fa-clock me-1"></i><?php echo date('d.m.Y H:i'); ?></span>
            </div>
        </div>
        
        <div class="p-4">
            <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show mb-4"><i class="fas fa-check-circle me-2"></i><?php echo $success; ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
            <?php endif; ?>
            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show mb-4"><i class="fas fa-exclamation-circle me-2"></i><?php echo $error; ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
            <?php endif; ?>
            
            <div class="row g-4">
                <div class="col-lg-5">
                    <div class="card mb-4">
                        <div class="card-header d-flex align-items-center">
                            <?php if ($edit): ?>
                                <h6 class="mb-0 fw-bold"><i class="fas fa-edit me-2 text-warning"></i>Piksel Düzenle</h6>
                                <a href="ads.php" class="btn btn-sm btn-outline-secondary ms-auto"><i class="fas fa-plus me-1"></i>Yeni Ekle</a>
                            <?php else: ?>
                                <h6 class="mb-0 fw-bold"><i class="fas fa-plus-circle me-2 text-success"></i>Yeni Piksel Ekle</h6>
                            <?php endif; ?>
                        </div>
                        <div class="card-body p-4">
                            <form method="POST">
                                <input type="hidden" name="action" value="<?php echo $edit ? 'update' : 'add'; ?>">
                                <?php if ($edit): ?>
                                    <input type="hidden" name="id" value="<?php echo $edit['id']; ?>">
                                <?php endif; ?>
                                
                                <div class="mb-3">
                                    <label class="form-label">Piksel Adı <span class="text-danger">*</span></label>
                                    <input type="text" name="name" class="form-control" value="<?php echo $edit ? htmlspecialchars($edit['name']) : ''; ?>" placeholder="Örn: Facebook Ana Sayfa Pikseli" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Platform</label>
                                    <select name="platform" class="form-select">
                                        <option value="">Seçiniz</option>
                                        <option value="facebook" <?php echo ($edit && $edit['platform'] == 'facebook') ? 'selected' : ''; ?>>📘 Facebook / Meta</option>
                                        <option value="tiktok" <?php echo ($edit && $edit['platform'] == 'tiktok') ? 'selected' : ''; ?>>🎵 TikTok</option>
                                        <option value="google" <?php echo ($edit && $edit['platform'] == 'google') ? 'selected' : ''; ?>>🔍 Google Ads / Analytics</option>
                                        <option value="instagram" <?php echo ($edit && $edit['platform'] == 'instagram') ? 'selected' : ''; ?>>📷 Instagram</option>
                                        <option value="twitter" <?php echo ($edit && $edit['platform'] == 'twitter') ? 'selected' : ''; ?>>🐦 Twitter / X</option>
                                        <option value="linkedin" <?php echo ($edit && $edit['platform'] == 'linkedin') ? 'selected' : ''; ?>>💼 LinkedIn</option>
                                        <option value="custom" <?php echo ($edit && $edit['platform'] == 'custom') ? 'selected' : ''; ?>>⚙️ Özel / Diğer</option>
                                    </select>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Gösterim Yeri</label>
                                    <select name="placement" class="form-select">
                                        <?php foreach ($placements as $key => $label): ?>
                                            <option value="<?php echo $key; ?>" <?php echo ($edit && $edit['placement'] == $key) ? 'selected' : ''; ?>><?php echo $label; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="form-text">Piksel kodunun hangi sayfalarda çalışacağını seçin.</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">
                                        Kod Konumu
                                        <span class="badge bg-success ms-1"><i class="fas fa-lightbulb me-1"></i>ÖNEMLİ</span>
                                    </label>
                                    <select name="position" class="form-select" style="border-width:2px;">
                                        <?php foreach ($positions as $key => $pos): ?>
                                            <option value="<?php echo $key; ?>" <?php echo (!$edit || ($edit['position'] ?? 'head') == $key) ? 'selected' : ''; ?>>
                                                <i class="fas <?php echo $pos['icon']; ?>"></i> <?php echo $pos['label']; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php 
                                        $cur_pos = $edit['position'] ?? 'head';
                                    ?>
                                    <div class="form-text" id="positionDesc" style="margin-top:8px;">
                                        <div class="alert alert-info py-2 px-3 mb-0 small">
                                            <i class="fas fa-info-circle me-1"></i>
                                            <strong id="posName"><?php echo $positions[$cur_pos]['label']; ?>:</strong>
                                            <span id="posDesc"><?php echo $positions[$cur_pos]['desc']; ?></span>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Piksel Kodu <span class="text-danger">*</span></label>
                                    <textarea name="pixel_code" rows="8" class="form-control font-monospace small" placeholder="Buraya Facebook, TikTok vb. size verilen script kodunu yapıştırın..." required style="background:#f8f9fa;"><?php echo $edit ? htmlspecialchars($edit['pixel_code']) : ''; ?></textarea>
                                    <div class="form-text text-danger">⚠️ Kodu doğrudan kopyalayıp yapıştırın, değişiklik yapmayın!</div>
                                </div>
                                
                                <div class="row g-3 mb-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Sıra</label>
                                        <input type="number" name="sort_order" class="form-control" value="<?php echo $edit ? $edit['sort_order'] : 0; ?>">
                                    </div>
                                    <div class="col-md-6 d-flex align-items-end">
                                        <div class="form-check form-switch">
                                            <input class="form-check-input" type="checkbox" name="status" id="status" <?php echo (!$edit || $edit['status'] == 1) ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="status">Aktif</label>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="d-flex gap-2">
                                    <?php if ($edit): ?>
                                        <a href="ads.php" class="btn btn-outline-secondary flex-grow-1"><i class="fas fa-times me-1"></i>İptal</a>
                                    <?php endif; ?>
                                    <button type="submit" class="btn btn-<?php echo $edit ? 'warning' : 'primary'; ?> flex-grow-1">
                                        <i class="fas fa-save me-1"></i>
                                        <?php echo $edit ? 'Güncelle' : 'Ekle'; ?>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                
                <div class="col-lg-7">
                    <div class="card">
                        <div class="card-header d-flex align-items-center">
                            <h6 class="mb-0 fw-bold"><i class="fas fa-list me-2 text-primary"></i>Kayıtlı Pikseller (<?php echo count($pixels); ?>)</h6>
                        </div>
                        <div class="card-body p-0">
                            <?php if (empty($pixels)): ?>
                                <div class="text-center py-5 text-muted">
                                    <i class="fas fa-ad fa-3x mb-3 opacity-50"></i>
                                    <h6>Henüz piksel eklenmemiş</h6>
                                    <p class="small mb-0">Soldaki formdan Facebook, TikTok vb. piksellerinizi ekleyin.</p>
                                </div>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-hover mb-0 align-middle">
                                        <thead class="bg-light">
                                            <tr>
                                                <th style="width:50px;">Sıra</th>
                                                <th>Platform / Piksel</th>
                                                <th>Yer (Sayfa)</th>
                                                <th>Konum (Kod)</th>
                                                <th>Durum</th>
                                                <th style="width:180px;">İşlem</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($pixels as $p): 
                                                $icon = 'fa-cog';
                                                $bg = '#6c757d';
                                                switch($p['platform']) {
                                                    case 'facebook': $icon = 'fa-facebook-f'; $bg = '#1877F2'; break;
                                                    case 'tiktok': $icon = 'fa-music'; $bg = '#000000'; break;
                                                    case 'google': $icon = 'fa-google'; $bg = '#EA4335'; break;
                                                    case 'instagram': $icon = 'fa-instagram'; $bg = '#E1306C'; break;
                                                    case 'twitter': $icon = 'fa-twitter'; $bg = '#1DA1F2'; break;
                                                    case 'linkedin': $icon = 'fa-linkedin-in'; $bg = '#0A66C2'; break;
                                                }
                                            ?>
                                            <tr>
                                                <td><span class="text-muted small"><?php echo $p['sort_order']; ?></span></td>
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <div class="platform-icon me-3" style="background:<?php echo $bg; ?>;">
                                                            <i class="fab <?php echo $icon; ?>"></i>
                                                        </div>
                                                        <div>
                                                            <div class="fw-semibold"><?php echo htmlspecialchars($p['name']); ?></div>
                                                            <small class="text-muted">#<?php echo $p['id']; ?> · <?php echo date('d.m.Y', strtotime($p['created_at'])); ?></small>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td>
                                                    <?php 
                                                        $badgeClass = 'bg-secondary';
                                                        if ($p['placement'] == 'all') $badgeClass = 'bg-info';
                                                        elseif ($p['placement'] == 'home') $badgeClass = 'bg-primary';
                                                        elseif ($p['placement'] == 'success') $badgeClass = 'bg-success';
                                                    ?>
                                                    <span class="badge badge-placement <?php echo $badgeClass; ?>"><?php echo $placements[$p['placement']] ?? $p['placement']; ?></span>
                                                </td>
                                                <td>
                                                    <?php 
                                                        $pos = $p['position'] ?? 'head';
                                                        $posBadge = 'bg-success';
                                                        $posIcon = 'fa-code';
                                                        if ($pos == 'body-top') { $posBadge = 'bg-warning'; $posIcon = 'fa-arrow-up'; }
                                                        elseif ($pos == 'body-bottom') { $posBadge = 'bg-dark'; $posIcon = 'fa-arrow-down'; }
                                                    ?>
                                                    <span class="badge badge-placement <?php echo $posBadge; ?>" title="<?php echo $positions[$pos]['desc'] ?? ''; ?>">
                                                        <i class="fas <?php echo $posIcon; ?> me-1"></i>
                                                        <?php echo $positions[$pos]['label'] ?? $pos; ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <form method="POST" style="display:inline;">
                                                        <input type="hidden" name="action" value="toggle">
                                                        <input type="hidden" name="id" value="<?php echo $p['id']; ?>">
                                                        <button type="submit" class="btn btn-sm <?php echo $p['status'] ? 'btn-success' : 'btn-secondary'; ?>" style="border-radius:20px;">
                                                            <?php if ($p['status']): ?><i class="fas fa-check me-1"></i>Aktif<?php else: ?><i class="fas fa-times me-1"></i>Pasif<?php endif; ?>
                                                        </button>
                                                    </form>
                                                </td>
                                                <td>
                                                    <div class="d-flex gap-1">
                                                        <a href="ads.php?edit=<?php echo $p['id']; ?>" class="btn btn-sm btn-warning" title="Düzenle">
                                                            <i class="fas fa-edit"></i>
                                                        </a>
                                                        <button type="button" class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#deleteModal<?php echo $p['id']; ?>" title="Sil">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                        <button type="button" class="btn btn-sm btn-info" data-bs-toggle="modal" data-bs-target="#viewModal<?php echo $p['id']; ?>" title="Kodu Gör">
                                                            <i class="fas fa-eye"></i>
                                                        </button>
                                                    </div>
                                                    
                                                    <div class="modal fade" id="viewModal<?php echo $p['id']; ?>" tabindex="-1">
                                                        <div class="modal-dialog modal-lg modal-dialog-centered">
                                                            <div class="modal-content">
                                                                <div class="modal-header"><h5 class="modal-title"><?php echo htmlspecialchars($p['name']); ?> - Kod</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                                                                <div class="modal-body p-0">
                                                                    <pre class="mb-0 p-3 bg-dark text-light small rounded-0" style="max-height:400px;overflow:auto;"><?php echo htmlspecialchars($p['pixel_code']); ?></pre>
                                                                </div>
                                                                <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Kapat</button></div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="modal fade" id="deleteModal<?php echo $p['id']; ?>" tabindex="-1">
                                                        <div class="modal-dialog modal-dialog-centered">
                                                            <div class="modal-content">
                                                                <div class="modal-header bg-danger text-white"><h5 class="modal-title"><i class="fas fa-exclamation-triangle me-2"></i>Pikseli Sil</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
                                                                <div class="modal-body text-center py-4">
                                                                    <i class="fas fa-trash fa-4x text-danger mb-3 opacity-75"></i>
                                                                    <p class="mb-1 fw-semibold">Silmek istediğinize emin misiniz?</p>
                                                                    <p class="text-muted small mb-0"><?php echo htmlspecialchars($p['name']); ?></p>
                                                                </div>
                                                                <div class="modal-footer">
                                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Vazgeç</button>
                                                                    <form method="POST" style="display:inline;">
                                                                        <input type="hidden" name="action" value="delete">
                                                                        <input type="hidden" name="id" value="<?php echo $p['id']; ?>">
                                                                        <button type="submit" class="btn btn-danger"><i class="fas fa-trash me-1"></i>Evet, Sil</button>
                                                                    </form>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="card mt-4 border-primary">
                        <div class="card-header bg-primary bg-opacity-10 border-primary">
                            <h6 class="mb-0 fw-bold text-primary"><i class="fas fa-lightbulb me-2"></i>Bilgilendirme</h6>
                        </div>
                        <div class="card-body">
                            <div class="row g-3 small">
                                <div class="col-md-6">
                                    <strong>📘 Facebook (Meta) Pikseli:</strong>
                                    <ul class="mb-0 mt-1 ps-3">
                                        <li>Events Manager → Ayarlar → Piksel kodunu kopyala</li>
                                        <li>Satın alma sinyali için "Purchase" eventi tanımlı olsun</li>
                                        <li>Başarı sayfası için ayrı piksel veya event eklenebilir</li>
                                    </ul>
                                </div>
                                <div class="col-md-6">
                                    <strong>🎵 TikTok Pikseli:</strong>
                                    <ul class="mb-0 mt-1 ps-3">
                                        <li>Ads Manager → Veri Kaynakları → Web Events</li>
                                        <li>Kodu doğrudan "Piksel Kodu" alanına yapıştırın</li>
                                        <li>Sipariş sonrası CompletePayment eventi çalışır</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    const posData = <?php echo json_encode($positions); ?>;
    const posName = document.getElementById('posName');
    const posDesc = document.getElementById('posDesc');
    const posSelect = document.querySelector('select[name="position"]');
    if (posSelect) {
        posSelect.addEventListener('change', function() {
            const val = this.value;
            if (posData[val]) {
                posName.textContent = posData[val].label + ':';
                posDesc.textContent = posData[val].desc;
            }
        });
    }
</script>
</body>
</html>
