<?php

/**
 * Migration 051 – Add featured blog posts + footer/header display settings.
 *
 * - Adds is_featured column to iw_blog_posts for sticky/featured posts
 * - Adds header_show_site_name setting (show site name alongside logo)
 * - Adds footer_show_address setting (display address + hours in footer)
 * - Adds new social media platform settings (discord, twitch, github, tiktok)
 */

use App\Database\Migration;

class AddFeaturedPostsAndFooterSettings extends Migration
{
    public function up(): void
    {
        // 1. Add is_featured column to blog_posts
        $col = $this->db->fetch(
            "SELECT COLUMN_NAME FROM information_schema.COLUMNS
             WHERE TABLE_SCHEMA = DATABASE()
               AND TABLE_NAME = 'iw_blog_posts'
               AND COLUMN_NAME = 'is_featured'
             LIMIT 1"
        );

        if (!$col) {
            $this->db->query(
                "ALTER TABLE iw_blog_posts
                 ADD COLUMN is_featured TINYINT(1) NOT NULL DEFAULT 0
                 AFTER status"
            );
            $this->db->query(
                "ALTER TABLE iw_blog_posts
                 ADD INDEX idx_featured (is_featured)"
            );
        }

        // 2. Add new settings (idempotent)
        $newSettings = [
            ['header_show_site_name', '0', 'branding'],
            ['footer_show_address',   '0', 'general'],
            ['social_discord',        '',  'social'],
            ['social_twitch',         '',  'social'],
            ['social_github',         '',  'social'],
            ['social_tiktok',         '',  'social'],
        ];

        foreach ($newSettings as [$key, $value, $group]) {
            $exists = $this->db->fetch(
                "SELECT id FROM iw_settings WHERE setting_key = :key LIMIT 1",
                ['key' => $key]
            );

            if (!$exists) {
                $this->db->insert('iw_settings', [
                    'setting_key'   => $key,
                    'setting_value' => $value,
                    'setting_group' => $group,
                ]);
            }
        }
    }

    public function down(): void
    {
        // Remove is_featured column
        $col = $this->db->fetch(
            "SELECT COLUMN_NAME FROM information_schema.COLUMNS
             WHERE TABLE_SCHEMA = DATABASE()
               AND TABLE_NAME = 'iw_blog_posts'
               AND COLUMN_NAME = 'is_featured'
             LIMIT 1"
        );

        if ($col) {
            $this->db->query("ALTER TABLE iw_blog_posts DROP INDEX idx_featured");
            $this->db->query("ALTER TABLE iw_blog_posts DROP COLUMN is_featured");
        }

        // Remove new settings
        $this->db->query(
            "DELETE FROM iw_settings WHERE setting_key IN (
                'header_show_site_name', 'footer_show_address',
                'social_discord', 'social_twitch', 'social_github', 'social_tiktok'
            )"
        );
    }
}
