<?php
/**
 * HVAC Community Events - Communication Installer
 *
 * Handles database table creation and updates for communication system.
 * Creates tables for schedules, logs, and tracking.
 *
 * @package HVAC_Community_Events
 * @subpackage Communication
 * @version 1.0.0
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Class HVAC_Communication_Installer
 *
 * Manages database installation for communication system.
 */
class HVAC_Communication_Installer {

    /**
     * Database version
     */
    const DB_VERSION = '1.0.0';

    /**
     * Install database tables
     */
    public static function install() {
        global $wpdb;

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

        $charset_collate = $wpdb->get_charset_collate();

        self::create_schedules_table( $charset_collate );
        self::create_logs_table( $charset_collate );
        self::create_tracking_table( $charset_collate );

        // Update version option
        update_option( 'hvac_communication_db_version', self::DB_VERSION );

        if ( class_exists( 'HVAC_Logger' ) ) {
            HVAC_Logger::info( 'Communication system database tables installed', 'Communication Installer' );
        }
    }

    /**
     * Create communication schedules table
     *
     * @param string $charset_collate Database charset and collation
     */
    private static function create_schedules_table( $charset_collate ) {
        global $wpdb;

        $table_name = $wpdb->prefix . 'hvac_communication_schedules';

        $sql = "CREATE TABLE {$table_name} (
            schedule_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            trainer_id BIGINT(20) UNSIGNED NOT NULL,
            event_id BIGINT(20) UNSIGNED DEFAULT NULL,
            template_id BIGINT(20) UNSIGNED NOT NULL,
            schedule_name VARCHAR(255) NOT NULL DEFAULT '',
            schedule_type VARCHAR(50) NOT NULL DEFAULT 'time_based',
            trigger_type VARCHAR(50) NOT NULL,
            trigger_value INT(11) NOT NULL DEFAULT 0,
            trigger_unit VARCHAR(20) NOT NULL DEFAULT 'days',
            status VARCHAR(20) NOT NULL DEFAULT 'active',
            target_audience VARCHAR(50) NOT NULL DEFAULT 'all_attendees',
            custom_recipient_list TEXT DEFAULT NULL,
            conditions TEXT DEFAULT NULL,
            next_run DATETIME DEFAULT NULL,
            last_run DATETIME DEFAULT NULL,
            run_count INT(11) NOT NULL DEFAULT 0,
            is_recurring TINYINT(1) NOT NULL DEFAULT 0,
            recurring_interval INT(11) DEFAULT NULL,
            recurring_unit VARCHAR(20) DEFAULT NULL,
            max_runs INT(11) DEFAULT NULL,
            created_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            modified_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (schedule_id),
            KEY trainer_id (trainer_id),
            KEY event_id (event_id),
            KEY template_id (template_id),
            KEY status (status),
            KEY trigger_type (trigger_type),
            KEY next_run (next_run),
            KEY created_date (created_date)
        ) {$charset_collate};";

        dbDelta( $sql );
    }

    /**
     * Create communication logs table
     *
     * @param string $charset_collate Database charset and collation
     */
    private static function create_logs_table( $charset_collate ) {
        global $wpdb;

        $table_name = $wpdb->prefix . 'hvac_communication_logs';

        $sql = "CREATE TABLE {$table_name} (
            log_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            schedule_id BIGINT(20) UNSIGNED NOT NULL,
            recipient_email VARCHAR(255) DEFAULT NULL,
            status VARCHAR(20) NOT NULL,
            sent_date DATETIME NOT NULL,
            recipient_count INT(11) NOT NULL DEFAULT 0,
            success_count INT(11) NOT NULL DEFAULT 0,
            error_count INT(11) NOT NULL DEFAULT 0,
            execution_time DECIMAL(8,4) NOT NULL DEFAULT 0.0000,
            details TEXT DEFAULT NULL,
            PRIMARY KEY (log_id),
            KEY schedule_id (schedule_id),
            KEY status (status),
            KEY sent_date (sent_date),
            KEY recipient_email (recipient_email)
        ) {$charset_collate};";

        dbDelta( $sql );
    }

    /**
     * Create event communication tracking table
     *
     * @param string $charset_collate Database charset and collation
     */
    private static function create_tracking_table( $charset_collate ) {
        global $wpdb;

        $table_name = $wpdb->prefix . 'hvac_event_communication_tracking';

        $sql = "CREATE TABLE {$table_name} (
            tracking_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            event_id BIGINT(20) UNSIGNED NOT NULL,
            attendee_id BIGINT(20) UNSIGNED NOT NULL,
            schedule_id BIGINT(20) UNSIGNED NOT NULL,
            email VARCHAR(255) NOT NULL,
            sent_date DATETIME NOT NULL,
            delivery_status VARCHAR(20) NOT NULL DEFAULT 'sent',
            opened TINYINT(1) NOT NULL DEFAULT 0,
            opened_date DATETIME DEFAULT NULL,
            clicked TINYINT(1) NOT NULL DEFAULT 0,
            clicked_date DATETIME DEFAULT NULL,
            bounced TINYINT(1) NOT NULL DEFAULT 0,
            bounce_reason TEXT DEFAULT NULL,
            PRIMARY KEY (tracking_id),
            UNIQUE KEY event_attendee_schedule (event_id, attendee_id, schedule_id),
            KEY event_id (event_id),
            KEY attendee_id (attendee_id),
            KEY schedule_id (schedule_id),
            KEY email (email),
            KEY delivery_status (delivery_status),
            KEY sent_date (sent_date)
        ) {$charset_collate};";

        dbDelta( $sql );
    }

    /**
     * Check if tables need to be updated
     *
     * @return bool True if update needed
     */
    public static function needs_update() {
        $installed_version = get_option( 'hvac_communication_db_version', '0' );
        return version_compare( $installed_version, self::DB_VERSION, '<' );
    }

    /**
     * Update database tables if needed
     */
    public static function maybe_update() {
        if ( self::needs_update() ) {
            self::install();
        }
    }

    /**
     * Check if all required tables exist
     *
     * @return bool True if all tables exist
     */
    public static function tables_exist() {
        global $wpdb;

        $required_tables = array(
            $wpdb->prefix . 'hvac_communication_schedules',
            $wpdb->prefix . 'hvac_communication_logs',
            $wpdb->prefix . 'hvac_event_communication_tracking'
        );

        foreach ( $required_tables as $table ) {
            if ( $wpdb->get_var( "SHOW TABLES LIKE '{$table}'" ) !== $table ) {
                return false;
            }
        }

        return true;
    }

    /**
     * Drop all communication tables (for uninstall)
     */
    public static function drop_tables() {
        global $wpdb;

        $tables = array(
            $wpdb->prefix . 'hvac_communication_schedules',
            $wpdb->prefix . 'hvac_communication_logs',
            $wpdb->prefix . 'hvac_event_communication_tracking'
        );

        foreach ( $tables as $table ) {
            $wpdb->query( "DROP TABLE IF EXISTS {$table}" );
        }

        delete_option( 'hvac_communication_db_version' );

        if ( class_exists( 'HVAC_Logger' ) ) {
            HVAC_Logger::info( 'Communication system database tables dropped', 'Communication Installer' );
        }
    }

    /**
     * Get table status information
     *
     * @return array Table status information
     */
    public static function get_table_status() {
        global $wpdb;

        $tables = array(
            'schedules' => $wpdb->prefix . 'hvac_communication_schedules',
            'logs' => $wpdb->prefix . 'hvac_communication_logs',
            'tracking' => $wpdb->prefix . 'hvac_event_communication_tracking'
        );

        $status = array();

        foreach ( $tables as $key => $table_name ) {
            $exists = $wpdb->get_var( "SHOW TABLES LIKE '{$table_name}'" ) === $table_name;
            $count = 0;

            if ( $exists ) {
                $count = $wpdb->get_var( "SELECT COUNT(*) FROM {$table_name}" );
            }

            $status[$key] = array(
                'table_name' => $table_name,
                'exists' => $exists,
                'record_count' => intval( $count )
            );
        }

        $status['db_version'] = get_option( 'hvac_communication_db_version', '0' );
        $status['current_version'] = self::DB_VERSION;
        $status['needs_update'] = self::needs_update();

        return $status;
    }

    /**
     * Repair corrupted tables
     *
     * @return array Repair results
     */
    public static function repair_tables() {
        global $wpdb;

        $tables = array(
            $wpdb->prefix . 'hvac_communication_schedules',
            $wpdb->prefix . 'hvac_communication_logs',
            $wpdb->prefix . 'hvac_event_communication_tracking'
        );

        $results = array();

        foreach ( $tables as $table ) {
            $result = $wpdb->query( "REPAIR TABLE {$table}" );
            $results[$table] = $result !== false;
        }

        return $results;
    }

    /**
     * Optimize database tables
     *
     * @return array Optimization results
     */
    public static function optimize_tables() {
        global $wpdb;

        $tables = array(
            $wpdb->prefix . 'hvac_communication_schedules',
            $wpdb->prefix . 'hvac_communication_logs',
            $wpdb->prefix . 'hvac_event_communication_tracking'
        );

        $results = array();

        foreach ( $tables as $table ) {
            $result = $wpdb->query( "OPTIMIZE TABLE {$table}" );
            $results[$table] = $result !== false;
        }

        return $results;
    }

    /**
     * Get database size information
     *
     * @return array Database size information
     */
    public static function get_database_size() {
        global $wpdb;

        $tables = array(
            $wpdb->prefix . 'hvac_communication_schedules',
            $wpdb->prefix . 'hvac_communication_logs',
            $wpdb->prefix . 'hvac_event_communication_tracking'
        );

        $total_size = 0;
        $table_sizes = array();

        foreach ( $tables as $table ) {
            $size_result = $wpdb->get_row( 
                $wpdb->prepare( 
                    "SELECT 
                        ROUND(((data_length + index_length) / 1024 / 1024), 2) AS 'size_mb'
                     FROM information_schema.TABLES 
                     WHERE table_schema = %s 
                     AND table_name = %s",
                    DB_NAME,
                    $table
                )
            );

            $size_mb = $size_result ? floatval( $size_result->size_mb ) : 0;
            $table_sizes[$table] = $size_mb;
            $total_size += $size_mb;
        }

        return array(
            'total_size_mb' => round( $total_size, 2 ),
            'table_sizes' => $table_sizes
        );
    }

    /**
     * Create default communication schedules
     */
    public static function create_default_schedules() {
        // This would create some default schedule templates
        // For now, we'll just log that defaults would be created
        
        if ( class_exists( 'HVAC_Logger' ) ) {
            HVAC_Logger::info( 'Default communication schedules would be created here', 'Communication Installer' );
        }
    }

    /**
     * Migrate data from older versions
     *
     * @param string $from_version Version to migrate from
     */
    public static function migrate_data( $from_version ) {
        // Handle data migration between versions
        // For now, this is a placeholder
        
        if ( class_exists( 'HVAC_Logger' ) ) {
            HVAC_Logger::info( "Data migration from version {$from_version} to " . self::DB_VERSION, 'Communication Installer' );
        }
    }
}