@charset "UTF-8";
/*
    Template: swell
    Theme Name: SWELL CHILD
    Theme URI: https://swell-theme.com/
    Description: SWELLの子テーマ
    Version: 1.0.0
    Author: LOOS WEB STUDIO
    Author URI: https://loos-web-studio.com/

    License: GNU General Public License
    License URI: http://www.gnu.org/licenses/gpl.html
*/
<?php
/* 子テーマのfunctions.phpは、親テーマのfunctions.phpより先に読み込まれることに注意してください。 */
/**
 * 親テーマのfunctions.phpのあとで読み込みたいコードはこの中に。
 */
// add_filter('after_setup_theme', function(){
// }, 11);

/**
 * 子テーマでのファイルの読み込み
 */
add_action('wp_enqueue_scripts', function() {
	$timestamp = date( 'Ymdgis', filemtime( get_stylesheet_directory() . '/style.css' ) );
	wp_enqueue_style( 'child_style', get_stylesheet_directory_uri() .'/style.css', [], $timestamp );
	/* その他の読み込みファイルはこの下に記述 */
}, 11);

/**
 * ========================================
 * AI副業サイト改善用カスタマイズ
 * ========================================
 */

/**
 * 1. SEO強化：記事本文内に自動的に内部リンクを挿入
 */
function add_auto_internal_links($content) {
    // 投稿ページのみ適用
    if (!is_single()) {
        return $content;
    }
    
    // キーワードと対応する記事URLのマッピング
    $keyword_links = array(
        'ChatGPT副業' => '/chatgpt-fukugyou-hajimekata/',
        '30日ロードマップ' => '/ai-fukugyou-1manen-30days-roadmap/',
        '稼げる案件' => '/chatgpt-fukugyou-kasegeru-anken-5sen/',
        'AIツール' => '/2025-kasegeru-ai-fukugyou-tool-10sen/',
        '月10万円' => '/ai-fukugyou-tsuki10manen-kensho/',
        'AI副業 失敗' => '/ai-fukugyou-shippai-pattern-5/',
    );
    
    foreach ($keyword_links as $keyword => $url) {
        // 既にリンクになっていない場合のみリンクを追加
        if (strpos($content, $keyword) !== false && strpos($content, 'href="' . $url . '"') === false) {
            $content = preg_replace(
                '/(?<!<a[^>]*>)(' . preg_quote($keyword, '/') . ')(?![^<]*<\/a>)/',
                '<a href="' . $url . '" class="auto-internal-link">$1</a>',
                $content,
                1 // 最初の1回のみ置換
            );
        }
    }
    
    return $content;
}
add_filter('the_content', 'add_auto_internal_links');

/**
 * 2. アフィリエイトリンク管理：短縮URLとクリック追跡
 */
function add_affiliate_tracking() {
    ?>
    <script>
    // アフィリエイトリンクのクリック追跡
    document.addEventListener('DOMContentLoaded', function() {
        const affiliateLinks = document.querySelectorAll('a[href*="chatgpt.com"], a[href*="crowdworks.jp"], a[href*="lancers.jp"]');
        
        affiliateLinks.forEach(function(link) {
            link.addEventListener('click', function() {
                // Google Analytics等でクリックを追跡
                if (typeof gtag !== 'undefined') {
                    gtag('event', 'click', {
                        'event_category': 'affiliate',
                        'event_label': this.href
                    });
                }
            });
        });
    });
    </script>
    <?php
}
add_action('wp_footer', 'add_affiliate_tracking');

/**
 * 3. 記事下に関連記事とCTAを自動挿入
 */
function add_post_cta($content) {
    // 投稿ページのみ適用
    if (!is_single() || !in_the_loop() || !is_main_query()) {
        return $content;
    }
    
    $cta_content = '
    <div class="post-cta-section" style="margin: 40px 0; padding: 30px; background: #f8f9fa; border-radius: 10px; border-left: 5px solid #007cba;">
        <h3 style="color: #007cba; margin-bottom: 20px;">🚀 AI副業を今すぐ始めたい方へ</h3>
        <p style="margin-bottom: 20px;">成功に必要なツールとプラットフォームをすべて揃えました。</p>
        
        <div style="margin-bottom: 25px;">
            <h4 style="color: #333; margin-bottom: 10px;">【必須ツール】</h4>
            <p>✅ <a href="https://chatgpt.com/" target="_blank" rel="noopener" style="color: #007cba; font-weight: bold;">ChatGPT Plus公式登録</a> ※月25ドル・7日間無料体験・成功の必須条件</p>
        </div>
        
        <div style="margin-bottom: 25px;">
            <h4 style="color: #333; margin-bottom: 10px;">【案件獲得プラットフォーム】</h4>
            <p>✅ <a href="https://crowdworks.jp/" target="_blank" rel="noopener" style="color: #007cba;">クラウドワークス</a> – 案件数最多・初心者向け<br>
            ✅ <a href="https://www.lancers.jp/" target="_blank" rel="noopener" style="color: #007cba;">ランサーズ</a> – 高単価案件・中級者以上<br>
            ✅ <a href="https://coconala.com/" target="_blank" rel="noopener" style="color: #007cba;">ココナラ</a> – サービス販売・リピート重視</p>
        </div>
        
        <p style="text-align: center; font-weight: bold; color: #007cba;">行動するのは今です！来月には副業収入が現実になっています。</p>
    </div>';
    
    return $content . $cta_content;
}
add_filter('the_content', 'add_post_cta');

/**
 * 4. 目次自動生成（SWELLの目次機能を補完）
 */
function enhance_table_of_contents($content) {
    if (!is_single()) {
        return $content;
    }
    
    // H2、H3タグにIDを自動追加（SWELLで未設定の場合）
    $content = preg_replace_callback(
        '/<h([23])(?![^>]*id=)([^>]*)>(.*?)<\/h[23]>/i',
        function($matches) {
            $level = $matches[1];
            $attributes = $matches[2];
            $text = $matches[3];
            $id = sanitize_title($text);
            return '<h' . $level . ' id="' . $id . '"' . $attributes . '>' . $text . '</h' . $level . '>';
        },
        $content
    );
    
    return $content;
}
add_filter('the_content', 'enhance_table_of_contents');

/**
 * 5. パフォーマンス最適化：画像遅延読み込み
 */
function add_lazy_loading_to_images($content) {
    if (!is_single()) {
        return $content;
    }
    
    // loading="lazy"を画像に追加
    $content = preg_replace('/<img(?![^>]*loading=)([^>]+)>/i', '<img$1 loading="lazy">', $content);
    
    return $content;
}
add_filter('the_content', 'add_lazy_loading_to_images');

/**
 * 6. メタディスクリプション自動生成（SEO改善）
 */
function auto_meta_description() {
    if (is_single()) {
        global $post;
        
        // 手動設定がない場合のみ自動生成
        if (!get_post_meta($post->ID, '_yoast_wpseo_metadesc', true)) {
            $excerpt = wp_trim_words(strip_tags($post->post_content), 30, '...');
            echo '<meta name="description" content="' . esc_attr($excerpt) . '">' . "\n";
        }
    }
}
add_action('wp_head', 'auto_meta_description');

/**
 * 7. 問い合わせフォーム改善用のスタイル
 */
function add_contact_form_styles() {
    ?>
    <style>
    /* 問い合わせフォームのスタイル改善 */
    .contact-form-wrapper {
        max-width: 600px;
        margin: 0 auto;
        padding: 30px;
        background: #fff;
        border-radius: 10px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    
    /* CTAボタンのスタイル */
    .post-cta-section a {
        text-decoration: none;
        transition: color 0.3s ease;
    }
    
    .post-cta-section a:hover {
        color: #005a87 !important;
    }
    
    /* 自動内部リンクのスタイル */
    .auto-internal-link {
        color: #007cba;
        text-decoration: underline;
        font-weight: 500;
    }
    
    .auto-internal-link:hover {
        color: #005a87;
    }
    </style>
    <?php
}
add_action('wp_head', 'add_contact_form_styles');

/**
 * 8. 記事読了時間の計算
 */
function calculate_reading_time($post_id) {
    $content = get_post_field('post_content', $post_id);
    $word_count = str_word_count(strip_tags($content));
    $reading_time = ceil($word_count / 200); // 1分200語として計算
    
    return max(1, $reading_time); // 最低1分
}

/**
 * 9. ショートコード：読了時間表示
 */
function reading_time_shortcode($atts) {
    global $post;
    $reading_time = calculate_reading_time($post->ID);
    
    return '<span class="reading-time">📖 読了時間：約' . $reading_time . '分</span>';
}
add_shortcode('reading_time', 'reading_time_shortcode');

/**
 * 10. セキュリティ強化：ログイン試行回数制限
 */
function limit_login_attempts() {
    $ip = $_SERVER['REMOTE_ADDR'];
    $attempts = get_transient('login_attempts_' . $ip);
    
    if ($attempts && $attempts >= 5) {
        wp_die('ログイン試行回数が上限に達しました。1時間後に再試行してください。');
    }
}
add_action('wp_login_failed', function() {
    $ip = $_SERVER['REMOTE_ADDR'];
    $attempts = get_transient('login_attempts_' . $ip) ?: 0;
    set_transient('login_attempts_' . $ip, $attempts + 1, HOUR_IN_SECONDS);
});

// ログイン成功時にカウンターをリセット
add_action('wp_login', function() {
    $ip = $_SERVER['REMOTE_ADDR'];
    delete_transient('login_attempts_' . $ip);
});
?>
