<?php
namespace ComptaFlowUK\Services;

defined('ABSPATH') || exit;

/**
 * Export Handler
 *
 * Handles admin_post hooks for all CSV exports.
 */
class ExportHandler
{
    /**
     * Register admin_post hooks for all exports
     */
    public static function register(): void
    {
        // LITE exports only (basic reports)
        add_action('admin_post_comptaflow_uk_export_audit_trail', [self::class, 'handleAuditTrail']);
        add_action('admin_post_comptaflow_uk_export_balance', [self::class, 'handleBalance']);
        add_action('admin_post_comptaflow_uk_export_journal', [self::class, 'handleJournal']);
        add_action('admin_post_comptaflow_uk_export_nominal_ledger', [self::class, 'handleNominalLedger']);
        add_action('admin_post_comptaflow_uk_export_profit_loss', [self::class, 'handleProfitLoss']);
    }

    /**
     * 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-uk-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-uk-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_uk_export_balance');
        $params = self::getDateParams();
        self::cleanBuffers();

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

    /**
     * Export Audit Trail
     */
    public static function handleAuditTrail(): void
    {
        self::verifyRequest('comptaflow_uk_export_audit_trail');
        $params = self::getDateParams();
        self::cleanBuffers();

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

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

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

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

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

    /**
     * Export Income Statement (Profit & Loss)
     */
    public static function handleProfitLoss(): void
    {
        self::verifyRequest('comptaflow_uk_export_profit_loss');
        $params = self::getDateParams();
        self::cleanBuffers();

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