<?php
/**
 * Fired when the Agency Hub plugin is uninstalled.
 *
 * @package   WPCM_Agency_Hub
 */

// If uninstall not called from WordPress, exit.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
    exit;
}

global $wpdb;

// 1. Limpar todos os Custom Post Types (Sites, Perfis, Serviços)
$wpcm_cpt_slugs = array(
    'wpcm_hub_site',
    'wpcm_hub_service',
    'wpcm_hub_profile',
);

$wpcm_cpt_placeholders = implode( ', ', array_fill( 0, count( $wpcm_cpt_slugs ), '%s' ) );
$wpcm_sql_select = "SELECT ID FROM {$wpdb->prefix}posts WHERE post_type IN ( $wpcm_cpt_placeholders )";

// phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQL.NotPrepared
$wpcm_post_ids = $wpdb->get_col(
    $wpdb->prepare(
        $wpcm_sql_select,
        $wpcm_cpt_slugs
    )
);

if ( ! empty( $wpcm_post_ids ) ) {
    $wpcm_id_placeholders = implode( ', ', array_fill( 0, count( $wpcm_post_ids ), '%d' ) );
    
    // 1a. Deleta todos os metadados (postmeta) associados
    $wpcm_sql_delete_meta = "DELETE FROM {$wpdb->prefix}postmeta WHERE post_id IN ( $wpcm_id_placeholders )";
    
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQL.NotPrepared
    $wpdb->query(
        $wpdb->prepare( $wpcm_sql_delete_meta, $wpcm_post_ids )
    );
    
    // 1b. Deleta todos os posts (da tabela de posts)
    $wpcm_sql_delete_posts = "DELETE FROM {$wpdb->prefix}posts WHERE ID IN ( $wpcm_id_placeholders )";
    
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQL.NotPrepared
    $wpdb->query(
        $wpdb->prepare( $wpcm_sql_delete_posts, $wpcm_post_ids )
    );
}

// 2. Remover a tabela de log personalizada
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}wpcm_hub_logs" );

// 3. Remover as Opções (Options)
delete_option( 'wpcm_hub_global_settings' );
delete_option( 'wpcm_hub_setup_complete' );

// 4. Limpar as tarefas agendadas (Cron Jobs) do Action Scheduler
if ( function_exists( 'as_unschedule_all_actions' ) ) {
    as_unschedule_all_actions( 'wpcm_hub_sync_site_job' );
    as_unschedule_all_actions( '', array(), 'wpcm-hub-sync' );
}

// 5. Limpar o cache
wp_cache_flush();