<?php
/**
 * Freefactu Uninstall
 *
 * Removes plugin data based on user settings when the plugin is uninstalled.
 * Settings are configured in the "Configuración" tab under "Eliminación de Datos al Desinstalar".
 *
 * By default, all data is preserved (safe default for fiscal compliance).
 * Users must opt-in to delete specific data types.
 *
 * @package Freefactu
 */

// Exit if not called by WordPress uninstall - MUST be first check
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
    exit;
}

// Initialize WP_Filesystem
global $wp_filesystem;
if ( empty( $wp_filesystem ) ) {
    require_once ABSPATH . '/wp-admin/includes/file.php';
    WP_Filesystem();
}

global $wpdb;

// Get user settings (configured in the settings page)
$freefactu_options = get_option( 'freefactu_settings', array() );

// Read deletion preferences from settings (default: keep everything)
$freefactu_delete_invoices     = ! empty( $freefactu_options['delete_invoices_on_uninstall'] );
$freefactu_delete_series       = ! empty( $freefactu_options['delete_series_on_uninstall'] );
$freefactu_delete_declarations = ! empty( $freefactu_options['delete_declarations_on_uninstall'] );
$freefactu_delete_pdfs         = ! empty( $freefactu_options['delete_pdfs_on_uninstall'] );
$freefactu_delete_certificates = ! empty( $freefactu_options['delete_certificates_on_uninstall'] );
$freefactu_delete_settings     = ! empty( $freefactu_options['delete_settings_on_uninstall'] );

// Always delete transients (they are temporary anyway)
delete_transient( 'freefactu_table_exists' );

// Drop invoices table if user opted to delete invoices
if ( $freefactu_delete_invoices ) {
    $wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}freefactu_invoices" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
}

// Drop series table if user opted to delete series
if ( $freefactu_delete_series ) {
    $wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}freefactu_series" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
    // Also drop extension series table (used by presupuestos and other extensions)
    $wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}freefactu_extension_series" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
}

// Drop presupuestos (quotes/estimates) table if user opted to delete invoices
// Presupuestos are document-type data similar to invoices
if ( $freefactu_delete_invoices ) {
    $wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}freefactu_presupuestos" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
}

// Drop declarations table if user opted to delete declarations
if ( $freefactu_delete_declarations ) {
    $wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}freefactu_declarations" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
}

// Delete uploaded files based on user preferences
$freefactu_upload_dir = wp_upload_dir();

// Delete PDFs and declarations files if user opted to delete them
if ( $freefactu_delete_pdfs || $freefactu_delete_declarations ) {
    $freefactu_dir = $freefactu_upload_dir['basedir'] . '/freefactu';
    
    if ( $wp_filesystem->is_dir( $freefactu_dir ) ) {
        // If both should be deleted, remove entire directory
        if ( $freefactu_delete_pdfs && $freefactu_delete_declarations ) {
            $wp_filesystem->delete( $freefactu_dir, true );
        } else {
            // Selectively delete subdirectories
            if ( $freefactu_delete_pdfs && $wp_filesystem->is_dir( $freefactu_dir . '/invoices' ) ) {
                $wp_filesystem->delete( $freefactu_dir . '/invoices', true );
            }
            // Delete presupuestos (quotes) PDFs
            if ( $freefactu_delete_pdfs && $wp_filesystem->is_dir( $freefactu_dir . '/presupuestos' ) ) {
                $wp_filesystem->delete( $freefactu_dir . '/presupuestos', true );
            }
            if ( $freefactu_delete_declarations && $wp_filesystem->is_dir( $freefactu_dir . '/declarations' ) ) {
                $wp_filesystem->delete( $freefactu_dir . '/declarations', true );
            }
            
            // Check if directory is empty and remove it
            // Simple check: try to remove, if not empty it might fail or we can check content
            // WP_Filesystem->dirlist could be used but rmdir is safe if empty
            $freefactu_list = $wp_filesystem->dirlist( $freefactu_dir );
            if ( empty( $freefactu_list ) ) {
                $wp_filesystem->rmdir( $freefactu_dir );
            }
        }
    }
}

// Delete certificates if user opted to delete them
if ( $freefactu_delete_certificates ) {
    $freefactu_cert_dir = $freefactu_upload_dir['basedir'] . '/freefactu-certs';
    
    if ( $wp_filesystem->is_dir( $freefactu_cert_dir ) ) {
        $wp_filesystem->delete( $freefactu_cert_dir, true );
    }
}

// Delete plugin options if user opted to delete settings
if ( $freefactu_delete_settings ) {
    delete_option( 'freefactu_settings' );
    delete_option( 'freefactu_version' );
    delete_option( 'freefactu_system_requirements_ack' );
    // Delete extension settings
    delete_option( 'freefactu_presupuestos_settings' );
    delete_option( 'freefactu_active_extensions' );
}

// Clean up any legacy options that may exist
delete_option( 'freefactu_uninstall_preferences' );

/**
 * Recursively delete a directory and all its contents.
 *
 * @param string $dir Directory path to delete.
 * @return bool True on success, false on failure.
 */
function freefactu_recursive_delete( $dir ) {
    global $wp_filesystem;
    if ( empty( $wp_filesystem ) ) {
        require_once ABSPATH . '/wp-admin/includes/file.php';
        WP_Filesystem();
    }
    
    if ( ! $wp_filesystem || ! $wp_filesystem->is_dir( $dir ) ) {
        return false;
    }
    
    return $wp_filesystem->delete( $dir, true );
}

// Note: Order meta with _freefactu_ prefix is no longer used.
// All invoice data is stored in the wp_freefactu_invoices table,
// which is dropped above if the user opted to delete it.
