<?php
// app/database/DatabaseSetup.php

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Content Craft AI Database Setup
 * 
 * Handles database table creation and initialization
 */
class ContentCraftAI_DatabaseSetup
{
    /**
     * Initialize database tables
     * Creates all the tables needed for the plugin
     */
    public static function init_tables()
    {
        self::create_article_generations_table();
        self::create_internal_links_table();
    }

    /**
     * Create the article generations table
     */
    private static function create_article_generations_table()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'content_craft_ai_generations';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE IF NOT EXISTS {$table_name} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            queue_id varchar(100) NOT NULL,
            title text NOT NULL,
            type varchar(20) NOT NULL DEFAULT 'article',
            status varchar(50) NOT NULL DEFAULT 'pending',
            word_count int DEFAULT NULL,
            created_at datetime NOT NULL,
            completed_at datetime DEFAULT NULL,
            user_id bigint(20) NOT NULL,
            category bigint(20) DEFAULT NULL,
            post_id bigint(20) DEFAULT NULL,
            parameters longtext,
            scheduled_time datetime DEFAULT NULL,
            is_scheduled tinyint(1) DEFAULT 0,
            PRIMARY KEY  (id),
            UNIQUE KEY queue_id (queue_id(100)),
            KEY status (status),
            KEY type (type),
            KEY scheduled_time (scheduled_time),
            KEY is_scheduled (is_scheduled)
        ) $charset_collate;";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

    /**
     * Create the internal links table
     */
    private static function create_internal_links_table()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'content_craft_ai_internal_links';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE IF NOT EXISTS {$table_name} (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            post_id bigint(20) NOT NULL,
            title text NOT NULL,
            link text NOT NULL,
            focus_keyword varchar(255) DEFAULT NULL,
            tags text DEFAULT NULL,
            updated_at datetime DEFAULT NULL,
            created_at datetime NOT NULL,
            PRIMARY KEY  (id),
            KEY post_id (post_id)
        ) $charset_collate;";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
}
