<?php

/**
 * Plugin Name: KleinBooks
 * Plugin URI: https://kleinbooks.de
 * Description: Simple accounting for German Kleinunternehmer. Invoicing, expenses, DATEV export.
 * Version: 1.9.1
 * Author: KleinBooks
 * Author URI: https://kleinbooks.de
 * License: GPL v2 or later
 * Text Domain: kleinbooks
 * Domain Path: /languages
 *
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
define( 'KLEINBOOKS_VERSION', '1.9.1' );
define( 'KLEINBOOKS_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'KLEINBOOKS_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'KLEINBOOKS_APP_SLUG', 'accounting' );
// Frontend URL: yoursite.com/accounting
/**
 * Freemius SDK bootstrap.
 *
 * Registers the KleinBooks product (Freemius ID 31786) and loads the SDK that
 * was installed via Composer at vendor/freemius/wordpress-sdk. Premium features
 * are gated with kb_fs()->is__premium_only() / can_use_premium_code(); Freemius
 * auto-generates the WordPress.org free build with all premium code stripped
 * (is_org_compliant = true).
 *
 * NOTE: the path is /vendor/freemius/wordpress-sdk/start.php (Composer layout),
 * not /vendor/freemius/start.php which Freemius emits for the manual install.
 * Flip 'has_paid_plans' => true once the paid plan is configured in Freemius.
 */
if ( !function_exists( 'kb_fs' ) ) {
    // Create a helper function for easy SDK access.
    function kb_fs() {
        global $kb_fs;
        if ( !isset( $kb_fs ) ) {
            // Include Freemius SDK.
            require_once dirname( __FILE__ ) . '/vendor/freemius/wordpress-sdk/start.php';
            $kb_fs = fs_dynamic_init( array(
                'id'               => '31786',
                'slug'             => 'kleinbooks',
                'type'             => 'plugin',
                'public_key'       => 'pk_b1fa16b94cec86e34a4dbb321ff2f',
                'is_premium'       => false,
                'premium_suffix'   => 'Pro',
                'has_addons'       => false,
                'has_paid_plans'   => true,
                'is_org_compliant' => true,
                'trial'            => array(
                    'days'               => 14,
                    'is_require_payment' => false,
                ),
                'menu'             => array(
                    'slug'    => 'kleinbooks',
                    'account' => false,
                    'support' => false,
                ),
                'is_live'          => true,
            ) );
        }
        return $kb_fs;
    }

    // Init Freemius.
    kb_fs();
    // Signal that SDK was initiated.
    do_action( 'kb_fs_loaded' );
    // KleinBooks targets DACH freelancers — default the in-dashboard pricing table +
    // checkout to EUR (USD stays available via the currency dropdown for others).
    kb_fs()->add_filter( 'default_currency', function () {
        return 'eur';
    } );
}
class KleinBooks_Main {
    private static $instance = null;

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

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

    private function load_dependencies() {
        require_once KLEINBOOKS_PLUGIN_DIR . 'includes/class-kleinbooks-database.php';
        require_once KLEINBOOKS_PLUGIN_DIR . 'includes/class-kleinbooks-rest-api.php';
        require_once KLEINBOOKS_PLUGIN_DIR . 'includes/class-kleinbooks-offers-api.php';
        require_once KLEINBOOKS_PLUGIN_DIR . 'includes/class-kleinbooks-pdf-generator.php';
    }

    private function init_hooks() {
        register_activation_hook( __FILE__, array($this, 'activate') );
        register_deactivation_hook( __FILE__, array($this, 'deactivate') );
        // Load translations
        add_action( 'plugins_loaded', array($this, 'load_textdomain') );
        // Check for plugin update and run migrations
        add_action( 'init', array($this, 'check_version') );
        // REST API
        add_action( 'rest_api_init', array('KleinBooks_REST_API', 'register_routes') );
        add_action( 'rest_api_init', array('KleinBooks_Offers_API', 'register_routes') );
        // Frontend app route
        add_action( 'init', array($this, 'add_rewrite_rules') );
        add_filter( 'query_vars', array($this, 'add_query_vars') );
        add_action( 'template_redirect', array($this, 'handle_frontend_route') );
        // Admin menu
        add_action( 'admin_menu', array($this, 'add_admin_menu') );
        add_action( 'admin_enqueue_scripts', array($this, 'enqueue_admin_assets') );
        add_action( 'admin_head', array($this, 'add_admin_menu_styles') );
    }

    public function activate() {
        // Create tables
        KleinBooks_Database::create_tables();
        KleinBooks_Database::insert_default_settings();
        // Add rewrite rules
        $this->add_rewrite_rules();
        flush_rewrite_rules();
        // Update version
        update_option( 'kleinbooks_version', KLEINBOOKS_VERSION );
    }

    public function deactivate() {
        flush_rewrite_rules();
    }

    /**
     * Load plugin translations
     */
    public function load_textdomain() {
        load_plugin_textdomain( 'kleinbooks', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
    }

    /**
     * Check plugin version and run updates if needed
     */
    public function check_version() {
        $installed_version = get_option( 'kleinbooks_version', '0' );
        if ( version_compare( $installed_version, KLEINBOOKS_VERSION, '<' ) ) {
            // Run table creation (dbDelta is safe to run on existing tables)
            KleinBooks_Database::create_tables();
            // Flush rewrite rules
            $this->add_rewrite_rules();
            flush_rewrite_rules();
            // Update version
            update_option( 'kleinbooks_version', KLEINBOOKS_VERSION );
        }
    }

    // ============ FRONTEND APP ============
    public function add_rewrite_rules() {
        add_rewrite_rule( '^' . KLEINBOOKS_APP_SLUG . '/?$', 'index.php?kleinbooks_app=1', 'top' );
        add_rewrite_rule( '^' . KLEINBOOKS_APP_SLUG . '/(.*)/?$', 'index.php?kleinbooks_app=1', 'top' );
    }

    public function add_query_vars( $vars ) {
        $vars[] = 'kleinbooks_app';
        return $vars;
    }

    public function handle_frontend_route() {
        if ( !get_query_var( 'kleinbooks_app' ) ) {
            return;
        }
        // Check if user is logged in and is admin
        if ( !is_user_logged_in() ) {
            wp_redirect( wp_login_url( home_url( '/' . KLEINBOOKS_APP_SLUG . '/' ) ) );
            exit;
        }
        if ( !current_user_can( 'manage_options' ) ) {
            wp_die( '<h1>Access Denied</h1><p>You do not have permission to access KleinBooks.</p>', 'Access Denied', array(
                'response' => 403,
            ) );
        }
        // Render the frontend app
        $this->render_frontend_app();
        exit;
    }

    public function render_frontend_app() {
        $asset_file = KLEINBOOKS_PLUGIN_DIR . 'assets/index.asset.php';
        if ( file_exists( $asset_file ) ) {
            $assets = (include $asset_file);
        } else {
            $assets = array(
                'dependencies' => array('wp-element', 'wp-components', 'wp-api-fetch'),
                'version'      => KLEINBOOKS_VERSION,
            );
        }
        // Version the stylesheet by its own mtime so style-only changes bust the
        // browser cache even when the JS bundle hash (index.asset.php) is unchanged.
        $css_path = KLEINBOOKS_PLUGIN_DIR . 'assets/index.css';
        $css_ver = ( file_exists( $css_path ) ? filemtime( $css_path ) : $assets['version'] );
        // Get site info
        $site_name = get_bloginfo( 'name' );
        $app_url = home_url( '/' . KLEINBOOKS_APP_SLUG . '/' );
        ?>
<!DOCTYPE html>
<html <?php 
        language_attributes();
        ?>>
<head>
    <meta charset="<?php 
        bloginfo( 'charset' );
        ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="robots" content="noindex, nofollow">
    <title>KleinBooks - <?php 
        echo esc_html( $site_name );
        ?></title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <?php 
        wp_head();
        ?>
    <style>
        /* Reset and base styles for standalone app */
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        html, body { height: 100%; }
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #0a0a0b;
            color: #f4f4f5;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }
        #kleinbooks-root {
            min-height: 100vh;
        }
        /* Hide WP admin bar on this page */
        #wpadminbar { display: none !important; }
        html { margin-top: 0 !important; }
    </style>
    <link rel="stylesheet" href="<?php 
        echo esc_url( KLEINBOOKS_PLUGIN_URL . 'assets/index.css?ver=' . $css_ver );
        ?>">
    <style>
        /* Custom overrides - MUST be after index.css */
        .mk-dashboard { max-width: 100% !important; }
        .mk-content { max-width: 100% !important; }

        /* Net income - use default text color instead of green */
        .mk-stat-card__change--positive {
            color: #a1a1aa !important;
        }
    </style>
</head>
<body class="kleinbooks-frontend">
    <div id="kleinbooks-root"></div>

    <script>
        var mkAccounting = {
            apiUrl: '<?php 
        echo esc_js( rest_url( 'kleinbooks/v1' ) );
        ?>',
            nonce: '<?php 
        echo esc_js( wp_create_nonce( 'wp_rest' ) );
        ?>',
            pluginUrl: '<?php 
        echo esc_js( KLEINBOOKS_PLUGIN_URL );
        ?>',
            appUrl: '<?php 
        echo esc_js( $app_url );
        ?>',
            currentYear: <?php 
        echo date( 'Y' );
        ?>,
            currency: 'EUR',
            currencySymbol: '€',
            locale: '<?php 
        echo esc_js( str_replace( '_', '-', get_user_locale() ) );
        ?>',
            isFrontend: true,
            pro: <?php 
        echo json_encode( array(
            'active'      => kb_fs()->can_use_premium_code(),
            'is_trial'    => kb_fs()->is_trial(),
            'is_paying'   => kb_fs()->is_paying(),
            'upgrade_url' => kb_fs()->get_upgrade_url(),
            'account_url' => kb_fs()->get_account_url(),
        ) );
        ?>,
            invoicePresets: <?php 
        echo json_encode( apply_filters( 'kleinbooks_invoice_presets', array() ) );
        ?>
        };
    </script>
    <?php 
        // Register and enqueue the app script with proper dependencies
        wp_register_script(
            'kleinbooks-app',
            KLEINBOOKS_PLUGIN_URL . 'assets/index.js',
            array('wp-element', 'wp-api-fetch', 'wp-i18n'),
            $assets['version'],
            true
        );
        // Set up JavaScript translations
        wp_set_script_translations( 'kleinbooks-app', 'kleinbooks', KLEINBOOKS_PLUGIN_DIR . 'languages' );
        // Enqueue the script
        wp_enqueue_script( 'kleinbooks-app' );
        // Print the scripts
        wp_print_scripts( array('kleinbooks-app') );
        wp_footer();
        ?>
</body>
</html>
        <?php 
    }

    // ============ ADMIN MENU ============
    public function add_admin_menu() {
        add_menu_page(
            __( 'KleinBooks', 'kleinbooks' ),
            __( 'KleinBooks', 'kleinbooks' ),
            'manage_options',
            'kleinbooks',
            array($this, 'render_help_page'),
            'dashicons-chart-area',
            30
        );
        add_submenu_page(
            'kleinbooks',
            __( 'Help & Info', 'kleinbooks' ),
            __( 'Help & Info', 'kleinbooks' ),
            'manage_options',
            'kleinbooks',
            array($this, 'render_help_page')
        );
        add_submenu_page(
            'kleinbooks',
            __( 'Email Log', 'kleinbooks' ),
            __( 'Email Log', 'kleinbooks' ),
            'manage_options',
            'kleinbooks-emails',
            array($this, 'render_email_log_page')
        );
    }

    public function add_admin_menu_styles() {
        // No custom styles needed for simplified menu
    }

    public function render_help_page() {
        $frontend_url = home_url( '/' . KLEINBOOKS_APP_SLUG . '/' );
        ?>
        <style>
            .mk-help-wrap {
                margin: 20px 20px 20px 0;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            }
            .mk-help-header {
                background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
                color: #fff;
                padding: 40px;
                border-radius: 12px;
                margin-bottom: 30px;
            }
            .mk-help-header h1 {
                margin: 0 0 10px 0;
                font-size: 28px;
                font-weight: 600;
                color: #fff;
            }
            .mk-help-header p {
                margin: 0;
                opacity: 0.8;
                font-size: 15px;
            }
            .mk-help-launch {
                display: inline-flex;
                align-items: center;
                gap: 8px;
                background: #fff;
                color: #1a1a2e;
                padding: 12px 24px;
                border-radius: 8px;
                text-decoration: none;
                font-weight: 600;
                font-size: 14px;
                margin-top: 20px;
                transition: transform 0.2s, box-shadow 0.2s;
            }
            .mk-help-launch:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(0,0,0,0.3);
                color: #1a1a2e;
            }
            .mk-help-card {
                background: #fff;
                border: 1px solid #e0e0e0;
                border-radius: 10px;
                padding: 28px;
                margin-bottom: 20px;
            }
            .mk-help-card h2 {
                margin: 0 0 16px 0;
                font-size: 18px;
                color: #1a1a2e;
                display: flex;
                align-items: center;
                gap: 10px;
            }
            .mk-help-card h2 .dashicons {
                color: #667eea;
            }
            .mk-help-card p, .mk-help-card li {
                color: #555;
                line-height: 1.7;
                font-size: 14px;
            }
            .mk-help-card ul {
                margin: 12px 0;
                padding-left: 20px;
            }
            .mk-help-card li {
                margin-bottom: 8px;
            }
            .mk-help-grid {
                display: grid;
                grid-template-columns: repeat(2, 1fr);
                gap: 20px;
            }
            @media (max-width: 782px) {
                .mk-help-grid { grid-template-columns: 1fr; }
            }
            .mk-help-table {
                width: 100%;
                border-collapse: collapse;
                margin: 16px 0;
                font-size: 13px;
            }
            .mk-help-table th, .mk-help-table td {
                text-align: left;
                padding: 10px 12px;
                border-bottom: 1px solid #eee;
            }
            .mk-help-table th {
                background: #f8f9fa;
                font-weight: 600;
                color: #333;
            }
            .mk-help-table code {
                background: #f0f0f0;
                padding: 2px 6px;
                border-radius: 4px;
                font-size: 12px;
            }
            .mk-tech-badge {
                display: inline-block;
                background: #e8f4fd;
                color: #1976d2;
                padding: 4px 10px;
                border-radius: 20px;
                font-size: 12px;
                font-weight: 500;
                margin: 2px;
            }
            .mk-tech-badge.react { background: #e3f2fd; color: #1565c0; }
            .mk-tech-badge.php { background: #f3e5f5; color: #7b1fa2; }
            .mk-tech-badge.mysql { background: #fff3e0; color: #e65100; }
            .mk-tech-badge.rest { background: #e8f5e9; color: #2e7d32; }
        </style>

        <div class="mk-help-wrap">
            <div class="mk-help-header">
                <h1>KleinBooks</h1>
                <p><?php 
        esc_html_e( 'Simple accounting for German Kleinunternehmer', 'kleinbooks' );
        ?></p>
                <div style="display: flex; gap: 12px; margin-top: 20px;">
                    <a href="<?php 
        echo esc_url( $frontend_url );
        ?>" class="mk-help-launch" target="_blank">
                        <span class="dashicons dashicons-external"></span>
                        <?php 
        esc_html_e( 'Launch Application', 'kleinbooks' );
        ?>
                    </a>
                </div>
            </div>

            <div class="mk-help-card">
                <h2><span class="dashicons dashicons-info-outline"></span> <?php 
        esc_html_e( 'About This Plugin', 'kleinbooks' );
        ?></h2>
                <p><?php 
        esc_html_e( 'KleinBooks is a modern, single-page application (SPA) built specifically for Kleinunternehmer in Germany. It provides comprehensive tools for managing clients, creating invoices, tracking expenses, and DATEV export.', 'kleinbooks' );
        ?></p>
                <p><strong><?php 
        esc_html_e( 'Version:', 'kleinbooks' );
        ?></strong> <?php 
        echo KLEINBOOKS_VERSION;
        ?> &nbsp;|&nbsp; <strong><?php 
        esc_html_e( 'Author:', 'kleinbooks' );
        ?></strong> KleinBooks Team</p>
            </div>

            <!-- Getting Started -->
            <div class="mk-help-card" style="border-left: 4px solid #667eea;">
                <h2><span class="dashicons dashicons-flag"></span> <?php 
        esc_html_e( 'Getting Started', 'kleinbooks' );
        ?></h2>
                <p style="margin-bottom: 20px;"><?php 
        esc_html_e( 'Follow these steps to set up KleinBooks:', 'kleinbooks' );
        ?></p>

                <div style="display: grid; gap: 16px;">
                    <div style="display: flex; gap: 16px; align-items: flex-start;">
                        <span style="background: #667eea; color: #fff; width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 600; flex-shrink: 0;">1</span>
                        <div>
                            <strong><?php 
        esc_html_e( 'Settings', 'kleinbooks' );
        ?></strong>
                            <p style="margin: 4px 0 0 0; color: #666;"><?php 
        esc_html_e( 'Fill in your company details, bank information (IBAN/BIC), Steuernummer, and tax reserve percentage for planning. Choose your invoice template and theme.', 'kleinbooks' );
        ?></p>
                        </div>
                    </div>

                    <div style="display: flex; gap: 16px; align-items: flex-start;">
                        <span style="background: #667eea; color: #fff; width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 600; flex-shrink: 0;">2</span>
                        <div>
                            <strong><?php 
        esc_html_e( 'Add Clients', 'kleinbooks' );
        ?></strong>
                            <p style="margin: 4px 0 0 0; color: #666;"><?php 
        esc_html_e( 'Go to Clients and add your first customer with name, address, and email.', 'kleinbooks' );
        ?></p>
                        </div>
                    </div>

                    <div style="display: flex; gap: 16px; align-items: flex-start;">
                        <span style="background: #667eea; color: #fff; width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 600; flex-shrink: 0;">3</span>
                        <div>
                            <strong><?php 
        esc_html_e( 'Create Invoice', 'kleinbooks' );
        ?></strong>
                            <p style="margin: 4px 0 0 0; color: #666;"><?php 
        esc_html_e( 'Go to Invoices → New Invoice. Select client, add line items, preview PDF, and send via email.', 'kleinbooks' );
        ?></p>
                        </div>
                    </div>

                    <div style="display: flex; gap: 16px; align-items: flex-start;">
                        <span style="background: #667eea; color: #fff; width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 600; flex-shrink: 0;">4</span>
                        <div>
                            <strong><?php 
        esc_html_e( 'Track Expenses', 'kleinbooks' );
        ?></strong>
                            <p style="margin: 4px 0 0 0; color: #666;"><?php 
        esc_html_e( 'Go to Expenses and log your business costs. Upload receipts (images or PDF) for each expense to keep records organized.', 'kleinbooks' );
        ?></p>
                        </div>
                    </div>

                    <div style="display: flex; gap: 16px; align-items: flex-start;">
                        <span style="background: #667eea; color: #fff; width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 600; flex-shrink: 0;">5</span>
                        <div>
                            <strong><?php 
        esc_html_e( 'DATEV Export', 'kleinbooks' );
        ?></strong>
                            <p style="margin: 4px 0 0 0; color: #666;"><?php 
        esc_html_e( 'Go to Taxes → DATEV Export. Select date range and download. Send the file to your Steuerberater for import.', 'kleinbooks' );
        ?></p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Compliance Info -->
            <div class="mk-help-card">
                <h2><span class="dashicons dashicons-shield"></span> <?php 
        esc_html_e( 'Compliance', 'kleinbooks' );
        ?></h2>
                <div class="mk-help-grid" style="margin-top: 16px;">
                    <div>
                        <strong style="color: #2e7d32;">GoBD-konform</strong>
                        <p style="margin: 4px 0 0 0; font-size: 13px; color: #666;"><?php 
        esc_html_e( 'Invoices are automatically locked after sending. Use Storno (cancellation) for corrections - this creates a proper audit trail.', 'kleinbooks' );
        ?></p>
                    </div>
                    <div>
                        <strong style="color: #1565c0;">DATEV EXTF 700</strong>
                        <p style="margin: 4px 0 0 0; font-size: 13px; color: #666;"><?php 
        esc_html_e( 'Export uses official Buchungsstapel format with SKR03/SKR04 accounts. Your Steuerberater can import directly.', 'kleinbooks' );
        ?></p>
                    </div>
                    <div>
                        <strong style="color: #7b1fa2;">ZUGFeRD 2.2</strong>
                        <p style="margin: 4px 0 0 0; font-size: 13px; color: #666;"><?php 
        esc_html_e( 'Enable in Settings for e-invoicing. Creates hybrid PDFs with embedded XML for B2B/B2G requirements.', 'kleinbooks' );
        ?></p>
                    </div>
                    <div>
                        <strong style="color: #e65100;">§19 UStG</strong>
                        <p style="margin: 4px 0 0 0; font-size: 13px; color: #666;"><?php 
        esc_html_e( 'Kleinunternehmer notice is automatically added to invoices. Dashboard tracks your €22,000 threshold.', 'kleinbooks' );
        ?></p>
                    </div>
                </div>
            </div>

            <div class="mk-help-grid">
                <div class="mk-help-card">
                    <h2><span class="dashicons dashicons-editor-code"></span> <?php 
        esc_html_e( 'Technology', 'kleinbooks' );
        ?></h2>
                    <div style="margin: 15px 0;">
                        <span class="mk-tech-badge react">React</span>
                        <span class="mk-tech-badge rest">REST API</span>
                        <span class="mk-tech-badge php">PHP 7.4+</span>
                        <span class="mk-tech-badge mysql">MySQL</span>
                    </div>
                    <p style="color: #888; font-size: 13px;"><?php 
        esc_html_e( 'Modern single-page application built on WordPress', 'kleinbooks' );
        ?></p>
                </div>

                <div class="mk-help-card">
                    <h2><span class="dashicons dashicons-portfolio"></span> <?php 
        esc_html_e( 'Features', 'kleinbooks' );
        ?></h2>
                    <ul>
                        <li><strong><?php 
        esc_html_e( 'Dashboard', 'kleinbooks' );
        ?></strong> - <?php 
        esc_html_e( 'Financial overview with charts', 'kleinbooks' );
        ?></li>
                        <li><strong><?php 
        esc_html_e( 'Invoices', 'kleinbooks' );
        ?></strong> - <?php 
        esc_html_e( 'Create, edit, send PDF via email', 'kleinbooks' );
        ?></li>
                        <li><strong><?php 
        esc_html_e( 'Clients', 'kleinbooks' );
        ?></strong> - <?php 
        esc_html_e( 'Manage client database', 'kleinbooks' );
        ?></li>
                        <li><strong><?php 
        esc_html_e( 'Expenses', 'kleinbooks' );
        ?></strong> - <?php 
        esc_html_e( 'Track business expenses', 'kleinbooks' );
        ?></li>
                        <li><strong><?php 
        esc_html_e( 'DATEV Export', 'kleinbooks' );
        ?></strong> - <?php 
        esc_html_e( 'Tax-ready export for Steuerberater', 'kleinbooks' );
        ?></li>
                        <li><strong>§19 UStG</strong> - <?php 
        esc_html_e( 'Kleinunternehmer threshold tracking', 'kleinbooks' );
        ?></li>
                    </ul>
                </div>
            </div>

            <!-- FAQ -->
            <div class="mk-help-card">
                <h2><span class="dashicons dashicons-editor-help"></span> <?php 
        esc_html_e( 'FAQ', 'kleinbooks' );
        ?></h2>
                <div style="display: grid; gap: 20px; margin-top: 16px;">
                    <div>
                        <strong><?php 
        esc_html_e( 'How do I correct a sent invoice?', 'kleinbooks' );
        ?></strong>
                        <p style="margin: 4px 0 0 0; color: #666; font-size: 13px;"><?php 
        esc_html_e( 'Use the "Storno" button to cancel the invoice. You can optionally create a correction invoice automatically. This is the GoBD-compliant way to handle corrections.', 'kleinbooks' );
        ?></p>
                    </div>
                    <div>
                        <strong><?php 
        esc_html_e( 'What is DATEV export?', 'kleinbooks' );
        ?></strong>
                        <p style="margin: 4px 0 0 0; color: #666; font-size: 13px;"><?php 
        esc_html_e( 'DATEV is the standard accounting software used by German Steuerberater. The export creates a file they can import directly, saving manual data entry.', 'kleinbooks' );
        ?></p>
                    </div>
                    <div>
                        <strong><?php 
        esc_html_e( 'Should I enable ZUGFeRD?', 'kleinbooks' );
        ?></strong>
                        <p style="margin: 4px 0 0 0; color: #666; font-size: 13px;"><?php 
        esc_html_e( 'Enable ZUGFeRD if you invoice businesses (B2B) or government (B2G). It embeds machine-readable data in your PDF for automated processing.', 'kleinbooks' );
        ?></p>
                    </div>
                    <div>
                        <strong><?php 
        esc_html_e( 'Where is my data stored?', 'kleinbooks' );
        ?></strong>
                        <p style="margin: 4px 0 0 0; color: #666; font-size: 13px;"><?php 
        esc_html_e( 'All data stays in your WordPress database on your server. KleinBooks has no cloud dependency - you have full control.', 'kleinbooks' );
        ?></p>
                    </div>
                </div>
            </div>
        </div>
        <?php 
    }

    public function enqueue_admin_assets( $hook ) {
        // Only on our admin page (though we redirect to frontend)
        if ( strpos( $hook, 'kleinbooks' ) === false ) {
            return;
        }
    }

    // ============ EMAIL LOG PAGE ============
    public function render_email_log_page() {
        global $wpdb;
        // Get email logs
        $emails_table = KleinBooks_Database::get_table_name( 'emails' );
        $invoices_table = KleinBooks_Database::get_table_name( 'invoices' );
        $emails = $wpdb->get_results( "\n            SELECT e.*, i.invoice_number\n            FROM {$emails_table} e\n            LEFT JOIN {$invoices_table} i ON e.invoice_id = i.id\n            ORDER BY e.sent_at DESC\n            LIMIT 100\n        " );
        // Count stats
        $total_sent = $wpdb->get_var( "SELECT COUNT(*) FROM {$emails_table} WHERE status = 'sent'" );
        $total_failed = $wpdb->get_var( "SELECT COUNT(*) FROM {$emails_table} WHERE status = 'failed'" );
        ?>
        <style>
            .mk-email-wrap {
                margin: 20px 20px 20px 0;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            }
            .mk-email-header {
                background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
                color: #fff;
                padding: 30px 40px;
                border-radius: 12px;
                margin-bottom: 30px;
            }
            .mk-email-header h1 {
                margin: 0 0 8px 0;
                font-size: 24px;
                font-weight: 600;
                color: #fff;
            }
            .mk-email-header p {
                margin: 0;
                opacity: 0.8;
                font-size: 14px;
            }
            .mk-email-stats {
                display: flex;
                gap: 24px;
                margin-top: 20px;
            }
            .mk-email-stat {
                background: rgba(2.5.345,255,0.1);
                padding: 12px 20px;
                border-radius: 8px;
            }
            .mk-email-stat strong {
                font-size: 24px;
                display: block;
            }
            .mk-email-stat span {
                font-size: 12px;
                opacity: 0.8;
            }
            .mk-email-card {
                background: #fff;
                border: 1px solid #e0e0e0;
                border-radius: 10px;
                padding: 24px;
                margin-bottom: 20px;
            }
            .mk-email-card h2 {
                margin: 0 0 20px 0;
                font-size: 16px;
                color: #1a1a2e;
                display: flex;
                align-items: center;
                gap: 10px;
            }
            .mk-email-card h2 .dashicons {
                color: #667eea;
            }
            .mk-email-table {
                width: 100%;
                border-collapse: collapse;
                font-size: 13px;
            }
            .mk-email-table th {
                text-align: left;
                padding: 12px 16px;
                background: #f8f9fa;
                border-bottom: 2px solid #e0e0e0;
                font-weight: 600;
                color: #333;
            }
            .mk-email-table td {
                padding: 12px 16px;
                border-bottom: 1px solid #eee;
                color: #555;
            }
            .mk-email-table tr:hover td {
                background: #f8f9fa;
            }
            .mk-status-badge {
                display: inline-block;
                padding: 4px 10px;
                border-radius: 20px;
                font-size: 11px;
                font-weight: 600;
            }
            .mk-status-badge.sent {
                background: #d4edda;
                color: #155724;
            }
            .mk-status-badge.failed {
                background: #f8d7da;
                color: #721c24;
            }
            .mk-empty {
                text-align: center;
                padding: 60px 40px;
                color: #888;
            }
            .mk-empty .dashicons {
                font-size: 64px;
                width: 64px;
                height: 64px;
                margin-bottom: 20px;
                opacity: 0.3;
            }
            .mk-empty h3 {
                margin: 0 0 8px 0;
                color: #555;
            }
            .mk-empty p {
                margin: 0;
                font-size: 14px;
            }
            .mk-info-box {
                background: #e8f4fd;
                border: 1px solid #b8daff;
                border-radius: 8px;
                padding: 16px 20px;
                margin-bottom: 20px;
                font-size: 14px;
                color: #004085;
            }
            .mk-info-box strong {
                display: block;
                margin-bottom: 4px;
            }
        </style>

        <div class="mk-email-wrap">
            <div class="mk-email-header">
                <h1><span class="dashicons dashicons-email" style="margin-right: 10px;"></span> <?php 
        esc_html_e( 'Email Log', 'kleinbooks' );
        ?></h1>
                <p><?php 
        esc_html_e( 'History of all invoice emails sent from the application', 'kleinbooks' );
        ?></p>
                <div class="mk-email-stats">
                    <div class="mk-email-stat">
                        <strong><?php 
        echo intval( $total_sent );
        ?></strong>
                        <span><?php 
        esc_html_e( 'Emails Sent', 'kleinbooks' );
        ?></span>
                    </div>
                    <div class="mk-email-stat">
                        <strong><?php 
        echo intval( $total_failed );
        ?></strong>
                        <span><?php 
        esc_html_e( 'Failed', 'kleinbooks' );
        ?></span>
                    </div>
                </div>
            </div>

            <div class="mk-info-box">
                <strong><?php 
        esc_html_e( 'How to send invoice emails:', 'kleinbooks' );
        ?></strong>
                <?php 
        printf( esc_html__( 'In the %sKleinBooks App%s, open an invoice and use the action menu (⋮) to send via email. The email will be sent to the client\'s email address with the PDF attached.', 'kleinbooks' ), '<a href="' . esc_url( home_url( '/' . KLEINBOOKS_APP_SLUG . '/' ) ) . '" target="_blank">', '</a>' );
        ?>
            </div>

            <div class="mk-email-card">
                <h2><span class="dashicons dashicons-list-view"></span> <?php 
        esc_html_e( 'Email History', 'kleinbooks' );
        ?></h2>

                <?php 
        if ( empty( $emails ) ) {
            ?>
                    <div class="mk-empty">
                        <span class="dashicons dashicons-email"></span>
                        <h3><?php 
            esc_html_e( 'No emails sent yet', 'kleinbooks' );
            ?></h3>
                        <p><?php 
            esc_html_e( 'When you send invoice emails from the app, they will appear here.', 'kleinbooks' );
            ?></p>
                    </div>
                <?php 
        } else {
            ?>
                    <table class="mk-email-table">
                        <thead>
                            <tr>
                                <th><?php 
            esc_html_e( 'Date & Time', 'kleinbooks' );
            ?></th>
                                <th><?php 
            esc_html_e( 'Invoice', 'kleinbooks' );
            ?></th>
                                <th><?php 
            esc_html_e( 'Recipient', 'kleinbooks' );
            ?></th>
                                <th><?php 
            esc_html_e( 'Subject', 'kleinbooks' );
            ?></th>
                                <th><?php 
            esc_html_e( 'Status', 'kleinbooks' );
            ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
            foreach ( $emails as $email ) {
                ?>
                                <tr>
                                    <td>
                                        <strong><?php 
                echo esc_html( date_i18n( 'd M Y', strtotime( $email->sent_at ) ) );
                ?></strong><br>
                                        <small style="color: #888;"><?php 
                echo esc_html( date_i18n( 'H:i', strtotime( $email->sent_at ) ) );
                ?></small>
                                    </td>
                                    <td><code style="background: #f0f0f0; padding: 2px 8px; border-radius: 4px;"><?php 
                echo esc_html( ( $email->invoice_number ?: '-' ) );
                ?></code></td>
                                    <td>
                                        <strong><?php 
                echo esc_html( $email->recipient_name );
                ?></strong><br>
                                        <small style="color: #888;"><?php 
                echo esc_html( $email->recipient_email );
                ?></small>
                                    </td>
                                    <td><?php 
                echo esc_html( $email->subject );
                ?></td>
                                    <td>
                                        <span class="mk-status-badge <?php 
                echo esc_attr( $email->status );
                ?>">
                                            <?php 
                echo esc_html( ucfirst( $email->status ) );
                ?>
                                        </span>
                                        <?php 
                if ( $email->status === 'failed' && $email->error_message ) {
                    ?>
                                            <br><small style="color: #dc3545; margin-top: 4px; display: inline-block;"><?php 
                    echo esc_html( $email->error_message );
                    ?></small>
                                        <?php 
                }
                ?>
                                    </td>
                                </tr>
                            <?php 
            }
            ?>
                        </tbody>
                    </table>
                <?php 
        }
        ?>
            </div>
        </div>
        <?php 
    }

    // ============ DATA IMPORT ============
    public function render_import_page() {
        $import_file = KLEINBOOKS_PLUGIN_DIR . 'imports/expenses-import.json';
        $has_import_file = file_exists( $import_file );
        $import_data = ( $has_import_file ? json_decode( file_get_contents( $import_file ), true ) : [] );
        // Handle import action
        $message = '';
        $message_type = '';
        if ( isset( $_POST['import_expenses'] ) && wp_verify_nonce( $_POST['_wpnonce'], 'mk_import_expenses' ) ) {
            $result = $this->import_expenses_from_json();
            if ( $result['success'] ) {
                $message = $result['message'];
                $message_type = 'success';
                // Refresh import data
                $import_data = ( file_exists( $import_file ) ? json_decode( file_get_contents( $import_file ), true ) : [] );
            } else {
                $message = $result['message'];
                $message_type = 'error';
            }
        }
        ?>
        <div class="wrap">
            <h1>Import Data</h1>

            <?php 
        if ( $message ) {
            ?>
                <div class="notice notice-<?php 
            echo ( $message_type === 'success' ? 'success' : 'error' );
            ?> is-dismissible">
                    <p><?php 
            echo esc_html( $message );
            ?></p>
                </div>
            <?php 
        }
        ?>

            <div class="mk-import-section" style="background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-top: 20px;">
                <h2 style="margin-top: 0;">Import Expenses</h2>
                <p>Import expenses from the JSON file located at: <code>imports/expenses-import.json</code></p>

                <?php 
        if ( $message_type === 'success' ) {
            ?>
                    <p style="color: #46b450;"><strong>Import complete!</strong> Go to the Expenses page to view imported data. Make sure to select the correct year filter.</p>
                <?php 
        } elseif ( $has_import_file && !empty( $import_data ) ) {
            ?>
                    <h3>Preview (<?php 
            echo count( $import_data );
            ?> expenses to import):</h3>
                    <table class="wp-list-table widefat fixed striped" style="margin-bottom: 20px;">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Description</th>
                                <th>Category</th>
                                <th>Vendor</th>
                                <th>Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
            foreach ( $import_data as $expense ) {
                ?>
                                <tr>
                                    <td><?php 
                echo esc_html( $expense['expense_date'] );
                ?></td>
                                    <td><?php 
                echo esc_html( $expense['description'] );
                ?></td>
                                    <td><?php 
                echo esc_html( $expense['category'] );
                ?></td>
                                    <td><?php 
                echo esc_html( $expense['vendor'] ?? '-' );
                ?></td>
                                    <td><strong><?php 
                echo number_format(
                    $expense['amount'],
                    2,
                    ',',
                    '.'
                );
                ?> €</strong></td>
                                </tr>
                            <?php 
            }
            ?>
                        </tbody>
                    </table>

                    <form method="post">
                        <?php 
            wp_nonce_field( 'mk_import_expenses' );
            ?>
                        <button type="submit" name="import_expenses" class="button button-primary button-large">
                            Import <?php 
            echo count( $import_data );
            ?> Expense(s)
                        </button>
                    </form>
                <?php 
        } elseif ( $message_type !== 'success' ) {
            ?>
                    <p style="color: #888;">No import file found or file is empty. Add expenses to <code>imports/expenses-import.json</code></p>
                <?php 
        }
        ?>
            </div>

            <div class="mk-import-section" style="background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-top: 20px;">
                <h2 style="margin-top: 0;">JSON Format</h2>
                <p>Use this format for the import file:</p>
                <pre style="background: #f5f5f5; padding: 15px; border-radius: 4px; overflow-x: auto;">[
    {
        "expense_date": "2025-09-30",
        "category": "equipment",
        "description": "AIAIAI TMA-2 Headphones",
        "amount": 210.00,
        "vendor": "AIAIAI ApS",
        "payment_method": "card",
        "is_recurring": false,
        "notes": "Order #W3816121"
    }
]</pre>
                <p><strong>Categories:</strong> software, equipment, office, travel, marketing, education, insurance, legal, tax, hosting, subscriptions, other</p>
            </div>
        </div>
        <?php 
    }

    // ============ DEVELOPER GUIDE PAGE ============
    public function render_developer_guide_page() {
        ?>
        <style>
            .mk-dev-wrap {
                margin: 20px 20px 20px 0;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                max-width: 100%;
            }
            .mk-dev-header {
                background: linear-gradient(135deg, #2d1b69 0%, #11998e 100%);
                color: #fff;
                padding: 40px;
                border-radius: 12px;
                margin-bottom: 30px;
            }
            .mk-dev-header h1 {
                margin: 0 0 10px 0;
                font-size: 28px;
                font-weight: 600;
                color: #fff;
            }
            .mk-dev-header p {
                margin: 0;
                opacity: 0.9;
                font-size: 15px;
            }
            .mk-dev-card {
                background: #fff;
                border: 1px solid #e0e0e0;
                border-radius: 10px;
                padding: 28px;
                margin-bottom: 24px;
            }
            .mk-dev-card h2 {
                margin: 0 0 20px 0;
                font-size: 18px;
                color: #1a1a2e;
                display: flex;
                align-items: center;
                gap: 10px;
                border-bottom: 2px solid #667eea;
                padding-bottom: 12px;
            }
            .mk-dev-card h2 .dashicons {
                color: #667eea;
            }
            .mk-dev-card h3 {
                font-size: 15px;
                color: #333;
                margin: 24px 0 12px 0;
            }
            .mk-dev-card p, .mk-dev-card li {
                color: #555;
                line-height: 1.8;
                font-size: 14px;
            }
            .mk-dev-card ul, .mk-dev-card ol {
                margin: 12px 0;
                padding-left: 24px;
            }
            .mk-dev-card li {
                margin-bottom: 8px;
            }
            .mk-code-block {
                background: #1a1a2e;
                color: #e0e0e0;
                padding: 20px;
                border-radius: 8px;
                font-family: 'Monaco', 'Consolas', monospace;
                font-size: 13px;
                overflow-x: auto;
                margin: 16px 0;
            }
            .mk-code-block .comment { color: #6a9955; }
            .mk-code-block .folder { color: #dcdcaa; }
            .mk-code-block .arrow { color: #569cd6; }
            .mk-code-block .important { color: #ce9178; }
            .mk-inline-code {
                background: #f0f0f0;
                padding: 2px 8px;
                border-radius: 4px;
                font-family: 'Monaco', 'Consolas', monospace;
                font-size: 12px;
                color: #c7254e;
            }
            .mk-compare-grid {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 20px;
                margin: 20px 0;
            }
            .mk-compare-box {
                background: #f8f9fa;
                border-radius: 8px;
                padding: 20px;
            }
            .mk-compare-box h4 {
                margin: 0 0 12px 0;
                font-size: 14px;
                color: #333;
            }
            .mk-compare-box.classic { border-left: 4px solid #6c757d; }
            .mk-compare-box.modern { border-left: 4px solid #667eea; }
            .mk-step-list {
                counter-reset: step-counter;
                list-style: none;
                padding-left: 0;
            }
            .mk-step-list li {
                counter-increment: step-counter;
                position: relative;
                padding-left: 50px;
                margin-bottom: 20px;
            }
            .mk-step-list li::before {
                content: counter(step-counter);
                position: absolute;
                left: 0;
                top: 0;
                width: 32px;
                height: 32px;
                background: #667eea;
                color: #fff;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-weight: 600;
                font-size: 14px;
            }
            .mk-tools-table {
                width: 100%;
                border-collapse: collapse;
                margin: 16px 0;
            }
            .mk-tools-table th, .mk-tools-table td {
                text-align: left;
                padding: 12px 16px;
                border-bottom: 1px solid #eee;
            }
            .mk-tools-table th {
                background: #f8f9fa;
                font-weight: 600;
                color: #333;
            }
            .mk-warning-box {
                background: #fff3cd;
                border: 1px solid #ffc107;
                border-radius: 8px;
                padding: 16px 20px;
                margin: 20px 0;
            }
            .mk-warning-box strong {
                color: #856404;
            }
            .mk-success-box {
                background: #d4edda;
                border: 1px solid #28a745;
                border-radius: 8px;
                padding: 16px 20px;
                margin: 20px 0;
            }
            .mk-flow-diagram {
                background: #f8f9fa;
                border-radius: 8px;
                padding: 24px;
                text-align: center;
                margin: 20px 0;
            }
            .mk-flow-step {
                display: inline-block;
                background: #fff;
                border: 2px solid #667eea;
                border-radius: 8px;
                padding: 12px 20px;
                margin: 8px;
                font-size: 13px;
            }
            .mk-flow-arrow {
                display: inline-block;
                color: #667eea;
                font-size: 20px;
                margin: 0 8px;
            }
            @media (max-width: 782px) {
                .mk-compare-grid { grid-template-columns: 1fr; }
            }
        </style>

        <div class="mk-dev-wrap">
            <div class="mk-dev-header">
                <h1><span class="dashicons dashicons-code-standards" style="margin-right: 10px;"></span> Developer Guide</h1>
                <p>Everything you need to know to modify, build, and deploy this plugin</p>
            </div>

            <!-- Why This Plugin is Different -->
            <div class="mk-dev-card">
                <h2><span class="dashicons dashicons-info-outline"></span> Why This Plugin is Different</h2>

                <p>This is a <strong>modern React-based plugin</strong>, not a classic WordPress plugin. Here's the key difference:</p>

                <div class="mk-compare-grid">
                    <div class="mk-compare-box classic">
                        <h4>Classic WordPress Plugin</h4>
                        <div class="mk-code-block">
<span class="folder">my-plugin/</span>
├── my-plugin.php    <span class="comment">← PHP code</span>
├── style.css        <span class="comment">← CSS you write directly</span>
└── script.js        <span class="comment">← JavaScript you write</span>
                        </div>
                        <p style="margin: 12px 0 0 0; font-size: 13px;"><strong>Workflow:</strong> Edit files → Upload → Done!</p>
                    </div>

                    <div class="mk-compare-box modern">
                        <h4>This Plugin (React/Build-based)</h4>
                        <div class="mk-code-block">
<span class="folder">mk-freelance-accounting/</span>
├── <span class="important">src/</span>              <span class="comment">← Source (React, SCSS)</span>
├── <span class="important">build/</span>            <span class="comment">← Compiled output</span>
├── node_modules/     <span class="comment">← Build tools (68K files!)</span>
└── mk-freelance...php
                        </div>
                        <p style="margin: 12px 0 0 0; font-size: 13px;"><strong>Workflow:</strong> Edit src/ → Build → Deploy build/</p>
                    </div>
                </div>
            </div>

            <!-- Why We Need a Build Process -->
            <div class="mk-dev-card">
                <h2><span class="dashicons dashicons-admin-tools"></span> Why We Need a Build Process</h2>

                <p><strong>Problem:</strong> Browsers don't understand modern code syntax:</p>

                <ul>
                    <li><strong>React/JSX</strong> → <code class="mk-inline-code">&lt;div className="box"&gt;</code> — This isn't valid browser JavaScript</li>
                    <li><strong>SCSS</strong> → <code class="mk-inline-code">$color: purple;</code> — Browsers don't know CSS variables like this</li>
                    <li><strong>Modern JS</strong> → <code class="mk-inline-code">import</code>, <code class="mk-inline-code">const</code>, arrow functions — Older browsers break</li>
                </ul>

                <p><strong>Solution:</strong> The build process <em>translates</em> modern code into browser-compatible code:</p>

                <div class="mk-flow-diagram">
                    <div class="mk-flow-step">src/pages/Expenses.js<br><small>React, JSX, modern JS</small></div>
                    <span class="mk-flow-arrow">→</span>
                    <div class="mk-flow-step">npm run build</div>
                    <span class="mk-flow-arrow">→</span>
                    <div class="mk-flow-step">build/index.js<br><small>Plain JavaScript</small></div>
                </div>

                <h3>What Each Tool Does</h3>
                <table class="mk-tools-table">
                    <tr>
                        <th>Tool</th>
                        <th>Purpose</th>
                    </tr>
                    <tr>
                        <td><strong>Node.js</strong></td>
                        <td>JavaScript runtime — runs build tools on your computer</td>
                    </tr>
                    <tr>
                        <td><strong>npm</strong></td>
                        <td>Package manager — downloads build tools</td>
                    </tr>
                    <tr>
                        <td><strong>npm install</strong></td>
                        <td>Downloads tools listed in package.json → creates node_modules/</td>
                    </tr>
                    <tr>
                        <td><strong>npm run build</strong></td>
                        <td>Runs wp-scripts which compiles src/ → build/</td>
                    </tr>
                    <tr>
                        <td><strong>wp-scripts</strong></td>
                        <td>WordPress's official build tool (uses Webpack)</td>
                    </tr>
                </table>
            </div>

            <!-- Plugin Structure -->
            <div class="mk-dev-card">
                <h2><span class="dashicons dashicons-portfolio"></span> Plugin Structure Explained</h2>

                <div class="mk-code-block">
<span class="folder">mk-freelance-accounting/</span>
│
├── <span class="important">src/</span>                        <span class="comment">← SOURCE CODE (what you edit)</span>
│   ├── index.js                <span class="comment">← Main React entry point</span>
│   ├── pages/                  <span class="comment">← React page components</span>
│   │   ├── Dashboard.js
│   │   ├── Invoices.js
│   │   ├── Expenses.js
│   │   └── ...
│   ├── components/             <span class="comment">← Reusable UI components</span>
│   └── styles/main.scss        <span class="comment">← SCSS styles</span>
│
├── <span class="important">build/</span>                      <span class="comment">← COMPILED OUTPUT (auto-generated)</span>
│   ├── index.js                <span class="comment">← Compiled JavaScript</span>
│   ├── index.css               <span class="comment">← Compiled CSS</span>
│   └── index.asset.php         <span class="comment">← Dependencies list</span>
│
├── <span class="folder">includes/</span>                   <span class="comment">← PHP CLASSES (edit directly)</span>
│   ├── class-kleinbooks-database.php
│   ├── class-kleinbooks-rest-api.php
│   └── class-kleinbooks-pdf-generator.php
│
├── <span class="folder">templates/</span>                  <span class="comment">← PDF TEMPLATES (edit directly)</span>
│   └── invoice-pdf.php
│
├── <span class="folder">vendor/</span>                     <span class="comment">← PHP LIBRARIES (dompdf)</span>
│
├── node_modules/               <span class="comment">← BUILD TOOLS ONLY - never deploy!</span>
├── package.json                <span class="comment">← Lists npm dependencies</span>
└── mk-freelance-accounting.php <span class="comment">← Main plugin file</span>
                </div>

                <div class="mk-warning-box">
                    <strong>⚠️ Important:</strong> The <code class="mk-inline-code">node_modules/</code> folder contains 68,000+ files needed only for building. <strong>Never upload this to WordPress!</strong>
                </div>
            </div>

            <!-- Step by Step: Making Changes -->
            <div class="mk-dev-card">
                <h2><span class="dashicons dashicons-edit"></span> Step by Step: Making Changes</h2>

                <h3>For PHP Changes (Backend/API)</h3>
                <p>PHP files can be edited directly — no build needed:</p>
                <ol class="mk-step-list">
                    <li>
                        <strong>Edit the PHP file</strong><br>
                        Files in <code class="mk-inline-code">includes/</code> or <code class="mk-inline-code">templates/</code>
                    </li>
                    <li>
                        <strong>Upload to WordPress</strong><br>
                        Changes take effect immediately
                    </li>
                </ol>

                <h3>For Frontend Changes (React/UI)</h3>
                <p>Frontend files need to be compiled:</p>
                <ol class="mk-step-list">
                    <li>
                        <strong>Edit source files</strong><br>
                        Make changes in <code class="mk-inline-code">src/</code> folder (e.g., src/pages/Expenses.js)
                    </li>
                    <li>
                        <strong>Install dependencies (first time only)</strong><br>
                        <div class="mk-code-block">cd /path/to/mk-freelance-accounting
npm install</div>
                    </li>
                    <li>
                        <strong>Build the project</strong><br>
                        <div class="mk-code-block">npm run build</div>
                        This creates new files in the <code class="mk-inline-code">build/</code> folder
                    </li>
                    <li>
                        <strong>Deploy to WordPress</strong><br>
                        Upload the entire plugin folder <strong>except</strong> node_modules/
                    </li>
                </ol>
            </div>

            <!-- Deployment Checklist -->
            <div class="mk-dev-card">
                <h2><span class="dashicons dashicons-upload"></span> Deployment Checklist</h2>

                <h3>What to Deploy (Upload to WordPress)</h3>
                <ul>
                    <li>✅ <code class="mk-inline-code">build/</code> — Compiled JavaScript & CSS</li>
                    <li>✅ <code class="mk-inline-code">includes/</code> — PHP classes</li>
                    <li>✅ <code class="mk-inline-code">templates/</code> — PDF templates</li>
                    <li>✅ <code class="mk-inline-code">vendor/</code> — PHP libraries (dompdf)</li>
                    <li>✅ <code class="mk-inline-code">assets/</code> — Images, fonts</li>
                    <li>✅ <code class="mk-inline-code">imports/</code> — Import folder</li>
                    <li>✅ <code class="mk-inline-code">mk-freelance-accounting.php</code> — Main plugin file</li>
                    <li>✅ <code class="mk-inline-code">package.json</code> — (optional, small file)</li>
                </ul>

                <h3>What NOT to Deploy</h3>
                <ul>
                    <li>❌ <code class="mk-inline-code">node_modules/</code> — 68,000+ files, only for building!</li>
                    <li>❌ <code class="mk-inline-code">package-lock.json</code> — Not needed in production</li>
                    <li>❌ <code class="mk-inline-code">src/</code> — Source code (optional, WordPress only uses build/)</li>
                </ul>

                <div class="mk-success-box">
                    <strong>✅ Pro Tip:</strong> Before uploading via FTP/FileZilla, delete <code class="mk-inline-code">node_modules/</code> from your deploy folder to avoid uploading 68K unnecessary files!
                </div>
            </div>

            <!-- Quick Reference Commands -->
            <div class="mk-dev-card">
                <h2><span class="dashicons dashicons-editor-code"></span> Quick Reference Commands</h2>

                <table class="mk-tools-table">
                    <tr>
                        <th>Command</th>
                        <th>When to Use</th>
                    </tr>
                    <tr>
                        <td><code class="mk-inline-code">npm install</code></td>
                        <td>First time setup, or after pulling new code with updated dependencies</td>
                    </tr>
                    <tr>
                        <td><code class="mk-inline-code">npm run build</code></td>
                        <td>After making changes to src/ files — creates production build</td>
                    </tr>
                    <tr>
                        <td><code class="mk-inline-code">npm run start</code></td>
                        <td>Development mode — auto-rebuilds when you save files (hot reload)</td>
                    </tr>
                </table>

                <h3>Prerequisites</h3>
                <p>You need <strong>Node.js</strong> installed on your computer:</p>
                <ul>
                    <li>Download from: <a href="https://nodejs.org" target="_blank">https://nodejs.org</a> (LTS version)</li>
                    <li>Or install via Homebrew (Mac): <code class="mk-inline-code">brew install node</code></li>
                </ul>
            </div>

            <!-- Troubleshooting -->
            <div class="mk-dev-card">
                <h2><span class="dashicons dashicons-sos"></span> Troubleshooting</h2>

                <h3>"npm: command not found"</h3>
                <p>Node.js is not installed. Download from <a href="https://nodejs.org" target="_blank">nodejs.org</a> and install.</p>

                <h3>"wp-scripts: command not found"</h3>
                <p>Dependencies not installed. Run <code class="mk-inline-code">npm install</code> first.</p>

                <h3>Changes not showing after upload</h3>
                <ul>
                    <li>Did you run <code class="mk-inline-code">npm run build</code>?</li>
                    <li>Did you upload the <code class="mk-inline-code">build/</code> folder?</li>
                    <li>Clear browser cache (Cmd+Shift+R or Ctrl+Shift+R)</li>
                </ul>

                <h3>FileZilla showing 68,000 files</h3>
                <p>You're uploading <code class="mk-inline-code">node_modules/</code> — delete it from your deploy folder first!</p>
            </div>

            <!-- Development Workflow Summary -->
            <div class="mk-dev-card">
                <h2><span class="dashicons dashicons-update"></span> Complete Workflow Summary</h2>

                <div class="mk-flow-diagram" style="text-align: left; padding: 30px;">
                    <ol style="margin: 0; padding-left: 24px; line-height: 2.2;">
                        <li>Edit files in <code class="mk-inline-code">src/</code> folder</li>
                        <li>Run <code class="mk-inline-code">npm run build</code> in terminal</li>
                        <li>Remove <code class="mk-inline-code">node_modules/</code> from deploy folder</li>
                        <li>Upload plugin folder to <code class="mk-inline-code">/wp-content/plugins/</code></li>
                        <li>Test in WordPress!</li>
                    </ol>
                </div>

                <p style="text-align: center; color: #667eea; font-weight: 600; margin-top: 20px;">
                    🎉 Now you know how to develop and deploy this plugin!
                </p>
            </div>

        </div>
        <?php 
    }

    public function render_indexing_page() {
        ?>
        <style>
            .mk-index-wrap {
                margin: 20px 20px 20px 0;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                max-width: 900px;
            }
            .mk-index-header {
                background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
                color: #fff;
                padding: 40px;
                border-radius: 12px;
                margin-bottom: 30px;
                border: 1px solid #f59e0b;
            }
            .mk-index-header h1 {
                margin: 0 0 10px 0;
                font-size: 28px;
                font-weight: 600;
                color: #fff;
            }
            .mk-index-header p {
                margin: 0;
                opacity: 0.8;
            }
            .mk-index-card {
                background: #fff;
                border: 1px solid #e0e0e0;
                border-radius: 10px;
                padding: 28px;
                margin-bottom: 24px;
            }
            .mk-index-card h2 {
                margin: 0 0 20px 0;
                font-size: 18px;
                color: #1a1a2e;
            }
            .mk-status-badge {
                display: inline-block;
                padding: 8px 16px;
                background: rgba(245, 158, 11, 0.15);
                color: #b45309;
                border-radius: 20px;
                font-weight: 600;
                font-size: 14px;
                margin-bottom: 16px;
            }
            .mk-index-table {
                width: 100%;
                border-collapse: collapse;
            }
            .mk-index-table th, .mk-index-table td {
                text-align: left;
                padding: 12px 16px;
                border-bottom: 1px solid #eee;
            }
            .mk-index-table th {
                background: #f8f9fa;
                font-weight: 600;
            }
            .mk-blocked {
                color: #22c55e;
                font-weight: 500;
            }
            .mk-code {
                background: #f0f0f0;
                padding: 2px 8px;
                border-radius: 4px;
                font-family: monospace;
                font-size: 12px;
            }
        </style>

        <div class="mk-index-wrap">
            <div class="mk-index-header">
                <h1><span class="dashicons dashicons-hidden" style="margin-right: 10px;"></span> Indexing Status</h1>
                <p>Google crawling and indexing status for all public pages</p>
            </div>

            <div class="mk-index-card">
                <span class="mk-status-badge">🛡️ DEVELOPMENT MODE - NOT INDEXED</span>
                <h2>Current Status</h2>
                <p>All public pages have <code class="mk-code">&lt;meta name="robots" content="noindex, nofollow"&gt;</code></p>
                <p style="color: #666;">This means Google and other search engines will NOT index these pages. Your private data stays private.</p>
            </div>

            <div class="mk-index-card">
                <h2>Page Status</h2>
                <table class="mk-index-table">
                    <thead>
                        <tr>
                            <th>Page</th>
                            <th>URL</th>
                            <th>Robot Meta</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>Landing Page (Dark)</td>
                            <td><code class="mk-code">/kleinbooks</code></td>
                            <td><code class="mk-code">noindex, nofollow</code></td>
                            <td><span class="mk-blocked">✓ Blocked</span></td>
                        </tr>
                        <tr>
                            <td>Landing Page (Light)</td>
                            <td><code class="mk-code">/kleinbooks-v2</code></td>
                            <td><code class="mk-code">noindex, nofollow</code></td>
                            <td><span class="mk-blocked">✓ Blocked</span></td>
                        </tr>
                        <tr>
                            <td>Accounting App</td>
                            <td><code class="mk-code">/accounting</code></td>
                            <td><code class="mk-code">noindex, nofollow</code></td>
                            <td><span class="mk-blocked">✓ Blocked</span></td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div class="mk-index-card">
                <h2>When Ready to Launch</h2>
                <p>When you're ready to make pages public, change the meta tag to:</p>
                <code class="mk-code" style="display: block; padding: 12px; margin-top: 12px;">&lt;meta name="robots" content="index, follow"&gt;</code>
            </div>
        </div>
        <?php 
    }

    public function import_expenses_from_json() {
        global $wpdb;
        $import_file = KLEINBOOKS_PLUGIN_DIR . 'imports/expenses-import.json';
        if ( !file_exists( $import_file ) ) {
            return [
                'success' => false,
                'message' => 'Import file not found',
            ];
        }
        $data = json_decode( file_get_contents( $import_file ), true );
        if ( !$data || !is_array( $data ) ) {
            return [
                'success' => false,
                'message' => 'Invalid JSON format',
            ];
        }
        $expenses_table = KleinBooks_Database::get_table_name( 'expenses' );
        $imported = 0;
        $skipped = 0;
        foreach ( $data as $expense ) {
            if ( empty( $expense['expense_date'] ) || empty( $expense['description'] ) || !isset( $expense['amount'] ) ) {
                $skipped++;
                continue;
            }
            $expense_year = (int) date( 'Y', strtotime( $expense['expense_date'] ) );
            // Check for duplicate (same date, description, amount)
            $existing = $wpdb->get_var( $wpdb->prepare(
                "SELECT id FROM {$expenses_table} WHERE expense_date = %s AND description = %s AND amount = %f",
                $expense['expense_date'],
                $expense['description'],
                $expense['amount']
            ) );
            if ( $existing ) {
                $skipped++;
                continue;
            }
            $wpdb->insert( $expenses_table, [
                'expense_date'        => $expense['expense_date'],
                'category'            => sanitize_text_field( $expense['category'] ?? 'other' ),
                'description'         => sanitize_text_field( $expense['description'] ),
                'amount'              => floatval( $expense['amount'] ),
                'vendor'              => sanitize_text_field( $expense['vendor'] ?? '' ),
                'payment_method'      => sanitize_text_field( $expense['payment_method'] ?? 'bank' ),
                'is_recurring'        => ( !empty( $expense['is_recurring'] ) ? 1 : 0 ),
                'recurring_frequency' => sanitize_text_field( $expense['recurring_frequency'] ?? '' ),
                'notes'               => sanitize_textarea_field( $expense['notes'] ?? '' ),
                'expense_year'        => $expense_year,
            ] );
            $imported++;
        }
        // Clear the import file after successful import
        if ( $imported > 0 ) {
            file_put_contents( $import_file, '[]' );
        }
        return [
            'success' => true,
            'message' => "Successfully imported {$imported} expense(s). Skipped {$skipped} (duplicates or invalid).",
        ];
    }

    // ============ EMAIL SENDING ============
    /**
     * Send invoice email with PDF attachment
     */
    public function send_invoice_email( $invoice_id ) {
        global $wpdb;
        $invoices_table = KleinBooks_Database::get_table_name( 'invoices' );
        $clients_table = KleinBooks_Database::get_table_name( 'clients' );
        $items_table = KleinBooks_Database::get_table_name( 'invoice_items' );
        // Get invoice with client
        $invoice = $wpdb->get_row( $wpdb->prepare( "\n            SELECT i.*, c.company_name, c.contact_name, c.email as client_email, c.address_line1, c.city, c.postal_code\n            FROM {$invoices_table} i\n            LEFT JOIN {$clients_table} c ON i.client_id = c.id\n            WHERE i.id = %d\n        ", $invoice_id ) );
        if ( !$invoice ) {
            return new WP_Error('not_found', 'Invoice not found');
        }
        if ( empty( $invoice->client_email ) ) {
            return new WP_Error('no_email', 'Client has no email address');
        }
        // Get invoice items
        $items = $wpdb->get_results( $wpdb->prepare( "\n            SELECT * FROM {$items_table} WHERE invoice_id = %d ORDER BY sort_order ASC\n        ", $invoice_id ) );
        // Get settings
        $company_name = KleinBooks_Database::get_setting( 'company_name', 'Your Company' );
        $company_email = KleinBooks_Database::get_setting( 'company_email', '' );
        $company_owner = KleinBooks_Database::get_setting( 'company_owner', '' );
        $bank_name = KleinBooks_Database::get_setting( 'bank_name', '' );
        $bank_iban = KleinBooks_Database::get_setting( 'bank_iban', '' );
        // Generate PDF
        try {
            $pdf_content = KleinBooks_PDF_Generator::generate( $invoice_id, 'string' );
        } catch ( Exception $e ) {
            return new WP_Error('pdf_error', 'Failed to generate PDF: ' . $e->getMessage());
        }
        if ( !$pdf_content ) {
            return new WP_Error('pdf_error', 'Failed to generate PDF');
        }
        // Save PDF temporarily
        $upload_dir = wp_upload_dir();
        $pdf_dir = $upload_dir['basedir'] . '/kleinbooks-pdfs';
        if ( !file_exists( $pdf_dir ) ) {
            wp_mkdir_p( $pdf_dir );
        }
        $pdf_path = $pdf_dir . '/' . $invoice->invoice_number . '.pdf';
        file_put_contents( $pdf_path, $pdf_content );
        // Prepare email
        $to = $invoice->client_email;
        $subject = sprintf( 'Rechnung %s von %s', $invoice->invoice_number, $company_name );
        // Build email body (German — client-facing)
        $body = sprintf( "Sehr geehrte(r) %s,", ( $invoice->contact_name ?: $invoice->company_name ) );
        $body .= "\n\n";
        $body .= sprintf( "anbei erhalten Sie unsere Rechnung %s.", $invoice->invoice_number );
        $body .= "\n\n";
        $body .= sprintf( "Betrag: %s €", number_format(
            $invoice->total,
            2,
            ',',
            '.'
        ) );
        $body .= "\n\n";
        if ( $bank_name && $bank_iban ) {
            $body .= "Bankverbindung:\n";
            $body .= sprintf( "%s\n", $bank_name );
            $body .= sprintf( "IBAN: %s", $bank_iban );
            $body .= "\n\n";
        }
        $body .= "Mit freundlichen Grüßen\n";
        $body .= ( $company_owner ?: $company_name );
        $headers = array('Content-Type: text/plain; charset=UTF-8');
        if ( $company_email ) {
            $headers[] = 'From: ' . $company_name . ' <' . $company_email . '>';
        }
        $attachments = array($pdf_path);
        // Send email
        $sent = wp_mail(
            $to,
            $subject,
            $body,
            $headers,
            $attachments
        );
        // Log email
        $emails_table = KleinBooks_Database::get_table_name( 'emails' );
        $wpdb->insert( $emails_table, array(
            'invoice_id'      => $invoice_id,
            'recipient_email' => $to,
            'recipient_name'  => $invoice->company_name,
            'subject'         => $subject,
            'body'            => $body,
            'status'          => ( $sent ? 'sent' : 'failed' ),
            'error_message'   => ( $sent ? '' : 'wp_mail returned false' ),
            'sent_at'         => current_time( 'mysql' ),
        ) );
        // Update invoice sent_at timestamp and status if needed
        if ( $sent ) {
            $update_data = array(
                'sent_at' => current_time( 'mysql' ),
            );
            // Change status to 'sent' if it was draft or pending
            if ( in_array( $invoice->status, array('draft', 'pending') ) ) {
                $update_data['status'] = 'sent';
            }
            $wpdb->update( $invoices_table, $update_data, array(
                'id' => $invoice_id,
            ) );
        }
        // Clean up PDF file (optional - keep for records)
        // unlink($pdf_path);
        if ( !$sent ) {
            return new WP_Error('send_failed', 'Failed to send email');
        }
        return true;
    }

    /**
     * Send an offer (Angebot) by email with the PDF attached.
     * Mirrors send_invoice_email but for the offers tables; German body (client-facing).
     * On success, stamps sent_at + flips a draft to 'sent'.
     */
    public function send_offer_email( $offer_id ) {
        global $wpdb;
        $offers_table = KleinBooks_Database::get_table_name( 'offers' );
        $clients_table = KleinBooks_Database::get_table_name( 'clients' );
        $offer = $wpdb->get_row( $wpdb->prepare( "\n            SELECT o.*, c.company_name, c.contact_name, c.email as client_email\n            FROM {$offers_table} o\n            LEFT JOIN {$clients_table} c ON o.client_id = c.id\n            WHERE o.id = %d\n        ", $offer_id ) );
        if ( !$offer ) {
            return new WP_Error('not_found', 'Offer not found');
        }
        if ( empty( $offer->client_email ) ) {
            return new WP_Error('no_email', __( 'Kunde hat keine E-Mail-Adresse hinterlegt.', 'kleinbooks' ));
        }
        $company_name = KleinBooks_Database::get_setting( 'company_name', 'Your Company' );
        $company_email = KleinBooks_Database::get_setting( 'company_email', '' );
        $company_owner = KleinBooks_Database::get_setting( 'company_owner', '' );
        // Generate offer PDF
        try {
            $pdf_content = KleinBooks_PDF_Generator::generate_offer( $offer_id, 'string' );
        } catch ( Exception $e ) {
            return new WP_Error('pdf_error', 'Failed to generate PDF: ' . $e->getMessage());
        }
        if ( !$pdf_content ) {
            return new WP_Error('pdf_error', 'Failed to generate PDF');
        }
        $upload_dir = wp_upload_dir();
        $pdf_dir = $upload_dir['basedir'] . '/kleinbooks-pdfs';
        if ( !file_exists( $pdf_dir ) ) {
            wp_mkdir_p( $pdf_dir );
        }
        $pdf_path = $pdf_dir . '/' . $offer->offer_number . '.pdf';
        file_put_contents( $pdf_path, $pdf_content );
        $to = $offer->client_email;
        $subject = sprintf( 'Angebot %s von %s', $offer->offer_number, $company_name );
        $valid_until = ( !empty( $offer->valid_until ) ? date( 'd.m.Y', strtotime( $offer->valid_until ) ) : '' );
        $body = sprintf( "Sehr geehrte(r) %s,", ( $offer->contact_name ?: $offer->company_name ) );
        $body .= "\n\n";
        $body .= sprintf( "anbei erhalten Sie unser Angebot %s.", $offer->offer_number );
        $body .= "\n\n";
        $body .= sprintf( "Angebotssumme: %s €", number_format(
            $offer->total,
            2,
            ',',
            '.'
        ) );
        if ( $valid_until ) {
            $body .= sprintf( "\nGültig bis: %s", $valid_until );
        }
        $body .= "\n\n";
        $body .= "Bei Fragen stehen wir Ihnen gerne zur Verfügung.";
        $body .= "\n\n";
        $body .= "Mit freundlichen Grüßen\n";
        $body .= ( $company_owner ?: $company_name );
        $headers = array('Content-Type: text/plain; charset=UTF-8');
        if ( $company_email ) {
            $headers[] = 'From: ' . $company_name . ' <' . $company_email . '>';
        }
        $sent = wp_mail(
            $to,
            $subject,
            $body,
            $headers,
            array($pdf_path)
        );
        // Log (emails table is keyed on invoice_id; offers log with NULL).
        $emails_table = KleinBooks_Database::get_table_name( 'emails' );
        $wpdb->insert( $emails_table, array(
            'invoice_id'      => null,
            'recipient_email' => $to,
            'recipient_name'  => $offer->company_name,
            'subject'         => $subject,
            'body'            => $body,
            'status'          => ( $sent ? 'sent' : 'failed' ),
            'error_message'   => ( $sent ? '' : 'wp_mail returned false' ),
            'sent_at'         => current_time( 'mysql' ),
        ) );
        if ( $sent ) {
            $update = array(
                'sent_at' => current_time( 'mysql' ),
            );
            if ( $offer->status === 'draft' ) {
                $update['status'] = 'sent';
            }
            $wpdb->update( $offers_table, $update, array(
                'id' => $offer_id,
            ) );
        }
        if ( !$sent ) {
            return new WP_Error('send_failed', 'Failed to send email');
        }
        return true;
    }

}

// Initialize
KleinBooks_Main::get_instance();