<?php

namespace CodeConfig\EAW\App;

use CodeConfig\EAW\Utils\Helpers;
use CodeConfig\EAW\Utils\Singleton;
defined( 'ABSPATH' ) || exit( 'No direct script access allowed' );
class SaveCart {
    use Singleton;
    public function doHooks() {
        if ( !Helpers::getSetting( 'enableSaveCart' ) ) {
            return;
        }
        add_action( 'init', [$this, 'registerSavedCartEndpoint'] );
        add_filter( 'woocommerce_account_menu_items', [$this, 'addSavedCartMenu'] );
        add_action( 'woocommerce_account_saved-cart_endpoint', [$this, 'displaySavedCartContent'] );
        add_action( 'wp_enqueue_scripts', [$this, 'enqueueScripts'] );
        add_action( 'woocommerce_before_cart_table', [$this, 'renderSaveCartBtn'] );
        add_action( 'woocommerce_after_cart_table', [$this, 'renderSaveCartBtn'] );
        add_action( 'woocommerce_after_cart_table', [$this, 'renderShareLink'] );
        add_action( 'template_redirect', [$this, 'restoreSharedCart'] );
    }

    public function enqueueScripts() {
        if ( $this->isSaveCartEnabled() ) {
            wp_enqueue_script( 'ccpeaw-saved-shared' );
        }
    }

    public function registerSavedCartEndpoint() {
        if ( $this->isSaveCartEnabled() ) {
            add_rewrite_endpoint( 'saved-cart', EP_ROOT | EP_PAGES );
        }
    }

    public function addSavedCartMenu( $items ) {
        $title = ( Helpers::getSetting( 'saveCartPageTitle' ) ?: __( 'Saved Cart', 'essential-addons-for-woocommerce' ) );
        $new = [];
        foreach ( $items as $key => $label ) {
            if ( 'customer-logout' === $key ) {
                $new['saved-cart'] = esc_html( $title );
            }
            $new[$key] = $label;
        }
        return $new;
    }

    private function isSaveCartEnabled() {
        return Helpers::getSetting( 'enableSaveCart' ) && (is_user_logged_in() || Helpers::getSetting( 'enableSharingForLoggedOutUsers' ));
    }

    private function getSaveBtnPosition() {
        return ( Helpers::getSetting( 'saveCartButtonPosition' ) ?: 'afterCartTable' );
    }

    public function renderSaveCartBtn() {
        if ( !is_cart() ) {
            return;
        }
        $position = $this->getSaveBtnPosition();
        $hook = current_filter();
        $map = [
            'beforeCartTable'   => 'woocommerce_before_cart_table',
            'afterCartTable'    => 'woocommerce_after_cart_table',
            'afterCouponButton' => 'woocommerce_cart_coupon',
            'afterUpdateButton' => 'woocommerce_cart_actions',
        ];
        if ( !isset( $map[$position] ) || $map[$position] !== $hook ) {
            return;
        }
        $text = ( Helpers::getSetting( 'saveBtnTxt' ) ?: __( 'Save Cart to Account', 'essential-addons-for-woocommerce' ) );
        echo '<div class="eaw-save-wrapper ' . esc_attr( strtolower( $position ) ) . '">
            <button id="eaw-save-button">' . esc_html( $text ) . '</button>
        </div>';
    }

    public function renderShareLink() {
        if ( !is_cart() || !$this->isSaveCartEnabled() ) {
            return;
        }
        echo '<div class="eaw-share-wrapper">
            <span class="eaw-share-label">' . esc_html( ( Helpers::getSetting( 'shareSocialTitle' ) ?: __( 'Share Cart', 'essential-addons-for-woocommerce' ) ) ) . '</span>
            <div class="eaw-share-list" id="eaw-share-buttons">';
        foreach ( [
            'facebook',
            'x',
            'linkedin',
            'whatsapp',
            'email'
        ] as $network ) {
            if ( Helpers::getSetting( 'shareOn' . ucfirst( $network ) ) ) {
                printf( '<i data-network="%s" class="eaw-icon-%s"></i>', esc_attr( $network ), esc_attr( $network ) );
            }
        }
        if ( Helpers::getSetting( 'copyCartToClipboard' ) ) {
            printf( '<i id="eaw-copy-button" class="eaw-icon-link-copy" data-savecartid="%s" title="%s"></i>', esc_attr( WC()->cart->get_cart_hash() ), esc_attr__( 'Copy Cart Link', 'essential-addons-for-woocommerce' ) );
        }
        echo '</div></div>';
    }

    public function restoreSharedCart() {
        $shared = sanitize_text_field( get_query_var( 'shared_cart' ) );
        if ( !$shared ) {
            return;
        }
        $items = json_decode( base64_decode( $shared ), true );
        if ( !$items || !is_array( $items ) ) {
            return;
        }
        WC()->cart->empty_cart();
        foreach ( $items as $item ) {
            if ( !empty( $item['product_id'] ) && !empty( $item['quantity'] ) ) {
                WC()->cart->add_to_cart( $item['product_id'], $item['quantity'] );
            }
        }
        wp_safe_redirect( wc_get_cart_url() );
        exit;
    }

    public function displaySavedCartContent() {
        $carts = Helpers::getSavedCart();
        if ( empty( $carts ) ) {
            echo esc_html__( 'Your saved carts are empty.', 'essential-addons-for-woocommerce' );
            return;
        }
        $title = ( Helpers::getSetting( 'saveCartPageTitle' ) ?: __( 'Saved Cart', 'essential-addons-for-woocommerce' ) );
        ccpeaw_get_template( 'saved-carts/saved-carts', [
            'cartsData' => $carts,
            'title'     => $title,
        ] );
    }

    public function renderSavedCartShortcode() {
        ob_start();
        $this->displaySavedCartContent();
        return ob_get_clean();
    }

    public function renderShareCartShortcode() {
        ob_start();
        $this->renderShareLink();
        return ob_get_clean();
    }

    public function renderSavedAndShareCartShortcode() {
        ob_start();
        $this->displaySavedCartContent();
        $this->renderShareLink();
        return ob_get_clean();
    }

}
