<?php
/**
 * Cart Module bootstrapper.
 *
 * Wires the cart engine into WordPress:
 *   - Registers the session key cookie
 *   - Restores persistent cart on customer login
 *   - Registers REST routes
 *   - Registers storefront shortcodes
 *
 * @package TitanCart\Modules\Cart
 */

namespace TitanCart\Modules\Cart;

use TitanCart\REST\Cart\CartController;
use TitanCart\REST\Cart\ActiveCartsController;

defined( 'ABSPATH' ) || exit;

class CartModule {

    public function __construct() {
        // Initialise session key as early as possible.
        add_action( 'init', [ $this, 'init_session' ], 1 );

        // Merge guest cart into customer cart on login.
        add_action( 'wp_login', [ $this, 'on_login' ], 10, 2 );

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

        // Register [titancart_cart] shortcode.
        add_shortcode( 'titancart_cart', [ $this, 'cart_shortcode' ] );
    }

    /**
     * Ensure a session key cookie exists for the current visitor.
     */
    public function init_session(): void {
        CartSession::ensure();
    }

    /**
     * On login: restore saved customer cart and merge with any guest cart.
     *
     * @param string   $user_login
     * @param \WP_User $user
     */
    public function on_login( string $user_login, \WP_User $user ): void {
        $manager = new CartManager();
        $manager->merge_on_login( $user->ID );
    }

    /**
     * Register cart REST endpoints.
     */
    public function register_routes(): void {
        ( new CartController() )->register_routes();
        ( new ActiveCartsController() )->register_routes();
    }

    /**
     * [titancart_cart] shortcode — renders the cart page.
     *
     * @return string HTML
     */
    public function cart_shortcode(): string {
        $manager = new CartManager();
        $cart    = $manager->get_cart();
        return \TitanCart\Storefront\TemplateLoader::get_template( 'cart/cart.php', compact( 'cart' ), true );
    }

    /**
     * Boot the module.
     */
    public static function init(): void {
        new self();
    }
}
