<?php
/**
 * FajaedeSEO Invoice Generator with VAT Support
 *
 * @package FajaedeSEO
 */

defined('ABSPATH') || exit;

if (!class_exists('FajaedeSEO_Invoice_Generator')) {

    class FajaedeSEO_Invoice_Generator {

        /**
         * Generate invoice HTML
         *
         * @param array $order_data Order and customer information
         * @return string HTML content
         */
        public static function generate_html(array $order_data) {
            $html = '<!DOCTYPE html>
<html lang="nl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice ' . esc_html($order_data['invoice_number']) . '</title>
    <style>
        * { margin: 0; padding: 0; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
            color: #333;
            background: #f5f5f5;
        }
        .invoice-container {
            max-width: 800px;
            margin: 20px auto;
            background: #fff;
            padding: 40px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 40px;
            border-bottom: 2px solid #0073aa;
            padding-bottom: 20px;
        }
        .company-info h1 {
            color: #0073aa;
            margin-bottom: 10px;
            font-size: 24px;
        }
        .company-info p {
            font-size: 12px;
            line-height: 1.6;
            color: #666;
        }
        .invoice-info {
            text-align: right;
        }
        .invoice-info h3 {
            color: #0073aa;
            margin-bottom: 5px;
        }
        .invoice-info p {
            font-size: 12px;
            color: #666;
            line-height: 1.8;
        }
        .section {
            margin-bottom: 30px;
        }
        .section h3 {
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 10px;
            color: #333;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .customer-info, .payment-info {
            font-size: 12px;
            line-height: 1.8;
            color: #666;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        th {
            background-color: #f9f9f9;
            border: 1px solid #ddd;
            padding: 10px;
            text-align: left;
            font-weight: 600;
            font-size: 12px;
            color: #333;
        }
        td {
            border: 1px solid #ddd;
            padding: 10px;
            font-size: 12px;
        }
        .text-right {
            text-align: right;
        }
        .subtotal-row {
            background-color: #fafafa;
            font-weight: 500;
        }
        .total-row {
            background-color: #0073aa;
            color: #fff;
            font-weight: bold;
            font-size: 14px;
        }
        .vat-info {
            background-color: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 12px;
            margin-top: 20px;
            font-size: 11px;
            line-height: 1.6;
            color: #666;
        }
        .footer {
            margin-top: 40px;
            padding-top: 20px;
            border-top: 1px solid #ddd;
            font-size: 11px;
            color: #999;
            text-align: center;
        }
        .reverse-charge-notice {
            background-color: #e7f3ff;
            border-left: 4px solid #0073aa;
            padding: 12px;
            margin-top: 20px;
            font-size: 11px;
            line-height: 1.6;
            color: #0073aa;
        }
        .export-notice {
            background-color: #d4edda;
            border-left: 4px solid #28a745;
            padding: 12px;
            margin-top: 20px;
            font-size: 11px;
            line-height: 1.6;
            color: #155724;
        }
    </style>
</head>
<body>
    <div class="invoice-container">
        <div class="header">
            <div class="company-info">
                <h1>INVOICE</h1>
                <p><strong>FajaedeSEO</strong><br>
                Limburg, Belgium<br>
                VAT: ' . esc_html(self::get_company_vat_number()) . '<br>
                <a href="https://www.fajaede.nl" style="color: #0073aa; text-decoration: none;">www.fajaede.nl</a></p>
            </div>
            <div class="invoice-info">
                <h3>Invoice Details</h3>
                <p><strong>Invoice #:</strong> ' . esc_html($order_data['invoice_number']) . '<br>
                <strong>Order ID:</strong> ' . esc_html($order_data['order_id']) . '<br>
                <strong>Date:</strong> ' . esc_html($order_data['invoice_date']) . '<br>
                <strong>Due Date:</strong> ' . esc_html($order_data['due_date']) . '</p>
            </div>
        </div>

        <div class="section">
            <h3>Bill To</h3>
            <div class="customer-info">
                <p><strong>' . esc_html($order_data['customer_name']) . '</strong><br>
                ' . esc_html($order_data['customer_email']) . '<br>
                ' . esc_html(self::get_country_name($order_data['country_code'])) . '</p>
                ' . (!empty($order_data['vat_number']) ? '<p><strong>VAT Number:</strong> ' . esc_html($order_data['vat_number']) . '</p>' : '') . '
            </div>
        </div>

        <table>
            <thead>
                <tr>
                    <th>Description</th>
                    <th class="text-right">Unit Price</th>
                    <th class="text-right">Quantity</th>
                    <th class="text-right">Total (excl. VAT)</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><strong>' . esc_html($order_data['product_name']) . '</strong><br>
                    <span style="color: #999; font-size: 11px;">Plan: ' . ucfirst(esc_html($order_data['plan_tier'])) . '</span></td>
                    <td class="text-right">€ ' . number_format($order_data['unit_price'], 2, ',', '.') . '</td>
                    <td class="text-right">1</td>
                    <td class="text-right">€ ' . number_format($order_data['price_excl_vat'], 2, ',', '.') . '</td>
                </tr>
            </tbody>
        </table>

        <table style="margin-top: 0;">
            <tbody>
                <tr class="subtotal-row">
                    <td colspan="3" style="border-right: none;"><strong>Subtotal (excl. VAT)</strong></td>
                    <td class="text-right" style="border-left: none;"><strong>€ ' . number_format($order_data['price_excl_vat'], 2, ',', '.') . '</strong></td>
                </tr>
                <tr class="subtotal-row">
                    <td colspan="3" style="border-right: none;"><strong>' . esc_html($order_data['vat_description']) . '</strong></td>
                    <td class="text-right" style="border-left: none;"><strong>€ ' . number_format($order_data['vat_amount'], 2, ',', '.') . '</strong></td>
                </tr>
                <tr class="total-row">
                    <td colspan="3" style="border-color: #0073aa;"><strong>TOTAL (incl. VAT)</strong></td>
                    <td class="text-right" style="border-color: #0073aa;"><strong>€ ' . number_format($order_data['price_incl_vat'], 2, ',', '.') . '</strong></td>
                </tr>
            </tbody>
        </table>';

        // Add VAT notices based on transaction type
        if ($order_data['is_reverse_charge']) {
            $html .= '
        <div class="reverse-charge-notice">
            <strong>VAT Reverse Charge Notice</strong><br>
            VAT reverse charge applies under Article 199a of the VAT Directive. The recipient is responsible for self-assessment of VAT.
        </div>';
        } elseif ($order_data['is_export']) {
            $html .= '
        <div class="export-notice">
            <strong>Export Transaction</strong><br>
            This is an export of services outside the EU. No VAT is charged. This transaction is registered as 0% VAT export under Belgian/EU export regulations.
        </div>';
        } else {
            $html .= '
        <div class="vat-info">
            <strong>VAT Information</strong><br>
            The VAT has been calculated in accordance with Belgian VAT law and the MOSS (Mini One-Stop Shop) procedure where applicable. The VAT amount shown above is based on the customer\'s residence country (' . esc_html(self::get_country_name($order_data['country_code'])) . ') and applicable VAT rates.
        </div>';
        }

        $html .= '
        <div class="section payment-info">
            <h3>Payment Information</h3>
            <p><strong>Payment Method:</strong> ' . esc_html($order_data['payment_method']) . '<br>
            <strong>Payment ID:</strong> ' . esc_html($order_data['payment_id']) . '<br>
            <strong>Status:</strong> Paid</p>
        </div>

        <div class="footer">
            <p>Thank you for your business!</p>
            <p style="margin-top: 10px;">FajaedeSEO AI - The GEO & AI Visibility Platform for WordPress<br>
            Invoice generated on ' . current_time('mysql') . '</p>
        </div>
    </div>
</body>
</html>';

            return $html;
        }

        /**
         * Generate PDF invoice (requires DOMPDF)
         *
         * @param array $order_data Order and customer information
         * @param string $output_path Where to save the PDF (optional)
         * @return mixed PDF as string or filename if saved
         */
        public static function generate_pdf(array $order_data, $output_path = null) {
            if (!class_exists('Dompdf\Dompdf')) {
                return false;
            }

            $html = self::generate_html($order_data);

            try {
                $dompdf = new \Dompdf\Dompdf([
                    'isPhpEnabled' => false,
                    'isRemoteEnabled' => true,
                ]);
                $dompdf->loadHtml($html);
                $dompdf->setPaper('A4', 'portrait');
                $dompdf->render();

                if ($output_path) {
                    file_put_contents($output_path, $dompdf->output());
                    return $output_path;
                }

                return $dompdf->output();
            } catch (\Exception $e) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
                error_log('DOMPDF Error: ' . $e->getMessage());
                return false;
            }
        }

        /**
         * Get company VAT number from options
         *
         * @return string
         */
        private static function get_company_vat_number() {
            return get_option('fajaedeseo_company_vat_number', 'BE0XXXXXXXXX');
        }

        /**
         * Get country name
         *
         * @param string $country_code
         * @return string
         */
        private static function get_country_name($country_code) {
            return \FajaedeSEO_VAT_Calculator::get_country_name($country_code);
        }

        /**
         * Format price for display
         *
         * @param float $amount
         * @return string
         */
        public static function format_price($amount) {
            return '€ ' . number_format($amount, 2, ',', '.');
        }

        /**
         * Create invoice data from license record
         *
         * @param object $license License record from database
         * @return array Order data ready for invoice generation
         */
        public static function prepare_invoice_data($license) {
            $user = get_user_by('id', $license->user_id);
            $email = $user ? $user->user_email : '';

            $total = (float) $license->amount;
            $vat_rate = floatval($license->vat_rate);
            
            if ($vat_rate > 0) {
                $price_excl_vat = $total / (1 + $vat_rate);
                $vat_amount = $total - $price_excl_vat;
            } else {
                $price_excl_vat = $total;
                $vat_amount = 0;
            }
            
            $is_b2b = !empty($license->vat_number) && $license->customer_type === 'onderneming';
            $is_eu = \FajaedeSEO_VAT_Calculator::is_eu_country($license->country_code);
            $is_reverse_charge = $is_b2b && $is_eu && $vat_rate == 0.0;
            $is_export = !\FajaedeSEO_VAT_Calculator::is_eu_country($license->country_code);

            return [
                'invoice_number' => $license->invoice_number,
                'order_id' => $license->invoice_number,
                'payment_id' => $license->payment_id,
                'invoice_date' => date_i18n('d F Y', strtotime($license->created_at)),
                'due_date' => date_i18n('d F Y', strtotime($license->created_at . ' +30 days')),
                'customer_name' => $user ? $user->display_name : 'Customer',
                'customer_email' => $email,
                'country_code' => $license->country_code,
                'vat_number' => $license->vat_number,
                'product_name' => 'FajaedeSEO AI - WordPress Plugin',
                'plan_tier' => $license->plan_level,
                'unit_price' => $price_excl_vat,
                'price_excl_vat' => $price_excl_vat,
                'vat_amount' => $vat_amount,
                'vat_rate' => $vat_rate,
                'price_incl_vat' => $total,
                'vat_description' => \FajaedeSEO_VAT_Calculator::get_vat_description(
                    $vat_rate,
                    $license->country_code,
                    $is_reverse_charge,
                    $is_export
                ),
                'payment_method' => 'Mollie',
                'is_reverse_charge' => $is_reverse_charge,
                'is_export' => $is_export,
            ];
        }
    }
}
