<?php
/**
 * Plugin Name: Custom Checkout - Cart Restoration
 * Description: Prevents cart from being emptied when order is created for custom checkout
 * Version: 1.0.0
 * Author: Your Name
 */

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

/**
 * OPTION 1: Prevent cart from being emptied on order creation
 * This keeps the cart intact until payment succeeds
 */
add_action('woocommerce_checkout_order_processed', 'preserve_cart_on_order_creation', 10, 3);
function preserve_cart_on_order_creation($order_id, $posted_data, $order) {
    // Check if this is for custom checkout
    $is_custom_checkout = get_post_meta($order_id, '_custom_checkout', true);
    
    if ($is_custom_checkout === 'yes') {
        // Store cart contents in order meta for later restoration
        $cart_contents = WC()->cart->get_cart();
        update_post_meta($order_id, '_preserved_cart_contents', $cart_contents);
        
        // Don't empty the cart yet
        remove_action('woocommerce_thankyou', 'wc_empty_cart');
        
        error_log("[Custom Checkout] Cart preserved for order {$order_id}");
    }
}

/**
 * OPTION 2: Restore cart from order when payment fails
 * This is called via REST API from Next.js
 */
add_action('rest_api_init', function() {
    register_rest_route('custom-checkout/v1', '/restore-cart/(?P<order_id>\d+)', array(
        'methods' => 'POST',
        'callback' => 'restore_cart_from_order',
        'permission_callback' => function() {
            return current_user_can('edit_shop_orders');
        }
    ));
});

function restore_cart_from_order($request) {
    $order_id = $request['order_id'];
    $order = wc_get_order($order_id);
    
    if (!$order) {
        return new WP_Error('invalid_order', 'Order not found', array('status' => 404));
    }
    
    // Only restore for pending orders
    if ($order->get_status() !== 'pending') {
        return new WP_Error('invalid_status', 'Order is not pending', array('status' => 400));
    }
    
    $customer_id = $order->get_customer_id();
    
    if ($customer_id > 0) {
        // Restore cart for logged-in customer
        $cart_items = array();
        
        foreach ($order->get_items() as $item) {
            $product_id = $item->get_product_id();
            $quantity = $item->get_quantity();
            $variation_id = $item->get_variation_id();
            
            $cart_items[] = array(
                'product_id' => $product_id,
                'quantity' => $quantity,
                'variation_id' => $variation_id,
            );
        }
        
        // Store in customer meta (persistent cart)
        $cart_data = array('cart' => $cart_items);
        update_user_meta($customer_id, '_woocommerce_persistent_cart_' . get_current_blog_id(), $cart_data);
        
        error_log("[Custom Checkout] Cart restored for customer {$customer_id} from order {$order_id}");
        
        return array(
            'success' => true,
            'message' => 'Cart restored successfully',
            'items' => count($cart_items)
        );
    }
    
    return new WP_Error('guest_customer', 'Cannot restore cart for guest customers', array('status' => 400));
}

/**
 * OPTION 3: Clear cart only when payment succeeds
 * Hook into order status change
 */
add_action('woocommerce_order_status_pending_to_processing', 'clear_cart_on_payment_success', 10, 1);
add_action('woocommerce_order_status_pending_to_completed', 'clear_cart_on_payment_success', 10, 1);

function clear_cart_on_payment_success($order_id) {
    $order = wc_get_order($order_id);
    $customer_id = $order->get_customer_id();
    
    if ($customer_id > 0) {
        // Clear persistent cart
        delete_user_meta($customer_id, '_woocommerce_persistent_cart_' . get_current_blog_id());
        error_log("[Custom Checkout] Cart cleared for customer {$customer_id} after successful payment");
    }
}

/**
 * Mark orders as custom checkout
 * Add this to your order creation code in WooCommerce
 */
add_action('woocommerce_checkout_create_order', 'mark_custom_checkout_order', 10, 2);
function mark_custom_checkout_order($order, $data) {
    // Check if this is being redirected to custom checkout
    if (isset($_POST['use_custom_checkout']) || isset($_GET['custom_checkout'])) {
        $order->update_meta_data('_custom_checkout', 'yes');
    }
}

/**
 * Prevent automatic cart clearing for custom checkout orders
 */
add_filter('woocommerce_cart_needs_payment', 'prevent_cart_clear_for_custom_checkout', 10, 2);
function prevent_cart_clear_for_custom_checkout($needs_payment, $cart) {
    // Check if we're in custom checkout flow
    if (isset($_GET['custom_checkout']) || get_transient('custom_checkout_flow_' . get_current_user_id())) {
        return false; // Don't clear cart yet
    }
    return $needs_payment;
}

/**
 * Helper function to restore cart programmatically
 * Can be called from anywhere in WooCommerce
 */
function custom_checkout_restore_cart($order_id) {
    $order = wc_get_order($order_id);
    
    if (!$order) {
        return false;
    }
    
    // Clear existing cart
    WC()->cart->empty_cart();
    
    // Add items from order
    foreach ($order->get_items() as $item) {
        $product_id = $item->get_product_id();
        $quantity = $item->get_quantity();
        $variation_id = $item->get_variation_id();
        
        if ($variation_id) {
            WC()->cart->add_to_cart($product_id, $quantity, $variation_id);
        } else {
            WC()->cart->add_to_cart($product_id, $quantity);
        }
    }
    
    return true;
}






