# Freefactu Extensions

This directory contains optional extensions for the Freefactu plugin.

## Directory Structure

Each extension should have its own folder with the following structure:

```
extensions/
├── extension-name/
│   ├── class-freefactu-{extension-name}.php   # Main extension class
│   ├── readme.txt                              # Extension documentation
│   └── assets/                                 # Extension-specific assets
```

## Available Extensions

### adjuntar-factura-correo/ - Adjuntar Factura en Correos
Automatically attaches invoice PDFs to WooCommerce emails.

**Features:**
- Automatic PDF attachment to configurable order emails
- Supports all WooCommerce email types (completed, invoice, processing, etc.)
- Custom attachment naming with placeholders ({invoice_number}, {order_id}, {date})
- Admin notification emails support
- Configuration via Configuración tab

**Settings Location:** Configuración tab → "Adjuntar Factura en Correos" section

### presupuestos/ - Generación de Presupuestos
Creates and manages professional quotes/estimates that can be converted to invoices.

**Features:**
- Quote creation with configurable numbering (prefix, suffix, padding)
- Professional PDF generation with company branding
- Quote validity period tracking with expiration dates
- Quote to invoice conversion workflow
- Action button in WooCommerce order list (similar to invoice button)
- Dedicated meta box in order view
- Full configuration section in Configuración tab
- Order snapshot for accurate quote data preservation

**Settings Location:** Configuración tab → "Generación de Presupuestos" section

**Hooks provided:**
- `freefactu_presupuesto_created` - Fires after a presupuesto is created
- `freefactu_presupuesto_converting` - Fires when converting to invoice

## Developing Extensions

Extensions are managed through the Extensions Manager class (`class-freefactu-extensions.php`) and loaded by the Extension Loader (`class-freefactu-extension-loader.php`).

### Extension Structure

1. **Main Class File**: `class-freefactu-{extension-name}.php`
   - Should follow WordPress coding standards
   - Use singleton pattern for initialization
   - Check if extension is active before initializing

2. **Registration**: Add extension definition in two places:
   - `Freefactu_Extensions::get_extensions()` - for UI display
   - `Freefactu_Extension_Loader::get_extension_definitions()` - for automatic loading

### Adding Settings to Configuración Tab

Extensions can add their own settings section to the Configuración tab using the `freefactu_settings_sections` action hook:

```php
// In your extension class
add_action( 'freefactu_settings_sections', array( $this, 'render_settings_section' ), 20 );

public function render_settings_section() {
    // Check if extension is active
    if ( ! Freefactu_Extensions::is_extension_active( 'your-extension-id' ) ) {
        return;
    }
    
    ?>
    <div class="freefactu-settings-section freefactu-extension-section">
        <h2>
            <span>🔧</span>
            <?php esc_html_e( 'Your Extension Name', 'freefactu' ); ?>
            <span class="freefactu-extension-badge"><?php esc_html_e( 'Extensión', 'freefactu' ); ?></span>
        </h2>
        <!-- Your settings fields here -->
    </div>
    <?php
}
```

### Available Hooks

**Actions:**
- `freefactu_settings_sections` - Add settings sections to Configuración tab
- `freefactu_numbering_sections` - Add numbering/series sections to Numeración tab
- `freefactu_extension_activated` - Fired when extension is activated
- `freefactu_extension_deactivated` - Fired when extension is deactivated
- `freefactu_extensions_loaded` - Fired after all extensions are loaded
- `freefactu_extension_loaded_{id}` - Fired after specific extension is loaded
- `freefactu_extension_init_{id}` - Fired when extension is being initialized
- `freefactu_extension_cleanup_{id}` - Fired when extension is being cleaned up

**Filters:**
- `freefactu_extensions` - Modify the list of available extensions
- `freefactu_extension_definitions` - Add/modify extension file definitions
- `freefactu_email_attachments` - Modify email attachments (from email attachment extension)

### Standalone Design

Extensions are designed to be standalone:

1. **Self-contained code**: All extension code lives in its folder
2. **No core modifications**: Extensions use hooks, not direct code changes
3. **Clean removal**: Deleting the extension folder completely removes it
4. **Graceful degradation**: Plugin works normally without any extensions

### Best Practices

1. **Check activation**: Always verify extension is active before running code
2. **Use hooks**: Never modify core files directly
3. **Register settings properly**: Use WordPress Settings API
4. **Clean up on deactivation**: Remove transients, scheduled events, etc.
5. **Prefix everything**: Use `freefactu_extensionname_` for options and hooks
6. **Translation ready**: Use `__()` and `esc_html_e()` for all strings

## Extension Activation Flow

1. User activates extension via Extensiones tab
2. `freefactu_extension_activated` action fires
3. Extension ID added to `freefactu_active_extensions` option
4. On next page load, Extension Loader includes the extension file
5. Extension class initializes and registers hooks

## Example Extension Template

```php
<?php
/**
 * My Extension
 *
 * @package Freefactu
 * @subpackage Extensions/MyExtension
 * @since 1.2.0
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Freefactu_My_Extension {

    private static $instance = null;
    const EXTENSION_ID = 'my-extension';
    const OPTION_KEY = 'freefactu_my_extension_settings';

    public static function instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        $this->init_hooks();
    }

    private function init_hooks() {
        // Your hooks here
        add_action( 'freefactu_settings_sections', array( $this, 'render_settings_section' ), 20 );
    }

    public function render_settings_section() {
        if ( ! Freefactu_Extensions::is_extension_active( self::EXTENSION_ID ) ) {
            return;
        }
        // Render your settings UI
    }
}

// Initialize only if active
if ( class_exists( 'Freefactu_Extensions' ) && 
     Freefactu_Extensions::is_extension_active( 'my-extension' ) ) {
    Freefactu_My_Extension::instance();
}
```

## Testing Extensions

1. Activate the extension via Extensiones tab
2. Verify settings appear in Configuración tab
3. Test extension functionality
4. Deactivate and verify graceful cleanup
5. Delete extension folder and verify plugin still works
