<?php
/**
 * Plugin activation and deactivation.
 *
 * @package FacturX_For_WooCommerce
 */

defined( 'ABSPATH' ) || exit;

class GOFACTOX_Activator {

    /**
     * Runs on plugin activation.
     */
    public static function activate(): void {
        // Register CPT so rewrite rules can be flushed.
        GOFACTOX_Invoice::register_post_type();

        // Create uploads directory.
        self::create_upload_dir();

        // Set default options.
        self::set_defaults();

        // Flush rewrite rules.
        flush_rewrite_rules();
    }

    /**
     * Runs on plugin deactivation.
     */
    public static function deactivate(): void {
        flush_rewrite_rules();
    }

    /**
     * Create the invoice uploads directory with protection.
     */
    private static function create_upload_dir(): void {
        $upload_dir = wp_upload_dir();
        $gofactox_dir   = $upload_dir['basedir'] . '/wfx-invoices';

        if ( ! file_exists( $gofactox_dir ) ) {
            wp_mkdir_p( $gofactox_dir );
        }

        // Protect directory from direct access.
        $htaccess = $gofactox_dir . '/.htaccess';
        if ( ! file_exists( $htaccess ) ) {
            file_put_contents( $htaccess, "Options -Indexes\nDeny from all\n" );
        }

        $index = $gofactox_dir . '/index.php';
        if ( ! file_exists( $index ) ) {
            file_put_contents( $index, "<?php\n// Silence is golden.\n" );
        }
    }

    /**
     * Set default plugin options.
     */
    private static function set_defaults(): void {
        $defaults = [
            'gofactox_company_name'          => '',
            'gofactox_legal_form'            => '',
            'gofactox_share_capital'         => '',
            'gofactox_address_line1'         => '',
            'gofactox_address_line2'         => '',
            'gofactox_postal_code'           => '',
            'gofactox_city'                  => '',
            'gofactox_country_code'          => 'FR',
            'gofactox_siret'                 => '',
            'gofactox_vat_number'            => '',
            'gofactox_rcs_city'              => '',
            'gofactox_invoice_prefix'        => 'F-',
            'gofactox_invoice_digits'        => 4,
            'gofactox_next_invoice_number'   => 1,
            'gofactox_auto_generate'         => 'yes',
            'gofactox_auto_generate_status'  => 'completed',
            'gofactox_attach_to_email'       => 'yes',
            'gofactox_output_format'         => 'facturx',
            'gofactox_enable_b2b_fields'     => 'yes',
            'gofactox_late_payment_rate'     => '',
            'gofactox_vat_exempt'            => 'no',
        ];

        foreach ( $defaults as $key => $value ) {
            if ( false === get_option( $key ) ) {
                add_option( $key, $value );
            }
        }
    }
}
