<?php
namespace Ticketack\WP\Shortcodes;

use Ticketack\WP\Templates\TKTTemplate;
use Ticketack\WP\TKTApp;

/**
 * Cart shortcode
 *
 * Usage:
 *
 * [tkt_cart hidden_links="finalize,cancel,continue" hide_wallet="true"]
 *
 * Default layout is "screenings"
 */
class CartShortcode extends TKTShortcode
{
    /**
     * Get this Shortcode tag
     *
     * @return string: The tag to use to run this shortcode
     */
    public function get_tag()
    {
        return "tkt_cart";
    }

    /**
     * Get this Shortcode tag
     *
     * @param array $atts: Shortcode attributes
     * @param string $content: Shortcode content
     */
    public function run($atts, $content)
    {
        $enable_promo_code = TKTApp::get_instance()->get_config('eshop.enable_promo_code');
        $hidden_links      = $this->build_hidden_links($atts);
        $theme             = array_key_exists('theme', (array)$atts) ? $atts['theme'] : 'light';
        $hide_items        = array_key_exists('hide_items', (array)$atts);
        $hide_summary      = array_key_exists('hide_summary', (array)$atts);
        $cart_id           = tkt_get_url_param('cart_id');

        return TKTTemplate::render(
            'cart/cart',
            (object)[
                'hidden_links'      => $hidden_links,
                'enable_promo_code' => $enable_promo_code,
                'theme'             => $theme,
                'hide_items'        => $hide_items,
                'hide_summary'      => $hide_summary,
                'cart_id'           => $cart_id
            ]
        );
    }

    /**
     * Build hide_links list from shortcode attributes
     *
     * @param array $atts
     * @return string
     */
    protected function build_hidden_links($atts)
    {
        $hidden_links = array_key_exists('hide_links', (array)$atts) ? $atts['hide_links'] : '';
        if (filter_var($atts['hide_wallet'] ?? false, FILTER_VALIDATE_BOOLEAN)) {
            $parts = array_filter(array_map('trim', explode(',', $hidden_links)));
            if (!in_array('wallet', $parts, true)) {
                $parts[] = 'wallet';
            }
            $hidden_links = implode(',', $parts);
        }

        return $hidden_links;
    }
}
