-- Üst menü v2: parent_id (hiyerarşi) + show_in_nav.
-- Tekrar çalıştırılabilir (kolon / indeks / FK zaten varsa atlanır).
USE faunamix;

SET @db = DATABASE();

-- 1) parent_id
SELECT COUNT(*) INTO @c FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'nav_menu_items' AND COLUMN_NAME = 'parent_id';
SET @sql = IF(
  @c = 0,
  'ALTER TABLE nav_menu_items ADD COLUMN parent_id INT UNSIGNED NULL DEFAULT NULL AFTER id',
  'SELECT ''parent_id zaten var'' AS _skip'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 2) show_in_nav
SELECT COUNT(*) INTO @c FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'nav_menu_items' AND COLUMN_NAME = 'show_in_nav';
SET @sql = IF(
  @c = 0,
  'ALTER TABLE nav_menu_items ADD COLUMN show_in_nav TINYINT(1) NOT NULL DEFAULT 1 AFTER is_active',
  'SELECT ''show_in_nav zaten var'' AS _skip'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 3) İndeks
SELECT COUNT(*) INTO @c FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'nav_menu_items' AND INDEX_NAME = 'idx_nav_parent_sort';
SET @sql = IF(
  @c = 0,
  'ALTER TABLE nav_menu_items ADD KEY idx_nav_parent_sort (parent_id, sort_order)',
  'SELECT ''idx_nav_parent_sort zaten var'' AS _skip'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 4) Yabancı anahtar (çocuk silinince zincir CASCADE)
SELECT COUNT(*) INTO @c FROM information_schema.TABLE_CONSTRAINTS
WHERE CONSTRAINT_SCHEMA = @db AND TABLE_NAME = 'nav_menu_items' AND CONSTRAINT_NAME = 'fk_nav_menu_parent'
  AND CONSTRAINT_TYPE = 'FOREIGN KEY';
SET @sql = IF(
  @c = 0,
  'ALTER TABLE nav_menu_items ADD CONSTRAINT fk_nav_menu_parent FOREIGN KEY (parent_id) REFERENCES nav_menu_items (id) ON DELETE CASCADE',
  'SELECT ''fk_nav_menu_parent zaten var'' AS _skip'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
