<?php
namespace TCB;
if ( ! defined( 'ABSPATH' ) ) { exit; }

final class Installer {

    public static function t_partners(): string { global $wpdb; return $wpdb->prefix . 'tc_partners'; }
    public static function t_slots():    string { global $wpdb; return $wpdb->prefix . 'tc_booking_slots'; }
    public static function t_blocks():   string { global $wpdb; return $wpdb->prefix . 'tc_booking_blocks'; }
    public static function t_logs():     string { global $wpdb; return $wpdb->prefix . 'tc_booking_logs'; }
    public static function t_chat():     string { global $wpdb; return $wpdb->prefix . 'tc_booking_chat_messages'; }
    public static function t_requests(): string { global $wpdb; return $wpdb->prefix . 'tc_booking_requests'; }

    public static function activate(): void {
        self::create_tables();
        self::maybe_seed_default_partners();
        if ( get_option( 'tcb_booking_mode', '' ) === '' ) { update_option( 'tcb_booking_mode', 'simple' ); }
        if ( class_exists( '\TCB\DB\BookingsDAO' ) ) { \TCB\DB\BookingsDAO::repair_declined_released_slots(); }
        update_option( 'tcb_db_version', TCB_VERSION );
        flush_rewrite_rules();
    }

    public static function deactivate(): void { flush_rewrite_rules(); }

    public static function maybe_upgrade(): void {
        if ( get_option( 'tcb_db_version' ) !== TCB_VERSION ) {
            self::create_tables();
            self::mark_default_partners_seeded_for_existing_installs();
            if ( get_option( 'tcb_booking_mode', '' ) === '' ) { update_option( 'tcb_booking_mode', 'simple' ); }
            if ( class_exists( '\TCB\DB\BookingsDAO' ) ) { \TCB\DB\BookingsDAO::repair_declined_released_slots(); }
            update_option( 'tcb_db_version', TCB_VERSION );
        }
    }


    private static function maybe_seed_default_partners(): void {
        if ( get_option( 'tcb_default_partners_seeded', '' ) === 'yes' ) {
            return;
        }
        if ( class_exists( \TCB\Defaults\PartnerSeeder::class ) ) {
            \TCB\Defaults\PartnerSeeder::seed();
        }
        update_option( 'tcb_default_partners_seeded', 'yes' );
    }

    private static function mark_default_partners_seeded_for_existing_installs(): void {
        // Older builds seeded the default media partners on every page load, which made
        // deleted default partners appear again. From this version onward, defaults are
        // treated as normal editable/deletable rows and are never re-created on upgrade.
        if ( get_option( 'tcb_default_partners_seeded', '' ) !== 'yes' ) {
            update_option( 'tcb_default_partners_seeded', 'yes' );
        }
    }

    public static function create_tables(): void {
        global $wpdb;
        $cc = $wpdb->get_charset_collate();
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';

        dbDelta( "CREATE TABLE " . self::t_partners() . " (
            id             BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            name           VARCHAR(255) NOT NULL DEFAULT '',
            slug           VARCHAR(191) NOT NULL DEFAULT '',
            company_url    VARCHAR(500) NOT NULL DEFAULT '',
            logo_url       VARCHAR(500) NOT NULL DEFAULT '',
            email          VARCHAR(255) NOT NULL DEFAULT '',
            bio            LONGTEXT NULL,
            color          VARCHAR(20) NOT NULL DEFAULT '#e61a84',
            booking_open   TINYINT(1) NOT NULL DEFAULT 1,
            wp_user_id     BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
            encrypted_password LONGTEXT NULL,
            credentials_sent TINYINT(1) NOT NULL DEFAULT 0,
            credentials_sent_at DATETIME NULL,
            status         VARCHAR(20) NOT NULL DEFAULT 'active',
            created_at     DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY slug (slug),
            KEY email (email(191)),
            KEY wp_user_id (wp_user_id)
        ) $cc;" );

        dbDelta( "CREATE TABLE " . self::t_slots() . " (
            id             BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            event_id       BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
            partner_id     BIGINT(20) UNSIGNED NOT NULL,
            room           VARCHAR(150) NOT NULL DEFAULT '',
            slot_date      DATE NOT NULL,
            time_start     TIME NOT NULL,
            time_end       TIME NOT NULL,
            duration_mins  INT(11) NOT NULL DEFAULT 30,
            status         VARCHAR(20) NOT NULL DEFAULT 'available',
            speaker_id     BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
            created_at     DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY partner_id (partner_id),
            KEY slot_date (slot_date),
            KEY status (status)
        ) $cc;" );

        dbDelta( "CREATE TABLE " . self::t_blocks() . " (
            id             BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            slot_id        BIGINT(20) UNSIGNED NOT NULL,
            speaker_id     BIGINT(20) UNSIGNED NOT NULL,
            created_at     DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY slot_sp (slot_id, speaker_id)
        ) $cc;" );



        dbDelta( "CREATE TABLE " . self::t_requests() . " (
            id             BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            slot_id        BIGINT(20) UNSIGNED NOT NULL,
            partner_id     BIGINT(20) UNSIGNED NOT NULL,
            speaker_id     BIGINT(20) UNSIGNED NOT NULL,
            event_id       BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
            room           VARCHAR(150) NOT NULL DEFAULT '',
            slot_date      DATE NOT NULL,
            time_start     TIME NOT NULL,
            time_end       TIME NOT NULL,
            duration_mins  INT(11) NOT NULL DEFAULT 30,
            status         VARCHAR(20) NOT NULL DEFAULT 'pending',
            allow_rebook   TINYINT(1) NOT NULL DEFAULT 0,
            created_at     DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at     DATETIME NULL,
            PRIMARY KEY (id),
            KEY slot_id (slot_id),
            KEY partner_day_speaker (partner_id, slot_date, speaker_id),
            KEY status (status)
        ) $cc;" );

        dbDelta( "CREATE TABLE " . self::t_logs() . " (
            id             BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            slot_id        BIGINT(20) UNSIGNED NOT NULL,
            action         VARCHAR(50) NOT NULL DEFAULT '',
            user_id        BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
            notes          TEXT NULL,
            created_at     DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY slot_id (slot_id)
        ) $cc;" );


        dbDelta( "CREATE TABLE " . self::t_chat() . " (
            id             BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            slot_id        BIGINT(20) UNSIGNED NOT NULL,
            sender_user_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
            sender_role    VARCHAR(20) NOT NULL DEFAULT '',
            message        LONGTEXT NOT NULL,
            created_at     DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY slot_id (slot_id),
            KEY sender_user_id (sender_user_id),
            KEY created_at (created_at)
        ) $cc;" );
    }
}
