<?php
require_once '../../config/config.php';
require_once '../../includes/auth.php';

requireAdminLogin();

// Tüm menü öğelerini getir (parent seçimi için)
function getAllMenuItems($excludeId = null) {
    global $pdo;
    $sql = "SELECT id, title, parent_id FROM menu_items WHERE 1=1";
    $params = [];
    if ($excludeId) {
        $sql .= " AND id != ?";
        $params[] = $excludeId;
    }
    $sql .= " ORDER BY sort_order ASC, id ASC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchAll();
}

function buildMenuTree($items, $parentId = null, $level = 0, $excludeId = null) {
    $html = '';
    foreach ($items as $item) {
        if ($item['id'] == $excludeId) continue;
        if ($item['parent_id'] == $parentId || ($parentId === null && $item['parent_id'] === null)) {
            $indent = str_repeat('&nbsp;&nbsp;', $level);
            $html .= '<option value="' . $item['id'] . '">' . $indent . e($item['title']) . '</option>';
            $html .= buildMenuTree($items, $item['id'], $level + 1, $excludeId);
        }
    }
    return $html;
}

// Sayfaları getir (menüye ekleme için)
$stmt = $pdo->query("SELECT id, title, slug FROM pages WHERE status = 'published' ORDER BY title ASC");
$pages = $stmt->fetchAll();

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $url = trim($_POST['url'] ?? '');
    $parent_id = !empty($_POST['parent_id']) ? (int)$_POST['parent_id'] : null;
    $target = $_POST['target'] ?? '_self';
    $icon = trim($_POST['icon'] ?? '');
    $sort_order = (int)($_POST['sort_order'] ?? 0);
    $status = $_POST['status'] ?? 'active';
    
    if (empty($title)) {
        $error = 'Başlık gereklidir.';
    } elseif (empty($url)) {
        $error = 'URL gereklidir.';
    } else {
        try {
            $stmt = $pdo->prepare("
                INSERT INTO menu_items (title, url, parent_id, target, icon, sort_order, status)
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([$title, $url, $parent_id, $target, $icon, $sort_order, $status]);
            
            setFlashMessage('success', 'Menü öğesi başarıyla oluşturuldu.');
            redirect('index.php');
        } catch (PDOException $e) {
            $error = 'Menü öğesi oluşturulurken bir hata oluştu.';
        }
    }
}

$allMenuItems = getAllMenuItems();
$page_title = 'Yeni Menü Öğesi Ekle';
include '../includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3">Yeni Menü Öğesi Ekle</h1>
    <a href="index.php" class="btn btn-secondary">
        <i class="fas fa-arrow-left me-2"></i>Geri Dön
    </a>
</div>

<?php if ($error): ?>
    <div class="alert alert-danger"><?= e($error) ?></div>
<?php endif; ?>

<div class="card">
    <div class="card-body">
        <form method="POST">
            <div class="row">
                <div class="col-md-8">
                    <div class="mb-3">
                        <label for="title" class="form-label">Başlık <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="title" name="title" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="url" class="form-label">URL <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="text" class="form-control" id="url" name="url" required>
                            <button type="button" class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#pageModal">
                                <i class="fas fa-link me-1"></i>Sayfa Seç
                            </button>
                        </div>
                        <small class="text-muted">Örnek: /, /companies.php, /blog.php, /page/hakkimizda</small>
                    </div>
                    
                    <div class="mb-3">
                        <label for="parent_id" class="form-label">Üst Menü</label>
                        <select class="form-select" id="parent_id" name="parent_id">
                            <option value="">Ana Menü (Üst menü yok)</option>
                            <?= buildMenuTree($allMenuItems) ?>
                        </select>
                        <small class="text-muted">Boş bırakılırsa ana menüde görünür</small>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="icon" class="form-label">İkon</label>
                                <input type="text" class="form-control" id="icon" name="icon" placeholder="fas fa-home">
                                <small class="text-muted">Font Awesome ikon sınıfı (örn: fas fa-home)</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="target" class="form-label">Hedef</label>
                                <select class="form-select" id="target" name="target">
                                    <option value="_self">Aynı Pencere</option>
                                    <option value="_blank">Yeni Pencere</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-4">
                    <div class="mb-3">
                        <label for="sort_order" class="form-label">Sıra</label>
                        <input type="number" class="form-control" id="sort_order" name="sort_order" value="0">
                        <small class="text-muted">Küçük sayılar önce görünür</small>
                    </div>
                    
                    <div class="mb-3">
                        <label for="status" class="form-label">Durum</label>
                        <select class="form-select" id="status" name="status">
                            <option value="active">Aktif</option>
                            <option value="inactive">Pasif</option>
                        </select>
                    </div>
                </div>
            </div>
            
            <div class="mt-4">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save me-2"></i>Kaydet
                </button>
                <a href="index.php" class="btn btn-secondary">İptal</a>
            </div>
        </form>
    </div>
</div>

<!-- Sayfa Seçim Modal -->
<div class="modal fade" id="pageModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Sayfa Seç</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <?php if (empty($pages)): ?>
                    <p class="text-muted">Henüz yayınlanmış sayfa yok.</p>
                <?php else: ?>
                    <div class="list-group">
                        <a href="#" class="list-group-item list-group-item-action" onclick="selectPage('/', 'Ana Sayfa'); return false;">
                            <strong>Ana Sayfa</strong><br>
                            <small class="text-muted">/</small>
                        </a>
                        <a href="#" class="list-group-item list-group-item-action" onclick="selectPage('/companies.php', 'Firmalar'); return false;">
                            <strong>Firmalar</strong><br>
                            <small class="text-muted">/companies.php</small>
                        </a>
                        <a href="#" class="list-group-item list-group-item-action" onclick="selectPage('/blog.php', 'Blog'); return false;">
                            <strong>Blog</strong><br>
                            <small class="text-muted">/blog.php</small>
                        </a>
                        <?php foreach ($pages as $page): ?>
                            <a href="#" class="list-group-item list-group-item-action" onclick="selectPage('/page/<?= e($page['slug']) ?>', '<?= e($page['title']) ?>'); return false;">
                                <strong><?= e($page['title']) ?></strong><br>
                                <small class="text-muted">/page/<?= e($page['slug']) ?></small>
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

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

<script>
function selectPage(url, title) {
    document.getElementById('url').value = url;
    document.getElementById('title').value = title;
    var modal = bootstrap.Modal.getInstance(document.getElementById('pageModal'));
    modal.hide();
}
</script>


