<?php

defined("ABSPATH") || exit();

class Chit_Activator
{
    public const DB_VERSION = "1.1";

    /**
     * Re-runs the schema when the plugin updates without a reactivation.
     */
    public static function maybe_upgrade(): void
    {
        if (get_option("chit_db_version") !== self::DB_VERSION) {
            self::activate();
        }
    }

    public static function activate()
    {
        require_once ABSPATH . "wp-admin/includes/upgrade.php";
        global $wpdb;
        $table = $wpdb->prefix . "chit_codes";
        $charset_collate = $wpdb->get_charset_collate();
        //
        // wp_chit_codes
        // ├── id            BIGINT UNSIGNED  PRIMARY KEY AUTO_INCREMENT
        // ├── product_id    BIGINT UNSIGNED  NOT NULL                    (WC product)
        // ├── code          VARCHAR(64)      NOT NULL  UNIQUE            (generated <= 20 chars; imported <= 64)
        // ├── status        VARCHAR(20)      NOT NULL  DEFAULT 'unused'  (unused|activated|revoked|expired)
        // ├── created_at    DATETIME         NOT NULL
        // ├── activated_at  DATETIME         NULL
        // ├── activated_by  BIGINT UNSIGNED  NULL                        (WP user id)
        // └── order_id      BIGINT UNSIGNED  NULL                        (WC order; NULL for imported history)
        $sql = "CREATE TABLE $table (
          id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
          product_id bigint(20) unsigned NOT NULL,
          code varchar(64) NOT NULL,
          status varchar(20) NOT NULL DEFAULT 'unused',
          created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
          activated_at datetime,
          activated_by BIGINT UNSIGNED,
          order_id BIGINT UNSIGNED,
          batch_id BIGINT UNSIGNED,
          PRIMARY KEY  (id),
          UNIQUE KEY name (code),
          KEY status (status),
          KEY product_id (product_id),
          KEY batch_id (batch_id)
        ) $charset_collate";
        dbDelta($sql);

        // Import batches span products, so product_id/quantity are nullable.
        $table = $wpdb->prefix . "chit_batches";
        $sql = "CREATE TABLE $table (
          id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
          product_id bigint(20) unsigned,
          quantity bigint(20) unsigned,
          source varchar(20) NOT NULL DEFAULT 'generated',
          note varchar(200),
          created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
          created_by BIGINT UNSIGNED,
          PRIMARY KEY  (id),
          KEY product_id (product_id),
          KEY created_at (created_at)
        ) $charset_collate";
        dbDelta($sql);

        // dbDelta widens columns but never drops a NOT NULL, so 1.0 installs
        // need explicit MODIFYs. Idempotent; matches the CREATE above.
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- $table from $wpdb->prefix, no user input
        $wpdb->query(
            "ALTER TABLE $table
              MODIFY product_id bigint(20) unsigned NULL,
              MODIFY quantity bigint(20) unsigned NULL"
        );
        // phpcs:enable

        update_option("chit_db_version", self::DB_VERSION);

        self::ensure_redeem_page();
    }

    private static function ensure_redeem_page(): void
    {
        $existing_id = (int) get_option("chit_redeem_page_id", 0);
        if ($existing_id) {
            $page = get_post($existing_id);
            if ($page && $page->post_status !== "trash") {
                return;
            }
        }

        $existing = get_posts([
            "post_type" => "page",
            "post_status" => "publish",
            "s" => "[chit_redeem]",
            "posts_per_page" => 1,
        ]);
        if (!empty($existing)) {
            update_option("chit_redeem_page_id", (int) $existing[0]->ID);
            return;
        }

        $page_id = wp_insert_post([
            "post_title" => "Redeem Chit Code",
            "post_content" => "[chit_redeem]",
            "post_status" => "publish",
            "post_type" => "page",
            "comment_status" => "closed",
            "ping_status" => "closed",
        ]);
        if (!is_wp_error($page_id) && (int) $page_id > 0) {
            update_option("chit_redeem_page_id", (int) $page_id);
        }
    }
}
