<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

add_action( 'admin_init', 'elementsell_handle_bulk_delete_orders' );

/**
 * Popisek produktu v admin tabulce — včetně přijatého upsellu.
 *
 * @param object $order
 * @return string
 */
function elementsell_get_admin_order_product_label( $order ) {
    if ( ! $order ) {
        return '—';
    }

    $label = trim( (string) ( $order->product_name ?? '' ) );

    if (
        function_exists( 'elementsell_order_upsell_was_accepted' )
        && elementsell_order_upsell_was_accepted( (int) $order->id )
        && function_exists( 'elementsell_get_order_field' )
    ) {
        $upsell = trim( (string) elementsell_get_order_field( (int) $order->id, 'Upsell produkt' ) );

        if ( $upsell !== '' && strcasecmp( $upsell, $label ) !== 0 ) {
            $label = $label !== '' ? $label . ' + ' . $upsell : $upsell;
        }
    }

    return $label !== '' ? $label : '—';
}

/**
 * @param int $order_id
 * @return bool
 */
function elementsell_admin_delete_order( $order_id ) {
    $order_id = (int) $order_id;

    if ( $order_id <= 0 ) {
        return false;
    }

    if ( function_exists( 'elementsell_delete_order_by_id' ) ) {
        return (bool) elementsell_delete_order_by_id( $order_id );
    }

    global $wpdb;

    $wpdb->delete(
        $wpdb->prefix . 'elementsell_order_fields',
        [ 'order_id' => $order_id ],
        [ '%d' ]
    );

    $wpdb->delete(
        $wpdb->prefix . 'elementsell_invoices',
        [ 'order_id' => $order_id ],
        [ '%d' ]
    );

    $deleted = $wpdb->delete(
        $wpdb->prefix . 'elementsell_orders',
        [ 'id' => $order_id ],
        [ '%d' ]
    );

    return (bool) $deleted;
}

/**
 * Nezaplacené vždy; zaplacené jen demo ThePay (test).
 *
 * @param object $order
 * @return bool
 */
function elementsell_admin_order_can_be_deleted( $order ) {
    if ( ! $order ) {
        return false;
    }

    if ( (string) $order->payment_status !== 'paid' ) {
        return true;
    }

    return function_exists( 'elementsell_is_demo_order' ) && elementsell_is_demo_order( $order );
}

/**
 * @return void
 */
function elementsell_handle_bulk_delete_orders() {
    if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
        return;
    }

    if ( empty( $_POST['elementsell_bulk_delete_orders'] ) ) {
        return;
    }

    check_admin_referer( 'elementsell_bulk_delete_orders' );

    $order_ids = isset( $_POST['order_ids'] ) ? array_map( 'intval', (array) wp_unslash( $_POST['order_ids'] ) ) : [];
    $order_ids = array_values( array_filter( array_unique( $order_ids ) ) );

    foreach ( $order_ids as $order_id ) {
        elementsell_admin_delete_order( $order_id );
    }

    wp_safe_redirect( admin_url( 'admin.php?page=elementsell' ) );
    exit;
}

function elementsell_render_orders_page() {
    global $wpdb;

    echo '<div class="wrap elementsell-admin">';
    elementsell_render_admin_styles();

    if ( elementsell_is_billing_blocked() ) {
        echo '<h1>ElementSell</h1>';
        elementsell_render_billing_section();
        elementsell_render_invoice_footer_links();
        elementsell_render_cron_log_panel();
        elementsell_render_release_publish_trigger();
        echo '</div>';
        return;
    }

    $orders_table = $wpdb->prefix . 'elementsell_orders';

    $orders = $wpdb->get_results(
        "
        SELECT *
        FROM {$orders_table}
        ORDER BY id DESC
        LIMIT 100
        "
    );

    foreach ( (array) $orders as $order ) {
        if ( (string) $order->payment_status !== 'paid' ) {
            elementsell_sync_invoice_with_order( (int) $order->id );
        }
    }

    $invoices_by_order = elementsell_get_invoices_by_order_ids( wp_list_pluck( $orders, 'id' ) );
    $customer_fields_by_order = elementsell_get_customer_fields_for_orders( wp_list_pluck( $orders, 'id' ) );

    elementsell_render_admin_statistics();
    elementsell_render_order_reminder_notices();

    if ( function_exists( 'elementsell_render_onboarding_banner' ) ) {
        elementsell_render_onboarding_banner();
    }

    if ( empty( $orders ) ) {
        echo '<div class="elementsell-admin-card">';
        echo '<p class="elementsell-admin-empty">Zatím nejsou žádné objednávky.</p>';
        echo '</div>';
        elementsell_render_gmail_smtp_settings();
        elementsell_render_invoice_settings();
        elementsell_render_billing_section();
        elementsell_render_invoice_footer_links();
        elementsell_render_cron_log_panel();
        elementsell_render_release_publish_trigger();
        echo '</div>';
        return;
    }

    echo '<div class="elementsell-admin-card">';
    echo '<h2 class="elementsell-admin-section-title">Objednávky</h2>';

    echo '<form method="post" class="elementsell-bulk-form" id="elementsell-orders-bulk-form">';
    wp_nonce_field( 'elementsell_bulk_delete_orders' );

    echo '<div class="elementsell-table-scroll">';
    echo '<table class="widefat striped elementsell-orders-table elementsell-bulk-table">';
    echo '<thead>';
    echo '<tr>';
    echo '<th>Jméno</th>';
    echo '<th>Příjmení</th>';
    echo '<th>Email</th>';
    echo '<th>Telefon</th>';
    echo '<th class="elementsell-order-date-cell">Datum</th>';
    echo '<th class="elementsell-order-product-cell">Produkt</th>';
    echo '<th>Částka</th>';
    echo '<th class="elementsell-order-method-cell">Metoda</th>';
    echo '<th class="elementsell-order-paid-cell">Uhrazeno</th>';
    echo '<th class="elementsell-order-status-cell">Stav</th>';
    echo '<th class="elementsell-order-detail-cell">Detail</th>';
    echo '<th class="elementsell-bulk-checkbox-col" scope="col">';
    echo '<div class="elementsell-bulk-header-actions">';
    echo '<button type="submit" name="elementsell_bulk_delete_orders" value="1" class="elementsell-bulk-delete-btn" disabled>Smazat</button>';
    echo '<label class="elementsell-bulk-checkbox-label elementsell-bulk-checkbox-label--header" title="Vybrat vše">';
    echo '<input type="checkbox" id="elementsell-bulk-select-all" class="elementsell-bulk-checkbox-input">';
    echo '<span class="screen-reader-text">Vybrat vše</span>';
    echo '</label>';
    echo '</div>';
    echo '</th>';
    echo '</tr>';
    echo '</thead>';
    echo '<tbody>';

    foreach ( $orders as $order ) {
        $is_paid = ($order->payment_status === 'paid');
        $is_demo = function_exists( 'elementsell_is_demo_order' ) && elementsell_is_demo_order( $order );
        $can_delete = elementsell_admin_order_can_be_deleted( $order );
        $customer_fields = isset( $customer_fields_by_order[ (int) $order->id ] )
            ? $customer_fields_by_order[ (int) $order->id ]
            : [];
        $detail_id = 'elementsell-order-detail-' . (int) $order->id;

        echo '<tr class="elementsell-order-row">';
        echo '<td>' . esc_html($order->first_name) . '</td>';
        echo '<td>' . esc_html($order->surname) . '</td>';
        echo '<td>' . esc_html($order->email) . '</td>';
        echo '<td>' . esc_html($order->phone) . '</td>';
        echo '<td class="elementsell-order-date-cell">' . esc_html(mysql2date('j. n. Y, H:i', $order->created_at)) . '</td>';
        echo '<td class="elementsell-order-product-cell">' . esc_html( elementsell_get_admin_order_product_label( $order ) );
        if ( $is_demo ) {
            echo ' <span class="elementsell-demo-badge">DEMO</span>';
        }
        echo '</td>';
        echo '<td class="amount">' . esc_html(number_format((float) $order->amount, 2, ',', ' ')) . ' Kč</td>';
        echo '<td class="elementsell-order-method-cell">' . esc_html($order->payment_method ?: '—') . '</td>';

        if ( $is_paid ) {
            echo '<td class="elementsell-order-paid-cell"><span class="status-paid">✅</span></td>';
        } else {
            echo '<td class="elementsell-order-paid-cell"><span class="status-not-paid">✖</span></td>';
        }

        echo '<td class="elementsell-order-status-cell"><span class="status-text">' . esc_html($order->payment_status) . '</span></td>';

        echo '<td class="elementsell-order-detail-cell">';
        echo '<button type="button" class="button button-small elementsell-order-detail-toggle" aria-expanded="false" aria-controls="' . esc_attr( $detail_id ) . '" data-target="' . esc_attr( $detail_id ) . '">Zobrazit</button>';
        echo '</td>';

        echo '<td class="elementsell-bulk-checkbox-col">';

        if ( $can_delete ) {
            $delete_title = $is_paid && $is_demo
                ? 'Smazat demo objednávku #' . (string) (int) $order->id
                : 'Vybrat objednávku #' . (string) (int) $order->id;
            echo '<label class="elementsell-bulk-checkbox-label" title="' . esc_attr( $delete_title ) . '">';
            echo '<input type="checkbox" class="elementsell-bulk-checkbox-input elementsell-bulk-order-checkbox" name="order_ids[]" value="' . esc_attr( (string) (int) $order->id ) . '">';
            echo '<span class="screen-reader-text">' . esc_html( $delete_title ) . '</span>';
            echo '</label>';
        } else {
            echo '<span class="elementsell-bulk-checkbox-placeholder" title="Zaplacené ostré objednávky nelze smazat" aria-hidden="true"></span>';
        }

        echo '</td>';

        echo '</tr>';

        echo '<tr id="' . esc_attr( $detail_id ) . '" class="elementsell-order-detail-row" hidden>';
        echo '<td colspan="12">';
        echo '<div class="elementsell-order-detail-panel">';
        echo '<dl class="elementsell-order-detail-list">';

        echo '<div class="elementsell-order-detail-item">';
        echo '<dt>Faktura</dt>';
        echo '<dd>';
        if ( isset( $invoices_by_order[ $order->id ] ) ) {
            $invoice = $invoices_by_order[ $order->id ];
            $invoice_label = esc_html( $invoice->invoice_number );
            if ( (string) $invoice->type === 'demo' ) {
                $invoice_label .= ' <span class="elementsell-demo-badge">DEMO</span>';
            }
            echo '<a href="' . esc_url( elementsell_get_invoice_admin_url( $invoice->id ) ) . '">' . $invoice_label . '</a>';
        } else {
            echo '—';
        }
        echo '</dd>';
        echo '</div>';

        if ( $is_paid ) {
            $paid_email_sent_at = (string) elementsell_get_order_field( (int) $order->id, 'paid_email_sent_at' );
            $paid_email_error   = (string) elementsell_get_order_field( (int) $order->id, 'paid_email_error' );

            echo '<div class="elementsell-order-detail-item">';
            echo '<dt>E-mail po platbě</dt>';
            echo '<dd>';

            if ( $paid_email_sent_at !== '' ) {
                echo 'Odeslán ' . esc_html( mysql2date( 'j. n. Y, H:i', $paid_email_sent_at ) );
            } elseif ( $paid_email_error !== '' ) {
                echo '<span style="color:#b32d2e;">Selhal: ' . esc_html( $paid_email_error ) . '</span>';
            } else {
                echo '<span style="color:#b32d2e;">Neodeslán (zkontrolujte log e-mailů)</span>';
            }

            echo '</dd>';
            echo '</div>';
        }

        foreach ( $customer_fields as $field ) {
            echo '<div class="elementsell-order-detail-item">';
            echo '<dt>' . esc_html( $field['label'] ) . '</dt>';
            echo '<dd>' . esc_html( $field['value'] ) . '</dd>';
            echo '</div>';
        }

        echo '</dl>';

        echo '</div>';
        echo '</td>';
        echo '</tr>';
    }

    echo '</tbody>';
    echo '</table>';
    echo '</div>';
    echo '</form>';
    echo '<script>
    (function() {
        var form = document.getElementById("elementsell-orders-bulk-form");
        if (!form) return;

        var selectAll = form.querySelector("#elementsell-bulk-select-all");
        var checkboxes = form.querySelectorAll(".elementsell-bulk-order-checkbox");
        var deleteBtn = form.querySelector(".elementsell-bulk-delete-btn");

        function updateBulkState() {
            var checked = form.querySelectorAll(".elementsell-bulk-order-checkbox:checked");
            var count = checked.length;

            if (deleteBtn) {
                deleteBtn.disabled = count === 0;
            }

            if (selectAll) {
                selectAll.indeterminate = count > 0 && count < checkboxes.length;
                selectAll.checked = checkboxes.length > 0 && count === checkboxes.length;
            }
        }

        if (selectAll) {
            selectAll.addEventListener("change", function() {
                checkboxes.forEach(function(checkbox) {
                    checkbox.checked = selectAll.checked;
                });
                updateBulkState();
            });
        }

        checkboxes.forEach(function(checkbox) {
            checkbox.addEventListener("change", updateBulkState);
        });

        form.addEventListener("submit", function(event) {
            if (!event.submitter || event.submitter.name !== "elementsell_bulk_delete_orders") {
                return;
            }

            if (!confirm("Opravdu smazat vybrané objednávky?")) {
                event.preventDefault();
            }
        });

        updateBulkState();
    })();

    document.addEventListener("click", function(event) {
        var button = event.target.closest(".elementsell-order-detail-toggle");
        if (!button) return;
        var targetId = button.getAttribute("data-target");
        var row = targetId ? document.getElementById(targetId) : null;
        if (!row) return;
        var isOpen = !row.hasAttribute("hidden");
        if (isOpen) {
            row.setAttribute("hidden", "hidden");
            button.setAttribute("aria-expanded", "false");
            button.textContent = "Zobrazit";
        } else {
            row.removeAttribute("hidden");
            button.setAttribute("aria-expanded", "true");
            button.textContent = "Skrýt";
        }
    });
    </script>';
    echo '</div>';

    elementsell_render_email_log();
    elementsell_render_gmail_smtp_settings();
    elementsell_render_invoice_settings();
    elementsell_render_billing_section();
    elementsell_render_invoice_footer_links();
    elementsell_render_cron_log_panel();
    elementsell_render_release_publish_trigger();
    echo '</div>';
}
