<?php
declare(strict_types=1);

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

/**
 * Cart element renderer (shared).
 *
 * Phase 1, step 34. Frontend was a tiny shortcode dispatch:
 *
 *     $GLOBALS['instinctor_cart_settings'] = $settings;
 *     echo do_shortcode('[instinctor_cart]');
 *     unset($GLOBALS['instinctor_cart_settings']);
 *
 * (The real cart UI lives inside the `[instinctor_cart]` shortcode handler
 * — see CartController. Both the storefront and the mini-cart variant pipe
 * through the same shortcode with a `cart_mode` flag.)
 *
 * Editor used ~135 lines of inline preview rendering: a static cart with
 * placeholder items styled exactly like the live cart, but inert. Used the
 * builder canvas to show designers the cart styling result without
 * triggering the shortcode's REST hits.
 *
 * Unified here: same shared function, branches on `$context`. Frontend
 * keeps the shortcode dispatch (no change in production output). Editor
 * keeps the inline preview verbatim (no change in builder canvas).
 *
 * The mini-cart variant lives in mini_cart.php and reuses the same
 * shortcode on the frontend; the editor preview for mini-cart is its
 * own distinct layout, so it has its own file rather than a branch here.
 */
function impulse_element_render_cart($el, array $settings, string $context): string {
    if (is_object($el)) $el = (array) $el;
    $isEditor = ($context === 'editor');

    if (!$isEditor) {
        // Frontend: dispatch via shortcode. The cart_mode key drives full
        // vs mini rendering inside CartController. Settings flow through
        // a temporary global because shortcodes can't take object args.
        ob_start();
        $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 (static, inert) ───────────────────────────────────
    $device     = (string) ($GLOBALS['impulse_preview_device'] ?? 'desktop');
    $title      = (string) ($settings['title']      ?? 'Your Order');
    $emptyText  = (string) ($settings['empty_text'] ?? 'Your cart is empty');

    // Per-device checkbox reader. Mobile defaults to UNCHECKED for each
    // visibility toggle (cleaner cart on phones). Tablet inherits desktop
    // unless a tablet override exists. Same convention used by impulse-preview
    // before extraction.
    $cartChk = static function (string $key) use ($settings, $device): bool {
        if ($device === 'mobile') {
            if (isset($settings[$key . '_mobile'])) return (bool) $settings[$key . '_mobile'];
            return false;
        }
        if ($device === 'tablet' && isset($settings[$key . '_tablet'])) {
            return (bool) $settings[$key . '_tablet'];
        }
        return ($settings[$key] ?? true) !== false;
    };
    $showImage    = $cartChk('show_image');
    $showQuantity = $cartChk('show_quantity');
    $showSubtotal = $cartChk('show_subtotal');
    $showHeader   = $cartChk('show_header');
    $showTable    = $cartChk('show_table');
    $bgColor      = (string) ($settings['bg_color'] ?? '#ffffff');

    // Auto-contrast — derive every text/border color from the bg so a black
    // cart on a white page reads right with the same setting that gave a
    // white cart on a black page.
    $autoText         = function_exists('impulse_contrast_color') ? impulse_contrast_color($bgColor) : '#111827';
    $isLight          = ($autoText === '#111827');
    $autoTextSub      = $isLight ? 'rgba(0,0,0,0.45)' : 'rgba(255,255,255,0.45)';
    $autoTextMid      = $isLight ? 'rgba(0,0,0,0.6)'  : 'rgba(255,255,255,0.6)';
    $autoBorderStrong = $isLight ? 'rgba(0,0,0,0.15)' : 'rgba(255,255,255,0.15)';
    $autoPlaceholder  = $isLight ? 'rgba(0,0,0,0.1)'  : 'rgba(255,255,255,0.1)';

    $borderRadius = function_exists('impulse_get_responsive')
        ? intval(impulse_get_responsive($settings, 'border_radius', 4))
        : 4;
    // Never full-width on desktop: default 50% (centered via margin:auto below).
    // Mobile defaults to 100% and is INDEPENDENT of the desktop value — an
    // explicit max_width_mobile overrides, otherwise 100% (never inherited from
    // the desktop base) so a 50% desktop never shrinks the phone cart. Tablet
    // follows the desktop base unless it has its own override.
    if ($device === 'mobile') {
        $maxWidth = (isset($settings['max_width_mobile']) && $settings['max_width_mobile'] !== '')
            ? intval($settings['max_width_mobile']) : 100;
    } else {
        $maxWidth = (isset($settings['max_width']) && $settings['max_width'] !== '')
            ? intval($settings['max_width']) : 50;
        if ($device === 'tablet' && isset($settings['max_width_tablet']) && $settings['max_width_tablet'] !== '') {
            $maxWidth = intval($settings['max_width_tablet']);
        }
    }
    if ($maxWidth < 1 || $maxWidth > 100) $maxWidth = ($device === 'mobile') ? 100 : 50; // guard legacy px / empties

    $containerStyle = 'background:' . esc_attr($bgColor) . ';'
                    . 'border-radius:' . $borderRadius . 'px;'
                    . 'padding:20px;'
                    . 'width:' . $maxWidth . '%;margin:0 auto;'
                    . 'color:' . esc_attr($autoText) . ';'
                    . 'box-sizing:border-box;overflow:hidden;';

    // Real cart data lookup (the builder canvas can show what's actually in
    // the designer's session, which is occasionally useful).
    $cartItems = [];
    if (class_exists('\\Instinctor\\Core\\CartSession')) {
        $cart = \Instinctor\Core\CartSession::get('cart') ?? ['items' => []];
        if (!empty($cart['items'])) {
            global $wpdb;
            $useInstinctor = class_exists('\\Instinctor\\Core\\DB');
            $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);
                    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);
                        $cartItems[] = [
                            'name'     => (string) $product->name,
                            'price'    => $price,
                            'quantity' => intval($item['quantity'] ?? 1),
                            'image'    => function_exists('impulse_get_product_images') ? (impulse_get_product_images($product)[0] ?? '') : '',
                            'subtotal' => $price * intval($item['quantity'] ?? 1),
                        ];
                    }
                }
            }
        }
    }

    // Placeholder so the builder canvas shows realistic row styling on a
    // blank/empty cart.
    if (empty($cartItems)) {
        $cartItems = [
            ['name' => 'Product Name', 'price' => 29.99, 'quantity' => 1, 'image' => '', 'subtotal' => 29.99],
        ];
    }

    ob_start();
    echo '<div class="impulse-cart-block" style="' . esc_attr($containerStyle) . '">';

    if ($showHeader) {
        echo '<h2 class="impulse-cart-title" style="margin:0 0 24px;font-size:24px;color:' . esc_attr($autoText) . '">' . esc_html($title) . '</h2>';
    }

    if ($showTable) {
        echo '<div class="impulse-cart-table-header" style="display:grid;grid-template-columns:' . ($showImage ? '80px ' : '') . '1fr' . ($showQuantity ? ' 100px' : '') . ($showSubtotal ? ' 80px' : '') . ';gap:16px;padding-bottom:12px;border-bottom:2px solid ' . esc_attr($autoBorderStrong) . ';font-weight:600;font-size:14px;color:' . esc_attr($autoTextMid) . '">';
        if ($showImage) echo '<span></span>';
        echo '<span>Product</span>';
        if ($showQuantity) echo '<span style="text-align:center">Quantity</span>';
        if ($showSubtotal) echo '<span style="text-align:right">Subtotal</span>';
        echo '</div>';
    }

    foreach ($cartItems as $item) {
        echo '<div class="impulse-cart-item" style="display:grid;grid-template-columns:' . ($showImage ? '80px ' : '') . '1fr' . ($showQuantity ? ' 100px' : '') . ($showSubtotal ? ' 80px' : '') . ';gap:16px;padding:16px 0;align-items:center">';
        if ($showImage) {
            if (!empty($item['image'])) {
                echo '<div style="width:80px;height:80px;border-radius:4px;overflow:hidden"><img src="' . esc_url((string) $item['image']) . '" style="width:100%;height:100%;object-fit:cover"></div>';
            } else {
                echo '<div style="width:80px;height:80px;background:' . esc_attr($autoPlaceholder) . ';border-radius:4px"></div>';
            }
        }
        echo '<div><div style="font-weight:500;color:' . esc_attr($autoText) . '">' . esc_html((string) ($item['name'] ?? '')) . '</div><div style="font-size:14px;color:' . esc_attr($autoTextSub) . ';margin-top:4px">$' . number_format((float) $item['price'], 2) . '</div></div>';
        if ($showQuantity) {
            echo '<div style="display:flex;justify-content:center;align-items:center;gap:2px;color:' . esc_attr($autoText) . '"><span style="font-size:24px;padding:2px 6px;line-height:1;opacity:0.35;user-select:none">&#9666;</span><span style="min-width:30px;max-width:40px;text-align:center;font-size:15px;font-weight:500">' . intval($item['quantity']) . '</span><span style="font-size:24px;padding:2px 6px;line-height:1;opacity:0.35;user-select:none">&#9656;</span></div>';
        }
        if ($showSubtotal) {
            echo '<div style="text-align:right;font-weight:600;color:' . esc_attr($autoText) . '">$' . number_format((float) $item['subtotal'], 2) . '</div>';
        }
        echo '</div>';
    }

    // Footer
    $cartTotal       = array_sum(array_column($cartItems, 'subtotal'));
    $chkBtnText      = (string) ($settings['checkout_btn_text'] ?? 'Checkout');
    $chkBtnBg        = (string) ($settings['checkout_btn_bg']   ?? '#1d2327');
    $chkBtnAutoColor = function_exists('impulse_contrast_color') ? impulse_contrast_color($chkBtnBg) : '#ffffff';
    echo '<div style="display:flex;justify-content:space-between;align-items:center;padding:16px 0 0;border-top:2px solid ' . esc_attr($autoBorderStrong) . ';margin-top:4px">';
    echo '<a href="#" style="display:inline-flex;align-items:center;justify-content:center;height:40px;padding:0 20px;background:' . esc_attr($chkBtnBg) . ';color:' . esc_attr($chkBtnAutoColor) . ';border-radius:' . (int) $borderRadius . 'px;font-size:14px;font-weight:600;text-decoration:none;cursor:default" onclick="event.preventDefault()">' . esc_html($chkBtnText) . '</a>';
    echo '<div style="text-align:right"><span style="font-size:13px;color:' . esc_attr($autoTextMid) . ';margin-right:8px">Total</span><span style="font-size:16px;font-weight:600;color:' . esc_attr($autoText) . '">$' . number_format($cartTotal, 2) . '</span></div>';
    echo '</div>';
    echo '</div>';

    return (string) ob_get_clean();
}
