<?php
class PC_Community_Suggestions_Database {
    
    public static function create_tables() {
        global $wpdb;
        
        error_log('PC Community Suggestions: create_tables called');
        
        $charset_collate = $wpdb->get_charset_collate();
        
        $suggestions_table = $wpdb->prefix . 'pc_community_suggestions';
        $votes_table = $wpdb->prefix . 'pc_community_votes';
        $comments_table = $wpdb->prefix . 'pc_community_comments';
        
        error_log('PC Community Suggestions: Creating tables - ' . $suggestions_table . ', ' . $votes_table . ', ' . $comments_table);
        
        // Suggestions table
        $sql_suggestions = "CREATE TABLE IF NOT EXISTS $suggestions_table (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            user_id BIGINT UNSIGNED NOT NULL,
            title VARCHAR(255) NOT NULL,
            content TEXT NOT NULL,
            upvotes INT DEFAULT 0,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY user_id (user_id),
            KEY created_at (created_at),
            KEY upvotes (upvotes)
        ) $charset_collate;";
        
        // Votes table
        $sql_votes = "CREATE TABLE IF NOT EXISTS $votes_table (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            suggestion_id BIGINT UNSIGNED NOT NULL,
            user_id BIGINT UNSIGNED NOT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY user_suggestion (user_id, suggestion_id),
            KEY suggestion_id (suggestion_id)
        ) $charset_collate;";
        
        // Comments table
        $sql_comments = "CREATE TABLE IF NOT EXISTS $comments_table (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            suggestion_id BIGINT UNSIGNED NOT NULL,
            admin_id BIGINT UNSIGNED NOT NULL,
            comment TEXT NOT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY suggestion_id (suggestion_id),
            KEY admin_id (admin_id)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        
        // Clear any previous errors
        $wpdb->last_error = '';
        
        // Create tables directly using dbDelta
        dbDelta($sql_suggestions);
        dbDelta($sql_votes);
        dbDelta($sql_comments);
        
        // Log any errors for debugging
        if (!empty($wpdb->last_error)) {
            error_log('PC Community Suggestions Table Creation Error: ' . $wpdb->last_error);
        } else {
            error_log('PC Community Suggestions: Tables created without database errors');
        }
        
        // Verify tables were created
        $tables_created = true;
        $tables_to_check = array($suggestions_table, $votes_table, $comments_table);
        
        foreach ($tables_to_check as $table) {
            $exists = $wpdb->get_var("SHOW TABLES LIKE '$table'");
            if (!$exists) {
                error_log('PC Community Suggestions: Failed to create table ' . $table);
                $tables_created = false;
            } else {
                error_log('PC Community Suggestions: Table exists - ' . $table);
            }
        }
        
        return $tables_created;
    }
    
    public static function add_suggestion($user_id, $title, $content) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'pc_community_suggestions';
        
        error_log('PC Community Suggestions: add_suggestion called, table: ' . $table_name);
        error_log('PC Community Suggestions: user_id=' . $user_id . ', title=' . substr($title, 0, 50));
        
        // Check if table exists
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'");
        if (!$table_exists) {
            error_log('PC Community Suggestions: Table does not exist - ' . $table_name);
            error_log('PC Community Suggestions: Creating tables now...');
            self::create_tables();
            
            // Check again
            $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'");
            if (!$table_exists) {
                error_log('PC Community Suggestions: Still cannot find table after creation attempt');
                return false;
            }
        }
        
        $result = $wpdb->insert(
            $table_name,
            array(
                'user_id' => $user_id,
                'title' => sanitize_text_field($title),
                'content' => wp_kses_post($content)
            ),
            array('%d', '%s', '%s')
        );
        
        if ($result === false) {
            error_log('PC Community Suggestions: Failed to insert suggestion - ' . $wpdb->last_error);
            return false;
        }
        
        $insert_id = $wpdb->insert_id;
        error_log('PC Community Suggestions: Suggestion inserted with ID: ' . $insert_id);
        return $insert_id;
    }
    
    public static function get_suggestions($page = 1, $per_page = 10, $sort = 'popular') {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'pc_community_suggestions';
        $offset = ($page - 1) * $per_page;
        
        $order_by = $sort === 'newest' ? 'created_at DESC' : 'upvotes DESC, created_at DESC';
        
        $query = $wpdb->prepare(
            "SELECT s.*, u.user_login, u.display_name 
             FROM $table_name s 
             LEFT JOIN {$wpdb->users} u ON s.user_id = u.ID 
             ORDER BY $order_by 
             LIMIT %d OFFSET %d",
            $per_page,
            $offset
        );
        
        return $wpdb->get_results($query);
    }
    
    public static function get_suggestion_count() {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'pc_community_suggestions';
        
        return $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
    }
    
    public static function get_suggestion_by_id($suggestion_id) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'pc_community_suggestions';
        
        return $wpdb->get_row($wpdb->prepare(
            "SELECT s.*, u.user_login, u.display_name 
             FROM $table_name s 
             LEFT JOIN {$wpdb->users} u ON s.user_id = u.ID 
             WHERE s.id = %d",
            $suggestion_id
        ));
    }
    
    public static function add_vote($suggestion_id, $user_id) {
        global $wpdb;
        
        $votes_table = $wpdb->prefix . 'pc_community_votes';
        $suggestions_table = $wpdb->prefix . 'pc_community_suggestions';
        
        // Check if user already voted
        $existing_vote = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM $votes_table WHERE suggestion_id = %d AND user_id = %d",
                $suggestion_id,
                $user_id
            )
        );
        
        if ($existing_vote > 0) {
            return false;
        }
        
        $wpdb->query('START TRANSACTION');
        
        // Add vote
        $vote_result = $wpdb->insert(
            $votes_table,
            array(
                'suggestion_id' => $suggestion_id,
                'user_id' => $user_id
            ),
            array('%d', '%d')
        );
        
        if (!$vote_result) {
            $wpdb->query('ROLLBACK');
            return false;
        }
        
        // Update suggestion upvote count
        $update_result = $wpdb->query(
            $wpdb->prepare(
                "UPDATE $suggestions_table SET upvotes = upvotes + 1 WHERE id = %d",
                $suggestion_id
            )
        );
        
        if (!$update_result) {
            $wpdb->query('ROLLBACK');
            return false;
        }
        
        $wpdb->query('COMMIT');
        return true;
    }
    
    public static function get_user_vote_count($user_id) {
        global $wpdb;
        
        $votes_table = $wpdb->prefix . 'pc_community_votes';
        
        return $wpdb->get_var(
            $wpdb->prepare("SELECT COUNT(*) FROM $votes_table WHERE user_id = %d", $user_id)
        );
    }
    
    public static function has_user_voted($suggestion_id, $user_id) {
        global $wpdb;
        
        $votes_table = $wpdb->prefix . 'pc_community_votes';
        
        return (bool) $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM $votes_table WHERE suggestion_id = %d AND user_id = %d",
                $suggestion_id,
                $user_id
            )
        );
    }
    
    public static function add_comment($suggestion_id, $admin_id, $comment) {
        global $wpdb;
        
        $comments_table = $wpdb->prefix . 'pc_community_comments';
        
        return $wpdb->insert(
            $comments_table,
            array(
                'suggestion_id' => $suggestion_id,
                'admin_id' => $admin_id,
                'comment' => wp_kses_post($comment)
            ),
            array('%d', '%d', '%s')
        );
    }
    
    public static function get_comments($suggestion_id) {
        global $wpdb;
        
        $comments_table = $wpdb->prefix . 'pc_community_comments';
        
        return $wpdb->get_results($wpdb->prepare(
            "SELECT c.*, u.user_login, u.display_name 
             FROM $comments_table c 
             LEFT JOIN {$wpdb->users} u ON c.admin_id = u.ID 
             WHERE c.suggestion_id = %d 
             ORDER BY c.created_at ASC",
            $suggestion_id
        ));
    }
    
    public static function delete_comment($comment_id) {
        global $wpdb;
        
        $comments_table = $wpdb->prefix . 'pc_community_comments';
        
        return $wpdb->delete(
            $comments_table,
            array('id' => $comment_id),
            array('%d')
        );
    }
    
    public static function delete_suggestion($suggestion_id) {
        global $wpdb;
        
        $suggestions_table = $wpdb->prefix . 'pc_community_suggestions';
        $votes_table = $wpdb->prefix . 'pc_community_votes';
        $comments_table = $wpdb->prefix . 'pc_community_comments';
        
        $wpdb->query('START TRANSACTION');
        
        // Delete votes first
        $wpdb->delete($votes_table, array('suggestion_id' => $suggestion_id), array('%d'));
        
        // Delete comments
        $wpdb->delete($comments_table, array('suggestion_id' => $suggestion_id), array('%d'));
        
        // Delete suggestion
        $result = $wpdb->delete($suggestions_table, array('id' => $suggestion_id), array('%d'));
        
        if ($result === false) {
            $wpdb->query('ROLLBACK');
            return false;
        }
        
        $wpdb->query('COMMIT');
        return true;
    }
    
    public static function verify_tables() {
        global $wpdb;
        
        $suggestions_table = $wpdb->prefix . 'pc_community_suggestions';
        $votes_table = $wpdb->prefix . 'pc_community_votes';
        $comments_table = $wpdb->prefix . 'pc_community_comments';
        
        $tables_to_check = array($suggestions_table, $votes_table, $comments_table);
        $all_exist = true;
        
        foreach ($tables_to_check as $table) {
            $exists = $wpdb->get_var("SHOW TABLES LIKE '$table'");
            if (!$exists) {
                error_log('PC Community Suggestions: Missing table ' . $table);
                $all_exist = false;
            }
        }
        
        return $all_exist;
    }
}