<?php
/**
 * ComptaFlow - Ecran de gestion des factures
 */

namespace ComptaFlowPro\Admin\Screens;

use ComptaFlowPro\Services\InvoiceService;
use ComptaFlowPro\Services\ClientService;
use ComptaFlowPro\Services\PDFGenerator;

defined('ABSPATH') || exit;

class InvoicesScreen {

    public static function render(): void {
        if (!current_user_can('manage_options')) {
            wp_die('Acces refuse.');
        }

        $action = isset($_GET['action']) ? sanitize_text_field(wp_unslash($_GET['action'])) : 'list';

        echo '<div class="wrap">';

        switch ($action) {
            case 'new':
            case 'edit':
                self::renderForm();
                break;
            case 'view':
                self::renderView();
                break;
            default:
                self::renderList();
                break;
        }

        echo '</div>';
    }

    /**
     * Traiter les actions POST et GET (redirections)
     * Appele via admin_init pour rediriger AVANT l'output WordPress
     */
    public static function handleActions(): void {
        // Actions POST (sauvegarde)
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['_wpnonce'])) {
            $nonce = sanitize_text_field(wp_unslash($_POST['_wpnonce']));

            if (wp_verify_nonce($nonce, 'cfp_save_invoice')) {
                self::handleSave();
                return;
            }
        }

        // Actions GET (valider, payer, supprimer, enregistrer compta, dupliquer)
        if (isset($_GET['do']) && isset($_GET['id']) && isset($_GET['_wpnonce'])) {
            $do = sanitize_text_field(wp_unslash($_GET['do']));
            $id = absint($_GET['id']);
            $nonce = sanitize_text_field(wp_unslash($_GET['_wpnonce']));

            if (!wp_verify_nonce($nonce, 'cfp_invoice_action_' . $id)) {
                return;
            }

            switch ($do) {
                case 'validate':
                    InvoiceService::validate($id);
                    wp_safe_redirect(admin_url('admin.php?page=comptaflow-invoices&message=validated'));
                    exit;

                case 'mark_paid':
                    $method = isset($_GET['method']) ? sanitize_text_field(wp_unslash($_GET['method'])) : 'VIREMENT';
                    InvoiceService::markAsPaid($id, null, $method);
                    wp_safe_redirect(admin_url('admin.php?page=comptaflow-invoices&message=paid'));
                    exit;

                case 'register_accounting':
                    $result = InvoiceService::registerToAccounting($id);
                    $msg = $result ? 'registered' : 'error_register';
                    wp_safe_redirect(admin_url('admin.php?page=comptaflow-invoices&message=' . $msg));
                    exit;

                case 'register_payment_accounting':
                    $method = isset($_GET['method']) ? sanitize_text_field(wp_unslash($_GET['method'])) : 'VIREMENT';
                    InvoiceService::registerPaymentToAccounting($id, $method);
                    wp_safe_redirect(admin_url('admin.php?page=comptaflow-invoices&message=payment_registered'));
                    exit;

                case 'delete':
                    InvoiceService::delete($id);
                    wp_safe_redirect(admin_url('admin.php?page=comptaflow-invoices&message=deleted'));
                    exit;

                case 'duplicate':
                    $new_id = InvoiceService::duplicate($id);
                    if ($new_id) {
                        wp_safe_redirect(admin_url('admin.php?page=comptaflow-invoices&action=edit&id=' . $new_id));
                    } else {
                        wp_safe_redirect(admin_url('admin.php?page=comptaflow-invoices&message=error'));
                    }
                    exit;
            }
        }
    }

    /**
     * Sauvegarder une facture
     */
    private static function handleSave(): void {
        $invoice_id = isset($_POST['invoice_id']) ? absint($_POST['invoice_id']) : 0;

        $data = [
            'client_id' => absint($_POST['client_id'] ?? 0),
            'date_invoice' => sanitize_text_field(wp_unslash($_POST['date_invoice'] ?? '')),
            'date_due' => sanitize_text_field(wp_unslash($_POST['date_due'] ?? '')),
            'notes' => sanitize_textarea_field(wp_unslash($_POST['notes'] ?? '')),
        ];

        // Recuperer les lignes
        $lines = [];
        $descriptions = isset($_POST['line_description']) ? array_map('sanitize_text_field', wp_unslash($_POST['line_description'])) : [];
        $quantities = isset($_POST['line_quantity']) ? array_map('sanitize_text_field', wp_unslash($_POST['line_quantity'])) : [];
        $prices = isset($_POST['line_unit_price_ht']) ? array_map('sanitize_text_field', wp_unslash($_POST['line_unit_price_ht'])) : [];
        $vat_rates = isset($_POST['line_vat_rate']) ? array_map('sanitize_text_field', wp_unslash($_POST['line_vat_rate'])) : [];
        $account_codes = isset($_POST['line_account_code']) ? array_map('sanitize_text_field', wp_unslash($_POST['line_account_code'])) : [];

        for ($i = 0; $i < count($descriptions); $i++) {
            if (empty($descriptions[$i])) {
                continue;
            }
            $lines[] = [
                'description' => $descriptions[$i],
                'quantity' => $quantities[$i] ?? 1,
                'unit_price_ht' => $prices[$i] ?? 0,
                'vat_rate' => $vat_rates[$i] ?? 20,
                'account_code' => $account_codes[$i] ?? '706',
            ];
        }

        if ($invoice_id > 0) {
            $result = InvoiceService::update($invoice_id, $data, $lines);
            if ($result) {
                wp_safe_redirect(admin_url('admin.php?page=comptaflow-invoices&message=updated'));
                exit;
            }
        } else {
            $result = InvoiceService::create($data, $lines);
            if ($result) {
                wp_safe_redirect(admin_url('admin.php?page=comptaflow-invoices&action=view&id=' . $result . '&message=created'));
                exit;
            }
        }

        wp_safe_redirect(admin_url('admin.php?page=comptaflow-invoices&message=error'));
        exit;
    }

    /**
     * Afficher la liste des factures
     */
    private static function renderList(): void {
        // Mettre a jour les factures en retard
        InvoiceService::updateOverdueStatus();

        $status_filter = isset($_GET['status']) ? sanitize_text_field(wp_unslash($_GET['status'])) : '';
        $args = [];
        if (!empty($status_filter)) {
            $args['status'] = $status_filter;
        }

        $invoices = InvoiceService::getAll($args);
        $stats = InvoiceService::getStats();
        $message = isset($_GET['message']) ? sanitize_text_field(wp_unslash($_GET['message'])) : '';

        echo '<h1>';
        echo esc_html('Factures');
        echo ' <a href="' . esc_url(admin_url('admin.php?page=comptaflow-invoices&action=new')) . '" class="page-title-action">Nouvelle facture</a>';
        echo '</h1>';

        // Messages
        $messages = [
            'created' => ['success', 'Facture creee avec succes.'],
            'updated' => ['success', 'Facture mise a jour.'],
            'validated' => ['success', 'Facture validee.'],
            'paid' => ['success', 'Facture marquee comme payee.'],
            'registered' => ['success', 'Facture enregistree en comptabilite.'],
            'payment_registered' => ['success', 'Paiement enregistre en comptabilite.'],
            'deleted' => ['success', 'Facture supprimee.'],
            'error_register' => ['error', 'Erreur lors de l\'enregistrement comptable.'],
            'error' => ['error', 'Une erreur est survenue.'],
        ];

        if (isset($messages[$message])) {
            echo '<div class="notice notice-' . esc_attr($messages[$message][0]) . ' is-dismissible"><p>' . esc_html($messages[$message][1]) . '</p></div>';
        }

        // KPIs
        echo '<div style="display: flex; gap: 15px; margin: 20px 0;">';
        $kpis = [
            ['Brouillons', $stats['draft']['count'], '#999'],
            ['En attente', $stats['pending']['count'], '#f08c00'],
            ['En retard', $stats['overdue']['count'], '#e03131'],
            ['Payees', $stats['paid']['count'], '#00875a'],
            ['Impaye total', number_format($stats['unpaid']['total'], 2, ',', ' ') . ' €', '#d63638'],
        ];
        foreach ($kpis as $kpi) {
            echo '<div style="background: #fff; border: 1px solid #ddd; border-left: 4px solid ' . esc_attr($kpi[2]) . '; padding: 12px 16px; border-radius: 4px; min-width: 140px;">';
            echo '<div style="font-size: 20px; font-weight: bold; color: ' . esc_attr($kpi[2]) . ';">' . esc_html($kpi[1]) . '</div>';
            echo '<div style="font-size: 11px; color: #666;">' . esc_html($kpi[0]) . '</div>';
            echo '</div>';
        }
        echo '</div>';

        // Filtres par statut
        $base_url = admin_url('admin.php?page=comptaflow-invoices');
        echo '<ul class="subsubsub">';
        echo '<li><a href="' . esc_url($base_url) . '"' . ($status_filter === '' ? ' class="current"' : '') . '>Toutes</a> | </li>';
        echo '<li><a href="' . esc_url($base_url . '&status=DRAFT') . '"' . ($status_filter === 'DRAFT' ? ' class="current"' : '') . '>Brouillons</a> | </li>';
        echo '<li><a href="' . esc_url($base_url . '&status=PENDING') . '"' . ($status_filter === 'PENDING' ? ' class="current"' : '') . '>En attente</a> | </li>';
        echo '<li><a href="' . esc_url($base_url . '&status=OVERDUE') . '"' . ($status_filter === 'OVERDUE' ? ' class="current"' : '') . '>En retard</a> | </li>';
        echo '<li><a href="' . esc_url($base_url . '&status=PAID') . '"' . ($status_filter === 'PAID' ? ' class="current"' : '') . '>Payees</a></li>';
        echo '</ul>';
        echo '<br class="clear">';

        if (empty($invoices)) {
            echo '<div class="notice notice-info"><p>Aucune facture. <a href="' . esc_url(admin_url('admin.php?page=comptaflow-invoices&action=new')) . '">Creer votre premiere facture</a></p></div>';
            return;
        }

        echo '<table class="wp-list-table widefat fixed striped">';
        echo '<thead><tr>';
        echo '<th style="width: 130px;">N° Facture</th>';
        echo '<th>Client</th>';
        echo '<th style="width: 100px;">Date</th>';
        echo '<th style="width: 100px;">Echeance</th>';
        echo '<th style="width: 110px; text-align: right;">Total TTC</th>';
        echo '<th style="width: 100px;">Statut</th>';
        echo '<th style="width: 200px;">Actions</th>';
        echo '</tr></thead>';
        echo '<tbody>';

        foreach ($invoices as $inv) {
            $view_url = admin_url('admin.php?page=comptaflow-invoices&action=view&id=' . absint($inv['id']));
            $edit_url = admin_url('admin.php?page=comptaflow-invoices&action=edit&id=' . absint($inv['id']));

            $status_badge = match($inv['status']) {
                'DRAFT' => '<span class="badge" style="background: #999;">Brouillon</span>',
                'PENDING' => '<span class="badge" style="background: #f08c00;">En attente</span>',
                'PAID' => '<span class="badge" style="background: #00875a;">Payee</span>',
                'OVERDUE' => '<span class="badge" style="background: #e03131;">En retard</span>',
                'CANCELLED' => '<span class="badge" style="background: #666;">Annulee</span>',
                default => '<span class="badge">' . esc_html($inv['status']) . '</span>'
            };

            echo '<tr>';
            echo '<td><strong><a href="' . esc_url($view_url) . '">' . esc_html($inv['invoice_number']) . '</a></strong></td>';
            echo '<td>' . esc_html($inv['client_name'] ?? '—') . '</td>';
            echo '<td>' . esc_html(date_i18n('d/m/Y', strtotime($inv['date_invoice']))) . '</td>';
            echo '<td>' . esc_html(date_i18n('d/m/Y', strtotime($inv['date_due']))) . '</td>';
            echo '<td style="text-align: right; font-weight: bold;">' . esc_html(number_format(floatval($inv['total_ttc']), 2, ',', ' ')) . ' €</td>';
            echo '<td>' . $status_badge . '</td>';
            echo '<td>';

            // Actions selon le statut
            $actions = [];
            $actions[] = '<a href="' . esc_url($view_url) . '">Voir</a>';

            if ($inv['status'] === 'DRAFT') {
                $actions[] = '<a href="' . esc_url($edit_url) . '">Modifier</a>';
                $validate_url = wp_nonce_url(admin_url('admin.php?page=comptaflow-invoices&do=validate&id=' . absint($inv['id'])), 'cfp_invoice_action_' . absint($inv['id']));
                $actions[] = '<a href="' . esc_url($validate_url) . '" style="color: #00875a;">Valider</a>';
            }

            if (in_array($inv['status'], ['PENDING', 'OVERDUE'])) {
                // PDF
                $actions[] = '<a href="' . esc_url(PDFGenerator::getDownloadUrl('invoice', $inv['id'])) . '">PDF</a>';
            }

            if ($inv['status'] === 'PAID') {
                $actions[] = '<a href="' . esc_url(PDFGenerator::getDownloadUrl('invoice', $inv['id'])) . '">PDF</a>';
            }

            echo implode(' | ', $actions);
            echo '</td>';
            echo '</tr>';
        }

        echo '</tbody></table>';
    }

    /**
     * Afficher le detail d'une facture
     */
    private static function renderView(): void {
        $id = isset($_GET['id']) ? absint($_GET['id']) : 0;
        $invoice = InvoiceService::getById($id, true);

        if (!$invoice) {
            echo '<div class="notice notice-error"><p>Facture introuvable.</p></div>';
            return;
        }

        $client = ClientService::getById($invoice['client_id']);
        $message = isset($_GET['message']) ? sanitize_text_field(wp_unslash($_GET['message'])) : '';

        if ($message === 'created') {
            echo '<div class="notice notice-success is-dismissible"><p>Facture creee avec succes.</p></div>';
        }

        echo '<h1>Facture ' . esc_html($invoice['invoice_number']);
        echo ' <a href="' . esc_url(admin_url('admin.php?page=comptaflow-invoices')) . '" class="page-title-action">Retour a la liste</a>';
        echo '</h1>';

        // Barre d'actions
        echo '<div style="background: #fff; padding: 15px; border: 1px solid #ddd; margin: 20px 0; border-radius: 4px; display: flex; gap: 8px; flex-wrap: wrap;">';

        $nonce_url = function($do) use ($invoice) {
            return wp_nonce_url(
                admin_url('admin.php?page=comptaflow-invoices&do=' . $do . '&id=' . absint($invoice['id'])),
                'cfp_invoice_action_' . absint($invoice['id'])
            );
        };

        if ($invoice['status'] === 'DRAFT') {
            echo '<a href="' . esc_url(admin_url('admin.php?page=comptaflow-invoices&action=edit&id=' . absint($invoice['id']))) . '" class="button">Modifier</a>';
            echo '<a href="' . esc_url($nonce_url('validate')) . '" class="button button-primary">Valider la facture</a>';
            echo '<a href="' . esc_url($nonce_url('delete')) . '" class="button" style="color: #d63638;" onclick="return confirm(\'Supprimer ce brouillon ?\');">Supprimer</a>';
        }

        if (in_array($invoice['status'], ['PENDING', 'OVERDUE'])) {
            echo '<a href="' . esc_url(PDFGenerator::getViewUrl('invoice', $invoice['id'])) . '" class="button" target="_blank">Voir PDF</a>';
            echo '<a href="' . esc_url(PDFGenerator::getDownloadUrl('invoice', $invoice['id'])) . '" class="button">Telecharger PDF</a>';

            if (empty($invoice['transaction_id'])) {
                echo '<a href="' . esc_url($nonce_url('register_accounting')) . '" class="button button-primary">Enregistrer en comptabilite</a>';
            }

            echo '<a href="' . esc_url($nonce_url('mark_paid') . '&method=VIREMENT') . '" class="button" style="color: #00875a;">Marquer payee (Virement)</a>';
            echo '<a href="' . esc_url($nonce_url('mark_paid') . '&method=CB') . '" class="button" style="color: #00875a;">Marquer payee (CB)</a>';
            echo '<a href="' . esc_url($nonce_url('mark_paid') . '&method=CHEQUE') . '" class="button" style="color: #00875a;">Marquer payee (Cheque)</a>';
        }

        if ($invoice['status'] === 'PAID') {
            echo '<a href="' . esc_url(PDFGenerator::getViewUrl('invoice', $invoice['id'])) . '" class="button" target="_blank">Voir PDF</a>';
            echo '<a href="' . esc_url(PDFGenerator::getDownloadUrl('invoice', $invoice['id'])) . '" class="button">Telecharger PDF</a>';

            if (!empty($invoice['transaction_id'])) {
                echo '<span style="padding: 4px 10px; background: #e3fcef; color: #00875a; border-radius: 3px; font-size: 12px;">Enregistree en comptabilite</span>';
            } else {
                echo '<a href="' . esc_url($nonce_url('register_accounting')) . '" class="button">Enregistrer en comptabilite</a>';
            }
        }

        echo '<a href="' . esc_url($nonce_url('duplicate')) . '" class="button">Dupliquer</a>';

        echo '</div>';

        // Infos facture
        echo '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">';

        // Colonne gauche : infos facture
        echo '<div class="cfp-postbox">';
        echo '<h3>Informations</h3>';
        echo '<table class="form-table">';
        echo '<tr><th>Numero</th><td><strong>' . esc_html($invoice['invoice_number']) . '</strong></td></tr>';
        echo '<tr><th>Date emission</th><td>' . esc_html(date_i18n('d/m/Y', strtotime($invoice['date_invoice']))) . '</td></tr>';
        echo '<tr><th>Date echeance</th><td>' . esc_html(date_i18n('d/m/Y', strtotime($invoice['date_due']))) . '</td></tr>';
        echo '<tr><th>Statut</th><td>';
        $status_label = match($invoice['status']) {
            'DRAFT' => 'Brouillon',
            'PENDING' => 'En attente de paiement',
            'PAID' => 'Payee',
            'OVERDUE' => 'En retard',
            'CANCELLED' => 'Annulee',
            default => $invoice['status']
        };
        echo esc_html($status_label);
        echo '</td></tr>';
        if ($invoice['payment_date']) {
            echo '<tr><th>Date paiement</th><td>' . esc_html(date_i18n('d/m/Y', strtotime($invoice['payment_date']))) . '</td></tr>';
        }
        if ($invoice['payment_method']) {
            echo '<tr><th>Moyen de paiement</th><td>' . esc_html($invoice['payment_method']) . '</td></tr>';
        }
        echo '</table>';
        echo '</div>';

        // Colonne droite : client
        echo '<div class="cfp-postbox">';
        echo '<h3>Client</h3>';
        if ($client) {
            echo '<p><strong>' . esc_html($client['name']) . '</strong></p>';
            if (!empty($client['address'])) echo '<p>' . esc_html($client['address']) . '</p>';
            if (!empty($client['postal_code']) || !empty($client['city'])) {
                echo '<p>' . esc_html(trim($client['postal_code'] . ' ' . $client['city'])) . '</p>';
            }
            if (!empty($client['email'])) echo '<p>' . esc_html($client['email']) . '</p>';
            if (!empty($client['siret'])) echo '<p>SIRET : ' . esc_html($client['siret']) . '</p>';
        }
        echo '</div>';

        echo '</div>';

        // Lignes de facture
        echo '<div class="cfp-postbox">';
        echo '<h3>Lignes de facture</h3>';
        echo '<table class="wp-list-table widefat fixed striped">';
        echo '<thead><tr>';
        echo '<th>Description</th>';
        echo '<th style="width: 80px;">Compte</th>';
        echo '<th style="width: 80px; text-align: right;">Quantite</th>';
        echo '<th style="width: 110px; text-align: right;">Prix unit. HT</th>';
        echo '<th style="width: 70px; text-align: right;">TVA %</th>';
        echo '<th style="width: 110px; text-align: right;">Total HT</th>';
        echo '</tr></thead>';
        echo '<tbody>';

        $lines = $invoice['lines'] ?? [];
        foreach ($lines as $line) {
            echo '<tr>';
            echo '<td>' . esc_html($line['description']) . '</td>';
            echo '<td>' . esc_html($line['account_code']) . '</td>';
            echo '<td style="text-align: right;">' . esc_html(number_format(floatval($line['quantity']), 2, ',', ' ')) . '</td>';
            echo '<td style="text-align: right;">' . esc_html(number_format(floatval($line['unit_price_ht']), 2, ',', ' ')) . ' €</td>';
            echo '<td style="text-align: right;">' . esc_html(number_format(floatval($line['vat_rate']), 1)) . '%</td>';
            echo '<td style="text-align: right; font-weight: bold;">' . esc_html(number_format(floatval($line['total_ht']), 2, ',', ' ')) . ' €</td>';
            echo '</tr>';
        }

        echo '</tbody></table>';

        // Totaux
        echo '<div style="display: flex; justify-content: flex-end; margin-top: 15px;">';
        echo '<table style="min-width: 250px;">';
        echo '<tr><td style="text-align: right; padding: 5px 15px;">Total HT</td><td style="text-align: right; font-weight: bold;">' . esc_html(number_format(floatval($invoice['total_ht']), 2, ',', ' ')) . ' €</td></tr>';
        echo '<tr><td style="text-align: right; padding: 5px 15px;">TVA</td><td style="text-align: right; font-weight: bold;">' . esc_html(number_format(floatval($invoice['total_tva']), 2, ',', ' ')) . ' €</td></tr>';
        echo '<tr style="background: #2d3436; color: #fff;"><td style="text-align: right; padding: 10px 15px; font-weight: bold;">NET A PAYER</td><td style="text-align: right; padding: 10px 15px; font-size: 16px; font-weight: bold;">' . esc_html(number_format(floatval($invoice['total_ttc']), 2, ',', ' ')) . ' €</td></tr>';
        echo '</table>';
        echo '</div>';

        if (!empty($invoice['notes'])) {
            echo '<div style="margin-top: 15px; padding: 10px; background: #f8f9fa; border-radius: 4px;">';
            echo '<strong>Notes :</strong> ' . esc_html($invoice['notes']);
            echo '</div>';
        }

        echo '</div>';
    }

    /**
     * Afficher le formulaire de creation/modification
     */
    private static function renderForm(): void {
        $invoice_id = isset($_GET['id']) ? absint($_GET['id']) : 0;
        $invoice = $invoice_id ? InvoiceService::getById($invoice_id, true) : null;
        $is_edit = !empty($invoice);

        $clients = ClientService::getForDropdown();

        if (empty($clients)) {
            echo '<div class="notice notice-warning"><p>Vous devez d\'abord <a href="' . esc_url(admin_url('admin.php?page=comptaflow-clients&action=new')) . '">creer un client</a> avant de pouvoir creer une facture.</p></div>';
            return;
        }

        echo '<h1>' . esc_html($is_edit ? 'Modifier la facture ' . $invoice['invoice_number'] : 'Nouvelle facture') . '</h1>';

        echo '<form method="post" action="' . esc_url(admin_url('admin.php?page=comptaflow-invoices')) . '" id="cfp-invoice-form">';
        wp_nonce_field('cfp_save_invoice');

        if ($is_edit) {
            echo '<input type="hidden" name="invoice_id" value="' . esc_attr($invoice_id) . '">';
        }

        // Infos generales
        echo '<div class="cfp-postbox">';
        echo '<h3>Informations generales</h3>';
        echo '<table class="form-table">';

        // Client
        echo '<tr><th><label for="client_id">Client *</label></th>';
        echo '<td><select name="client_id" id="client_id" required>';
        echo '<option value="">-- Choisir un client --</option>';
        foreach ($clients as $cid => $cname) {
            $selected = ($is_edit && intval($invoice['client_id']) === intval($cid)) ? ' selected' : '';
            echo '<option value="' . esc_attr($cid) . '"' . $selected . '>' . esc_html($cname) . '</option>';
        }
        echo '</select>';
        echo ' <a href="' . esc_url(admin_url('admin.php?page=comptaflow-clients&action=new')) . '" target="_blank">+ Nouveau client</a>';
        echo '</td></tr>';

        // Dates
        $default_date = $is_edit ? $invoice['date_invoice'] : gmdate('Y-m-d');
        $default_due = $is_edit ? $invoice['date_due'] : gmdate('Y-m-d', strtotime('+30 days'));

        echo '<tr><th><label for="date_invoice">Date d\'emission</label></th>';
        echo '<td><input type="date" name="date_invoice" id="date_invoice" value="' . esc_attr($default_date) . '" required></td></tr>';

        echo '<tr><th><label for="date_due">Date d\'echeance</label></th>';
        echo '<td><input type="date" name="date_due" id="date_due" value="' . esc_attr($default_due) . '" required></td></tr>';

        // Notes
        echo '<tr><th><label for="notes">Notes</label></th>';
        echo '<td><textarea name="notes" id="notes" rows="3" class="large-text">' . esc_textarea($invoice['notes'] ?? '') . '</textarea>';
        echo '<p class="description">Visible sur la facture PDF.</p></td></tr>';

        echo '</table>';
        echo '</div>';

        // Lignes de facture
        echo '<div class="cfp-postbox">';
        echo '<h3>Lignes de facture</h3>';
        echo '<table class="wp-list-table widefat" id="cfp-invoice-lines" style="table-layout: fixed;">';
        echo '<thead><tr>';
        echo '<th style="width: 30%;">Description *</th>';
        echo '<th style="width: 14%;">Compte</th>';
        echo '<th style="width: 11%; text-align: right;">Quantite</th>';
        echo '<th style="width: 14%; text-align: right;">Prix unit. HT</th>';
        echo '<th style="width: 11%; text-align: right;">TVA %</th>';
        echo '<th style="width: 14%; text-align: right;">Total HT</th>';
        echo '<th style="width: 6%;"></th>';
        echo '</tr></thead>';
        echo '<tbody id="cfp-lines-body">';

        $lines = ($is_edit && !empty($invoice['lines'])) ? $invoice['lines'] : [['description' => '', 'account_code' => '706', 'quantity' => 1, 'unit_price_ht' => 0, 'vat_rate' => 20]];

        foreach ($lines as $i => $line) {
            self::renderLineRow($i, $line);
        }

        echo '</tbody>';
        echo '<tfoot>';
        echo '<tr><td colspan="7"><button type="button" class="button" id="cfp-add-line">+ Ajouter une ligne</button></td></tr>';
        echo '<tr class="cfp-totals-row">';
        echo '<td colspan="4"></td>';
        echo '<td style="text-align: right; font-weight: bold;">Total HT :</td>';
        echo '<td style="text-align: right; font-weight: bold;" id="cfp-total-ht">0,00 €</td>';
        echo '<td></td>';
        echo '</tr>';
        echo '<tr class="cfp-totals-row">';
        echo '<td colspan="4"></td>';
        echo '<td style="text-align: right;">TVA :</td>';
        echo '<td style="text-align: right;" id="cfp-total-tva">0,00 €</td>';
        echo '<td></td>';
        echo '</tr>';
        echo '<tr class="cfp-totals-row" style="background: #2d3436;">';
        echo '<td colspan="4"></td>';
        echo '<td style="text-align: right; font-weight: bold; color: #fff; padding: 10px;">NET A PAYER :</td>';
        echo '<td style="text-align: right; font-weight: bold; color: #fff; font-size: 16px; padding: 10px;" id="cfp-total-ttc">0,00 €</td>';
        echo '<td style="background: #2d3436;"></td>';
        echo '</tr>';
        echo '</tfoot>';
        echo '</table>';
        echo '</div>';

        echo '<p class="submit">';
        echo '<input type="submit" class="button button-primary" value="' . esc_attr($is_edit ? 'Mettre a jour' : 'Creer la facture (brouillon)') . '">';
        echo ' <a href="' . esc_url(admin_url('admin.php?page=comptaflow-invoices')) . '" class="button">Annuler</a>';
        echo '</p>';

        echo '</form>';

        // Template de ligne cachee pour JS
        echo '<template id="cfp-line-template">';
        self::renderLineRow('__INDEX__', ['description' => '', 'account_code' => '706', 'quantity' => 1, 'unit_price_ht' => 0, 'vat_rate' => 20]);
        echo '</template>';
    }

    /**
     * Rendre une ligne de facture
     */
    private static function renderLineRow($index, array $line): void {
        $desc = esc_attr($line['description'] ?? '');
        $account = esc_attr($line['account_code'] ?? '706');
        $qty = esc_attr($line['quantity'] ?? 1);
        $price = esc_attr($line['unit_price_ht'] ?? 0);
        $vat = esc_attr($line['vat_rate'] ?? 20);

        $total_ht = floatval($line['quantity'] ?? 1) * floatval($line['unit_price_ht'] ?? 0);

        echo '<tr class="cfp-line-row">';
        echo '<td><input type="text" name="line_description[]" value="' . $desc . '" style="width: 100%; box-sizing: border-box;" placeholder="Description de la prestation"></td>';
        echo '<td><select name="line_account_code[]" class="cfp-account-select" style="width: 100%; box-sizing: border-box;">';
        $accounts = ['701' => '701', '706' => '706', '707' => '707', '7082' => '7082', '7516' => '7516'];
        foreach ($accounts as $code => $label) {
            $sel = ($account === $code) ? ' selected' : '';
            echo '<option value="' . esc_attr($code) . '"' . $sel . '>' . esc_html($label) . '</option>';
        }
        echo '</select></td>';
        echo '<td><input type="number" name="line_quantity[]" value="' . $qty . '" min="0.001" step="0.001" class="cfp-line-qty" style="width: 100%; box-sizing: border-box; text-align: right;"></td>';
        echo '<td><input type="number" name="line_unit_price_ht[]" value="' . $price . '" min="0" step="0.01" class="cfp-line-price" style="width: 100%; box-sizing: border-box; text-align: right;"></td>';
        echo '<td><select name="line_vat_rate[]" class="cfp-line-vat" style="width: 100%; box-sizing: border-box;">';
        $vat_rates = [0 => '0%', 2.1 => '2,1%', 5.5 => '5,5%', 10 => '10%', 20 => '20%'];
        foreach ($vat_rates as $rate => $label) {
            $sel = (floatval($vat) === floatval($rate)) ? ' selected' : '';
            echo '<option value="' . esc_attr($rate) . '"' . $sel . '>' . esc_html($label) . '</option>';
        }
        echo '</select></td>';
        echo '<td class="cfp-line-total" style="text-align: right; font-weight: bold; vertical-align: middle;">' . esc_html(number_format($total_ht, 2, ',', ' ')) . ' €</td>';
        echo '<td style="text-align: center;"><button type="button" class="button cfp-remove-line" title="Supprimer">&times;</button></td>';
        echo '</tr>';
    }
}
