<?php
namespace ComptaFlowPro\Services;

defined('ABSPATH') || exit;

/**
 * Export Handler - Lite Version
 * 
 * Handles admin_post hooks for all LITE exports.
 * FEC export is only available in ComptaFlow Pro.
 */
class ExportHandler
{
    /**
     * Register admin_post hooks for all exports
     */
    public static function register(): void
    {
        // LITE exports only (no FEC)
        add_action('admin_post_comptaflow_export_balance', [self::class, 'handleBalance']);
        add_action('admin_post_comptaflow_export_journal', [self::class, 'handleJournal']);
        add_action('admin_post_comptaflow_export_grandlivre', [self::class, 'handleGrandLivre']);
        add_action('admin_post_comptaflow_export_resultat', [self::class, 'handleResultat']);
    }

    /**
     * Verify permissions and nonce
     */
    private static function verifyRequest(string $nonce_action): bool
    {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have sufficient permissions.', 'comptaflow-by-meetempo'), 403);
        }

        $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
        
        if (!wp_verify_nonce($nonce, $nonce_action)) {
            wp_die(esc_html__('Security check failed.', 'comptaflow-by-meetempo'), 403);
        }

        return true;
    }

    /**
     * Get and validate date parameters
     */
    private static function getDateParams(): array
    {
        $start = isset($_GET['start']) ? sanitize_text_field(wp_unslash($_GET['start'])) : gmdate('Y-01-01');
        $end = isset($_GET['end']) ? sanitize_text_field(wp_unslash($_GET['end'])) : gmdate('Y-12-31');

        // Validate date format YYYY-MM-DD
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $start)) {
            $start = gmdate('Y-01-01');
        }
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $end)) {
            $end = gmdate('Y-12-31');
        }

        return [
            'start' => $start,
            'end' => $end,
            'user_id' => get_current_user_id()
        ];
    }

    /**
     * Clean output buffers before export
     */
    private static function cleanBuffers(): void
    {
        while (ob_get_level()) {
            ob_end_clean();
        }
    }

    /**
     * Export Balance
     */
    public static function handleBalance(): void
    {
        self::verifyRequest('comptaflow_export_balance');
        $params = self::getDateParams();
        self::cleanBuffers();

        require_once COMPTAFLOW_PLUGIN_DIR . 'src/Services/BalanceExporter.php';
        BalanceExporter::export($params['user_id'], $params['start'], $params['end']);
        exit;
    }

    /**
     * Export Journal
     */
    public static function handleJournal(): void
    {
        self::verifyRequest('comptaflow_export_journal');
        $params = self::getDateParams();
        self::cleanBuffers();

        require_once COMPTAFLOW_PLUGIN_DIR . 'src/Services/JournalExporter.php';
        JournalExporter::export($params['user_id'], $params['start'], $params['end']);
        exit;
    }

    /**
     * Export Grand Livre (General Ledger)
     */
    public static function handleGrandLivre(): void
    {
        self::verifyRequest('comptaflow_export_grandlivre');
        $params = self::getDateParams();
        self::cleanBuffers();

        require_once COMPTAFLOW_PLUGIN_DIR . 'src/Services/GrandLivreExporter.php';
        GrandLivreExporter::export($params['user_id'], $params['start'], $params['end']);
        exit;
    }

    /**
     * Export Income Statement (Compte de Résultat)
     */
    public static function handleResultat(): void
    {
        self::verifyRequest('comptaflow_export_resultat');
        $params = self::getDateParams();
        self::cleanBuffers();

        require_once COMPTAFLOW_PLUGIN_DIR . 'src/Services/CompteResultatExporter.php';
        CompteResultatExporter::export($params['user_id'], $params['start'], $params['end']);
        exit;
    }
}
