# 🛒 Cart Restoration - Complete Solution

## 🔴 The Problem

**WooCommerce empties the cart IMMEDIATELY when an order is created**, not when payment succeeds. This happens BEFORE the customer reaches your checkout page.

### Why This Happens

This is **standard WooCommerce behavior**:
1. Customer clicks "Checkout" in WooCommerce
2. WooCommerce creates order (status: "pending")
3. **WooCommerce empties the cart** ← This is the problem
4. Customer redirected to custom checkout
5. If payment fails → Cart is already empty!

## ✅ The Solution (3 Options)

### Option 1: Automatic Cart Restoration (Implemented) ⭐ RECOMMENDED

The Next.js checkout now **automatically restores the cart** when payment fails.

**How it works:**
1. Payment fails
2. Webhook receives `payment_intent.payment_failed`
3. System restores cart items from the order
4. Customer can return to cart and try again

**What's been implemented:**
- ✅ `WooCommerce.restoreCartFromOrder()` method
- ✅ Webhook automatically restores cart on failure
- ✅ Works for logged-in customers
- ✅ Adds metadata to track restoration

**Limitations:**
- Only works for logged-in customers (WooCommerce API limitation)
- Guest customers need Option 2 (WooCommerce plugin)

---

### Option 2: WooCommerce Plugin (For Full Control) ⭐ BEST UX

Install the provided WooCommerce plugin to prevent cart from being emptied until payment succeeds.

**Installation:**

1. Copy `woocommerce-cart-restoration-plugin.php` to `/wp-content/plugins/`
2. Activate the plugin in WordPress admin
3. Done!

**What it does:**
- Prevents cart from being emptied when order is created
- Clears cart only when payment succeeds
- Works for both logged-in and guest customers
- Provides REST API endpoint for cart restoration

**Benefits:**
- ✅ Best user experience
- ✅ Works for all customers
- ✅ Handles stock levels correctly
- ✅ No manual intervention needed

---

### Option 3: Manual Cart Management

Don't create the order until payment succeeds (requires major refactoring).

**Not recommended** - requires significant changes to the flow.

---

## 🚀 Recommended Setup

### For Production (Best UX):

1. **Install the WooCommerce plugin** (Option 2)
2. **Keep the automatic restoration** (Option 1) as backup
3. Result: Cart never gets emptied until payment succeeds!

### Quick Setup (No Plugin):

1. **Use automatic restoration** (Option 1 - already implemented)
2. Works for logged-in customers
3. Guest customers will need to re-add items manually

---

## 📝 How to Install the Plugin

### Step 1: Create Plugin File

```bash
# On your WordPress server
cd /wp-content/plugins/
mkdir custom-checkout-cart-restoration
cd custom-checkout-cart-restoration
nano custom-checkout-cart-restoration.php
```

### Step 2: Copy Plugin Code

Copy the contents of `woocommerce-cart-restoration-plugin.php` into the file.

### Step 3: Activate Plugin

1. Go to WordPress Admin → Plugins
2. Find "Custom Checkout - Cart Restoration"
3. Click "Activate"

### Step 4: Mark Orders for Custom Checkout

Add this to your WooCommerce order creation:

```php
// When creating order that will use custom checkout
update_post_meta($order_id, '_custom_checkout', 'yes');
```

Or add query parameter when redirecting:

```php
$checkout_url = generate_checkout_url($order_id);
$checkout_url .= '&custom_checkout=1';
```

---

## 🧪 Testing

### Test Cart Restoration

1. **Add items to cart**
2. **Create order** (should NOT empty cart with plugin)
3. **Go to checkout**
4. **Use declined card:** `4000 0000 0000 0002`
5. **Check cart** → Should still have items!

### Test Successful Payment

1. **Add items to cart**
2. **Create order**
3. **Go to checkout**
4. **Use valid card:** `4242 4242 4242 4242`
5. **Check cart** → Should be empty!

---

## 🔧 Configuration

### For Logged-in Customers Only

No configuration needed - automatic restoration works out of the box.

### For Guest + Logged-in Customers

Install the WooCommerce plugin.

### Custom Behavior

Edit the plugin file to customize:
- When cart is cleared
- How restoration works
- What metadata is stored

---

## 📊 What's Tracked

### Order Metadata

| Meta Key | Description | When Set |
|----------|-------------|----------|
| `_custom_checkout` | Marks order for custom checkout | Order creation |
| `_preserved_cart_contents` | Backup of cart items | Order creation |
| `_cart_restored_on_failure` | Whether cart was restored | Payment failure |
| `_cart_restored` | Restoration success | Order cancellation |

### Console Logs

```
[v0] Attempting to restore cart from order 5938
[v0] Cart restored successfully for customer 123
[Custom Checkout] Cart preserved for order 5938
[Custom Checkout] Cart cleared for customer 123 after successful payment
```

---

## 🎯 Summary

| Scenario | Without Plugin | With Plugin |
|----------|----------------|-------------|
| Payment Success | Cart empty ✅ | Cart empty ✅ |
| Payment Failure (Logged-in) | Cart restored ✅ | Cart never emptied ✅ |
| Payment Failure (Guest) | Cart lost ❌ | Cart never emptied ✅ |
| Abandoned Checkout (Logged-in) | Cart lost ❌ | Cart intact ✅ |
| Abandoned Checkout (Guest) | Cart lost ❌ | Cart intact ✅ |

**Recommendation:** Install the plugin for the best user experience!

---

## 🆘 Troubleshooting

### Cart Still Empty After Failure

**Check:**
1. Is customer logged in? (Automatic restoration only works for logged-in)
2. Is plugin activated? (Check WordPress → Plugins)
3. Check console logs for restoration messages
4. Check order metadata for `_cart_restored_on_failure`

### Plugin Not Working

**Check:**
1. Plugin is activated
2. Order has `_custom_checkout` meta set to `yes`
3. Check WordPress error logs
4. Verify WooCommerce version is compatible

### Guest Customers Can't Restore Cart

**Solution:** Install the WooCommerce plugin - it's the only way to handle guest carts properly.

---

## 🔒 Security Notes

- Cart restoration only works for the order's customer
- REST API endpoint requires admin permissions
- Metadata tracks all restoration attempts
- Stock levels are checked during restoration

---

**Last Updated:** December 22, 2024
**Status:** ✅ Implemented
**Plugin Required:** Optional (but recommended)






