<?php
if (!defined('ABSPATH')) exit;

function searchshifter_ensure_core_tables() {
    global $wpdb;

    $charset = $wpdb->get_charset_collate();

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';

    // SCANS TABLE
    $table1 = $wpdb->prefix . 'ss_scans';

    $sql1 = "CREATE TABLE $table1 (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        url TEXT NOT NULL,
        status VARCHAR(20) DEFAULT 'queued',
        log LONGTEXT,
        attempts INT DEFAULT 0,
        score INT NULL,
        finished_at DATETIME NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id)
    ) $charset;";

    dbDelta($sql1);

    // JOBS TABLE
    $table2 = $wpdb->prefix . 'ss_jobs';

    $sql2 = "CREATE TABLE $table2 (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        type VARCHAR(100),
        payload LONGTEXT,
        status VARCHAR(20) DEFAULT 'queued',
        attempts INT DEFAULT 0,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id)
    ) $charset;";

    dbDelta($sql2);
}

// Run on activation
register_activation_hook(__FILE__, 'searchshifter_ensure_core_tables');

// Backup safety
add_action('admin_init', function () {
    if (current_user_can('manage_options')) {
        searchshifter_ensure_core_tables();
    }
});