<?php
/**
 * WishlistModule — bootstrapper for Module 10: Wishlists.
 *
 * Registers:
 *   - [titancart_wishlist]  Wishlist page shortcode
 *   - "Add to Wishlist" output injected into product card template
 *   - REST routes via WishlistController
 *   - wp_localize_script for wishlist state (in_wishlist flags)
 *
 * @package TitanCart\Modules\Wishlist
 */

namespace TitanCart\Modules\Wishlist;

use TitanCart\Storefront\TemplateLoader;
use TitanCart\Modules\Accounts\AccountManager;
use TitanCart\REST\Wishlist\WishlistController;
use TitanCart\REST\Extensions\ExtensionsController;

defined( 'ABSPATH' ) || exit;

class WishlistModule {

    private static WishlistManager $manager;

    public static function init(): void {
        // Skip all wishlist functionality if the extension is disabled.
        if ( ! ExtensionsController::is_active( 'wishlist' ) ) {
            return;
        }

        $instance      = new self();
        self::$manager = new WishlistManager();

        // Shortcode.
        add_shortcode( 'titancart_wishlist', [ $instance, 'render_wishlist' ] );

        // Inject heart button into product card output.
        add_filter( 'titancart_product_card_actions', [ $instance, 'inject_wishlist_button' ], 10, 2 );

        // Enqueue frontend script.
        add_action( 'wp_enqueue_scripts', [ $instance, 'enqueue_scripts' ] );

        // REST routes.
        add_action( 'rest_api_init', [ $instance, 'register_routes' ] );
    }

    // ══════════════════════════════════════════════════════════════════════════
    // SHORTCODE: [titancart_wishlist]
    // ══════════════════════════════════════════════════════════════════════════

    /**
     * Render the wishlist page.
     *
     * @param  array $atts  Shortcode attributes.
     * @return string
     */
    public function render_wishlist( array $atts = [] ): string {
        ob_start();

        // Shared wishlist via ?tc_wishlist=<key>
        $share_key = sanitize_key( $_GET['tc_wishlist'] ?? '' );
        if ( $share_key ) {
            $wishlist = self::$manager->find_by_share_key( $share_key );
            if ( $wishlist ) {
                $db    = titancart_db();
                $owner = $db->getRow(
                    "SELECT first_name, last_name FROM {$db->table('customers')} WHERE id = ?i LIMIT 1",
                    (int) $wishlist['customer_id']
                );
                $result = self::$manager->get_items( (int) $wishlist['customer_id'], 1, 50 );
                TemplateLoader::get( 'wishlist/wishlist.php', [
                    'items'    => $result['items'],
                    'total'    => $result['total'],
                    'owner'    => $owner,
                    'readonly' => true,
                ] );
                return (string) ob_get_clean();
            }
        }

        if ( ! is_user_logged_in() ) {
            $login_url = titancart_login_url();
            echo '<p class="tc-notice">' . wp_kses_post(
                sprintf(
                    /* translators: %s: login page URL. */
                    __( 'Please <a href="%s">log in</a> to view your wishlist.', 'titancart-lite' ),
                    esc_url( $login_url )
                )
            ) . '</p>';
            return (string) ob_get_clean();
        }

        $acc_manager = new AccountManager();
        $customer    = $acc_manager->get_or_create_current_customer();
        if ( ! $customer ) {
            return (string) ob_get_clean();
        }

        $page   = max( 1, absint( wp_unslash( $_GET['paged'] ?? 1 ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- idempotent GET view-state (pagination), see reviewer notes §6.
        $result = self::$manager->get_items( (int) $customer['id'], $page, 20 );
        $share_url = self::$manager->enable_sharing( (int) $customer['id'] );

        TemplateLoader::get( 'wishlist/wishlist.php', [
            'items'        => $result['items'],
            'total'        => $result['total'],
            'total_pages'  => $result['pages'],
            'current_page' => $page,
            'customer'     => $customer,
            'share_url'    => $share_url,
            'readonly'     => false,
        ] );

        return (string) ob_get_clean();
    }

    // ══════════════════════════════════════════════════════════════════════════
    // PRODUCT CARD INTEGRATION
    // ══════════════════════════════════════════════════════════════════════════

    /**
     * Append an "Add to Wishlist" heart button to product card actions output.
     *
     * This filter is applied inside templates/product/card.php via:
     *   echo apply_filters('titancart_product_card_actions', '', $product);
     *
     * @param  string $html      Existing actions HTML.
     * @param  array  $product   Product row.
     * @return string
     */
    public function inject_wishlist_button( string $html, array $product ): string {
        $product_id  = (int) ( $product['id'] ?? 0 );
        if ( ! $product_id ) {
            return $html;
        }

        $in_list = false;
        if ( is_user_logged_in() ) {
            $acc_manager = new AccountManager();
            $customer    = $acc_manager->get_current_customer();
            if ( $customer ) {
                $in_list = self::$manager->is_in_wishlist( (int) $customer['id'], $product_id );
            }
        }

        $label_add    = esc_attr__( 'Add to Wishlist', 'titancart-lite' );
        $label_remove = esc_attr__( 'Remove from Wishlist', 'titancart-lite' );
        $active_class = $in_list ? ' tc-wishlist-toggle--active' : '';

        $button = sprintf(
            '<button class="tc-wishlist-toggle%s"
                     data-product-id="%d"
                     data-in-list="%s"
                     aria-label="%s"
                     title="%s">
                 <svg width="18" height="18" viewBox="0 0 18 18" fill="%s" stroke="currentColor"
                      stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
                     <path d="M9 15.5S2 11 2 6a4 4 0 0 1 7-2.7A4 4 0 0 1 16 6c0 5-7 9.5-7 9.5z"/>
                 </svg>
             </button>',
            esc_attr( $active_class ),
            $product_id,
            $in_list ? 'true' : 'false',
            $in_list ? $label_remove : $label_add,
            $in_list ? $label_remove : $label_add,
            $in_list ? 'currentColor' : 'none'
        );

        return $html . $button;
    }

    // ══════════════════════════════════════════════════════════════════════════
    // SCRIPTS
    // ══════════════════════════════════════════════════════════════════════════

    /**
     * Enqueue the wishlist AJAX script on storefront pages.
     */
    public function enqueue_scripts(): void {
        if ( is_admin() ) {
            return;
        }

        $wl_file = TITANCART_PATH . 'assets/js/wishlist.js';
        wp_enqueue_script(
            'titancart-wishlist',
            TITANCART_ASSETS_URL . 'js/wishlist.js',
            [],
            file_exists( $wl_file ) ? filemtime( $wl_file ) : TITANCART_VERSION,
            true
        );

        $customer_id = 0;
        if ( is_user_logged_in() ) {
            $acc_manager = new AccountManager();
            $customer    = $acc_manager->get_current_customer();
            $customer_id = $customer ? (int) $customer['id'] : 0;
        }

        wp_localize_script( 'titancart-wishlist', 'titancartWishlist', [
            'restUrl'    => esc_url_raw( rest_url( 'titancart/v1/wishlist' ) ),
            'nonce'      => wp_create_nonce( 'wp_rest' ),
            'customerId' => $customer_id,
            'loginUrl'   => titancart_login_url(),
            'isLoggedIn' => is_user_logged_in(),
            'i18n'       => [
                'addToWishlist'      => __( 'Add to Wishlist', 'titancart-lite' ),
                'removeFromWishlist' => __( 'Remove from Wishlist', 'titancart-lite' ),
                'loginRequired'      => __( 'Please log in to save items to your wishlist.', 'titancart-lite' ),
            ],
        ] );
    }

    // ══════════════════════════════════════════════════════════════════════════
    // REST ROUTES
    // ══════════════════════════════════════════════════════════════════════════

    public function register_routes(): void {
        ( new WishlistController() )->register_routes();
    }

    // ══════════════════════════════════════════════════════════════════════════
    // HOOK: titancart_order_placed — remove purchased items from wishlist
    // ══════════════════════════════════════════════════════════════════════════

    /**
     * After a successful order, remove purchased product IDs from the
     * customer's wishlist so they don't linger as "already bought" items.
     *
     * @param int   $order_id   The new order ID.
     * @param array $order_data Order metadata (customer_id, addresses, etc.).
     * @param array $totals     Cart totals including line_items.
     */
    public function remove_purchased_items( int $order_id, array $order_data, array $totals ): void {
        $customer_id = (int) ( $order_data['customer_id'] ?? 0 );
        if ( ! $customer_id ) {
            return; // Guest — no persistent wishlist to clean.
        }

        $line_items = $totals['line_items'] ?? [];
        if ( empty( $line_items ) ) {
            return;
        }

        foreach ( $line_items as $line ) {
            $pid = (int) ( $line['product_id'] ?? 0 );
            if ( $pid ) {
                self::$manager->remove_item( $customer_id, $pid );
            }
        }
    }
}
