<?php
declare(strict_types=1);

if (!defined('ABSPATH')) { exit; }

/**
 * Mini-Cart element renderer (shared).
 *
 * Phase 1, step 35. Sister renderer to cart.php. The frontend dispatches
 * the same `[instinctor_cart]` shortcode with `cart_mode = 'mini'` — the
 * full cart controller handles the variant rendering. The editor has its
 * own ~100-line static preview with a distinct compact mini-cart layout
 * (sidebar/popover-friendly, 320px wide by default, image+name+qty+price
 * stacked rather than the cart's full-width table).
 *
 * Branches on `$context`:
 *   - frontend: shortcode dispatch with cart_mode='mini'
 *   - editor:   inline static preview
 *
 * One frontend-specific behaviour preserved: `hide_when_empty` makes the
 * block disappear when the cart has zero items. In editor preview we
 * always render a placeholder row so designers can see the block's styling
 * even on an empty session.
 */
function impulse_element_render_mini_cart($el, array $settings, string $context): string {
    if (is_object($el)) $el = (array) $el;
    $isEditor = ($context === 'editor');

    if (!$isEditor) {
        // Frontend: same shortcode as cart, with mode flag set to 'mini'.
        ob_start();
        $settings['cart_mode'] = 'mini';
        $GLOBALS['instinctor_cart_settings'] = $settings;
        if (function_exists('do_shortcode')) {
            echo do_shortcode('[instinctor_cart]');
        }
        unset($GLOBALS['instinctor_cart_settings']);
        return (string) ob_get_clean();
    }

    // ── Editor preview ───────────────────────────────────────────────────
    $title       = (string) ($settings['title']       ?? 'Your Cart');
    $emptyText   = (string) ($settings['empty_text']  ?? 'Your cart is empty');
    $buttonText  = (string) ($settings['button_text'] ?? 'Checkout');
    $bgColor     = (string) ($settings['bg_color']    ?? '#ffffff');
    $textColor   = (string) ($settings['text_color']  ?? '#1d2327');
    $width        = function_exists('impulse_get_responsive') ? intval(impulse_get_responsive($settings, 'width', 320))         : 320;
    $borderRadius = function_exists('impulse_get_responsive') ? intval(impulse_get_responsive($settings, 'border_radius', 8))   : 8;
    $align        = function_exists('impulse_get_responsive') ? (string) impulse_get_responsive($settings, 'align', 'center') : 'center';
    $buttonSize   = function_exists('impulse_get_responsive') ? intval(impulse_get_responsive($settings, 'button_size', 14))    : 14;
    $showSubtotal = ($settings['show_subtotal'] ?? true) !== false;
    $showRemove   = ($settings['show_remove']   ?? true) !== false;
    $hideWhenEmpty = ($settings['hide_when_empty'] ?? true) !== false;
    $buttonBg    = (string) ($settings['button_bg']    ?? '#1d2327');
    $buttonColor = (string) ($settings['button_color'] ?? '#ffffff');
    $imageSize   = intval($settings['image_size'] ?? 60);

    $justifyMap = ['left' => 'flex-start', 'center' => 'center', 'right' => 'flex-end'];
    $wrapStyle  = 'display:flex;justify-content:' . ($justifyMap[$align] ?? 'center') . ';';

    // Real cart contents (editor previews the designer's actual session
    // when there's data — otherwise shows a placeholder row).
    $miniCartItems = [];
    $miniCartTotal = 0.0;
    if (class_exists('\\Instinctor\\Core\\CartSession')) {
        $cart = \Instinctor\Core\CartSession::get('cart') ?? ['items' => []];
        if (!empty($cart['items'])) {
            $useInstinctor = class_exists('\\Instinctor\\Core\\DB');
            global $wpdb;
            $pt = $useInstinctor
                ? \Instinctor\Core\DB::prefix() . 'instinctor_products'
                : (isset($wpdb) ? $wpdb->prefix . 'instinctor_products' : '');
            if ($pt !== '') {
                foreach ($cart['items'] as $item) {
                    $productId = intval($item['product_id'] ?? 0);
                    $qty       = intval($item['quantity']   ?? 1);
                    if ($productId <= 0) continue;
                    if ($useInstinctor) {
                        $product = \Instinctor\Core\DB::get_row(\Instinctor\Core\DB::prepare("SELECT * FROM {$pt} WHERE id = %d", $productId));
                    } else {
                        $product = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$pt} WHERE id = %d", $productId)); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery -- $pt from DB::prefix(); plugin's own custom table; per-request render value
                    }
                    if ($product) {
                        $price = floatval($product->sale_price > 0 && $product->sale_price < $product->price ? $product->sale_price : $product->price);
                        $miniCartItems[] = [
                            'id'       => $productId,
                            'name'     => (string) $product->name,
                            'price'    => $price,
                            'quantity' => $qty,
                            'image'    => function_exists('impulse_get_product_images') ? (impulse_get_product_images($product)[0] ?? '') : '',
                        ];
                        $miniCartTotal += $price * $qty;
                    }
                }
            }
        }
    }

    // Editor honours `hide_when_empty` only when also in true edit mode
    // (impulseIsEditMode). Otherwise it always shows a placeholder so
    // designers can style the block without a populated cart.
    $isEditMode = !empty($GLOBALS['impulse_is_edit_mode']);
    if (empty($miniCartItems) && $hideWhenEmpty && !$isEditMode) {
        return '';
    }

    ob_start();
    echo '<div class="impulse-mini-cart-wrap" style="' . esc_attr($wrapStyle) . '">';
    echo '<div class="impulse-mini-cart" style="width:' . (int) $width . 'px;background:' . esc_attr($bgColor) . ';color:' . esc_attr($textColor) . ';border-radius:' . (int) $borderRadius . 'px;box-shadow:0 4px 20px rgba(0,0,0,0.15);padding:20px">';
    echo '<div style="font-weight:600;font-size:16px;margin-bottom:16px;padding-bottom:12px;border-bottom:1px solid #eee">' . esc_html($title) . '</div>';

    if (empty($miniCartItems)) {
        // Placeholder row — same layout as a real item, so the styling
        // result is honest in the editor canvas.
        echo '<div style="display:flex;gap:12px;padding:12px 0;border-bottom:1px solid #eee">';
        echo '<div style="width:' . (int) $imageSize . 'px;height:' . (int) $imageSize . 'px;background:#f5f5f5;border-radius:4px;flex-shrink:0"></div>';
        echo '<div style="flex:1;min-width:0;display:flex;flex-direction:column;justify-content:space-between;height:' . (int) $imageSize . 'px">';
        echo '<div style="font-weight:500;font-size:14px">Product Name</div>';
        echo '<div style="font-size:12px;color:#666">Qty: 1</div>';
        echo '<div style="font-size:14px;font-weight:600">$29.99</div>';
        echo '</div>';
        if ($showRemove) echo '<span class="impulse-mini-cart-remove" style="color:#999;cursor:pointer;padding:4px;font-size:18px;line-height:1;align-self:flex-start">&times;</span>';
        echo '</div>';
        $displayTotal = '$29.99';
    } else {
        foreach ($miniCartItems as $item) {
            echo '<div style="display:flex;gap:12px;padding:12px 0;border-bottom:1px solid #eee">';
            if (!empty($item['image'])) {
                echo '<img src="' . esc_url((string) $item['image']) . '" style="width:' . (int) $imageSize . 'px;height:' . (int) $imageSize . 'px;object-fit:cover;border-radius:4px;flex-shrink:0">';
            } else {
                echo '<div style="width:' . (int) $imageSize . 'px;height:' . (int) $imageSize . 'px;background:#f5f5f5;border-radius:4px;flex-shrink:0"></div>';
            }
            echo '<div style="flex:1;min-width:0;display:flex;flex-direction:column;justify-content:space-between;height:' . (int) $imageSize . 'px">';
            echo '<div style="font-weight:500;font-size:14px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">' . esc_html((string) ($item['name'] ?? '')) . '</div>';
            echo '<div style="font-size:12px;color:#666">Qty: ' . intval($item['quantity']) . '</div>';
            echo '<div style="font-size:14px;font-weight:600">$' . number_format((float) $item['price'], 2) . '</div>';
            echo '</div>';
            if ($showRemove) echo '<span class="impulse-mini-cart-remove" data-product-id="' . intval($item['id']) . '" style="color:#999;cursor:pointer;padding:4px;font-size:18px;line-height:1;align-self:flex-start">&times;</span>';
            echo '</div>';
        }
        $displayTotal = '$' . number_format($miniCartTotal, 2);
    }

    if ($showSubtotal) {
        echo '<div style="display:flex;justify-content:space-between;padding:16px 0;font-weight:600">';
        echo '<span>Subtotal</span><span>' . esc_html($displayTotal) . '</span>';
        echo '</div>';
    }
    echo '<button class="impulse-mini-cart-btn" style="width:100%;padding:12px;background:' . esc_attr($buttonBg) . ';color:' . esc_attr($buttonColor) . ';border:none;border-radius:6px;font-weight:600;font-size:' . (int) $buttonSize . 'px;cursor:pointer">' . esc_html($buttonText) . '</button>';
    echo '</div>';
    echo '</div>';

    return (string) ob_get_clean();
}
