# Guest Shopping Cart - Quick Reference

## 🎯 What Users Can Do Now

### Before Your Changes:
❌ Guests couldn't browse products  
❌ Guests couldn't add to cart  
❌ Guests were forced to login immediately  
❌ Only authenticated users could shop  

### After Your Changes:
✅ **Guests can browse products**  
✅ **Guests can add items to cart (no login)**  
✅ **Guests can view and manage cart**  
✅ **Login only required at checkout**  
✅ **SweetAlert shows friendly login prompt**  

---

## 📍 Page-by-Page Guide

### **shop.php** - Product Browsing
| Scenario | What Happens |
|----------|-------------|
| **Guest visits** | Sees "Shop as Guest or Login" banner + all products |
| **Guest adds item** | Added to localStorage, toast shows "✅ Added to cart" |
| **Guest changes qty** | Can set quantity before adding |
| **Guest removes** | Item gone, cart count updates |
| **Logged-in user** | Sees welcome banner with their name |
| **User adds item** | Sent to database, cart-api.php processes |
| **Admin visits** | Sees "Admin cannot shop" message |

### **cart.php** - Shopping Cart Review
| User Type | Cart Source | Buttons | Actions |
|-----------|------------|---------|---------|
| **Guest** | localStorage | "Login to Checkout" | View, remove, continue shopping |
| **Logged-in** | Database | "Checkout" + "Logout" | View, remove, checkout |
| **Admin** | N/A | Logout | Redirected from shop |

### **Checkout Button Behavior**
```
Guest clicks "Proceed to Checkout"
         ↓
SweetAlert pops up:
┌─────────────────────────────┐
│ 🔐 Login Required           │
│                             │
│ Please login to complete    │
│ your purchase.              │
│                             │
│ [Go to Login] [Cancel]      │
└─────────────────────────────┘
         ↓
User clicks "Go to Login"
         ↓
Redirected to auth-system/login.php
         ↓
User enters email & password
         ↓
localStorage['userLoggedIn'] = 'true'
         ↓
Redirected to customer dashboard
         ↓
User goes to cart.php again
         ↓
Now shows "Checkout" button (no SweetAlert)
         ↓
Direct access to checkout.php
```

---

## 💾 Data Storage

### Guest Cart (Client-Side)
**Location**: Browser localStorage  
**Key**: `guestCart`  
**Format**: JSON array  
**Example**:
```javascript
[
  {
    "product_id": "1",
    "product_name": "Nordic Wooden Chair",
    "price": "10000",
    "image": "assets/img/product/product_1_1.jpg",
    "quantity": 2
  },
  {
    "product_id": "3",
    "product_name": "Rounded Dining Table",
    "price": "14000",
    "image": "assets/img/product/product_1_3.jpg",
    "quantity": 1
  }
]
```

### Authenticated Cart (Server-Side)
**Location**: MySQL database  
**Table**: `cart`  
**Columns**: id, user_id, product_id, product_name, price, image, quantity  
**Query Method**: cart-api.php

---

## 🔄 Complete User Journey

### **Path A: Guest → Buyer**
```
START
  │
  ├─ Open shop.php (no login needed)
  │
  ├─ Browse products
  │
  ├─ Click "Add to Cart" button
  │   └─ Added to localStorage
  │   └─ Toast: "✅ Product added"
  │
  ├─ Add more items (optional)
  │
  ├─ Click "View Cart" link
  │   └─ Redirected to cart.php
  │
  ├─ cart.php loads from localStorage
  │   └─ Shows: Items + Subtotal + Shipping + Tax
  │
  ├─ Click "Proceed to Checkout" button
  │   └─ SweetAlert appears
  │
  ├─ Click "Go to Login"
  │   └─ Redirected to login.php
  │
  ├─ Enter credentials
  │   └─ Session created
  │   └─ localStorage['userLoggedIn'] = 'true'
  │
  ├─ Redirected to dashboard
  │
  ├─ Navigate to checkout.php (or cart.php → checkout)
  │
  ├─ checkout.php checks: Session exists? ✅ YES
  │   └─ Loads items from database
  │
  ├─ Complete payment form
  │
  ├─ Click "Place Order"
  │   └─ Order inserted to orders table
  │   └─ Email sent to user
  │
  └─ Order confirmed!
     └─ Thank you page shown
```

### **Path B: Logged-In User**
```
START (Already logged in)
  │
  ├─ localStorage['userLoggedIn'] = 'true'
  │ Session['user_id'] = 123
  │
  ├─ Open shop.php
  │   └─ Sees: "Welcome, [Name]!" banner
  │
  ├─ Add items to cart
  │   └─ Sent to database
  │   └─ cart-api.php processes
  │
  ├─ View cart
  │   └─ cart.php loads from database
  │   └─ Shows: Items, subtotal, etc.
  │
  ├─ Click "Proceed to Checkout"
  │   └─ NO SweetAlert (already logged in)
  │   └─ Direct to checkout.php
  │
  ├─ checkout.php verifies session ✅
  │   └─ Loads items from database
  │
  ├─ Fill order form
  │
  ├─ Click "Place Order"
  │
  └─ Order complete!
```

---

## 🛠 Technical Details

### JavaScript Detection
```javascript
// Check if user is logged in
const isLoggedIn = localStorage.getItem('userLoggedIn');

if (isLoggedIn) {
    // Use authenticated cart (database)
    addToAuthenticatedCart(...);
} else {
    // Use guest cart (localStorage)
    addToGuestCart(...);
}
```

### Cart Item Structure
```javascript
{
    product_id: "1",           // From data attribute
    product_name: "Product",   // From data attribute
    price: "10000",            // In rupees
    image: "path/to/img.jpg",  // Product image
    quantity: 2                // User selected
}
```

### Key Functions

**shop.php**:
- `addToGuestCart()` - Saves to localStorage
- `addToAuthenticatedCart()` - Sends to cart-api.php
- `showToast()` - Shows success/error message

**cart.php**:
- `loadCart()` - Loads from localStorage or database
- `removeItem()` - Removes from cart
- `proceedToCheckout()` - Shows SweetAlert if guest
- `showToast()` - Notification display

---

## ⚙️ Configuration

### localStorage Keys Used
| Key | Value | Set By |
|-----|-------|--------|
| `userLoggedIn` | "true" | login.php |
| `userName` | "John Doe" | login.php |
| `userRole` | "customer" | login.php |
| `guestCart` | JSON array | shop.js |

### Amounts & Fees
- Shipping: ₹500 (flat)
- Tax: 5% of subtotal
- Total = Subtotal + Shipping + Tax

### API Endpoints
| Endpoint | Method | Purpose |
|----------|--------|---------|
| `auth-system/cart-api.php?action=add` | POST | Add authenticated user item |
| `auth-system/cart-api.php?action=remove` | POST | Remove authenticated user item |
| `auth-system/cart-api.php?action=get` | GET | Get authenticated user cart |

---

## 🧪 Quick Tests

### Test 1: Guest Shopping (2 min)
```
1. Open incognito window
2. Go to http://localhost/interior/shop.php
3. Click "Add to Cart" on any product
4. Go to http://localhost/interior/cart.php
5. Verify items show up ✓
6. Click "Proceed to Checkout"
7. SweetAlert appears? ✓
8. Click "Go to Login"
9. Redirected to login.php? ✓
```

### Test 2: Authenticated User (3 min)
```
1. Login with valid account
2. Go to shop.php
3. Add items to cart
4. Go to cart.php
5. Click "Proceed to Checkout"
6. Should go DIRECTLY to checkout.php (no SweetAlert)
7. Place test order ✓
```

### Test 3: localStorage Persistence (2 min)
```
1. Open incognito, add items as guest
2. Refresh page → items still there? ✓
3. Close & reopen incognito → items still there? ✓
4. Clear localStorage
5. Refresh → cart empty? ✓
```

---

## 🎨 UI/UX Flow

### Guest Mode
```
Shop Page (Browse)
    ↓
Add to Cart (Multiple items)
    ↓
View Cart Button
    ↓
Cart Page (Guest)
    ├─ Item 1 ✓
    ├─ Item 2 ✓
    ├─ Item 3 ✓
    └─ Subtotal, Shipping, Tax
    ↓
Proceed to Checkout (Button)
    ↓
SweetAlert Modal (Login Required)
    ├─ "🔐 Login Required"
    ├─ "Please login to complete your purchase"
    └─ [Go to Login] [Continue Shopping]
    ↓
Login Page
    ├─ Enter Email
    ├─ Enter Password
    └─ Click Login
    ↓
Dashboard (Redirected)
    └─ User logged in! localStorage set
    ↓
Checkout Page (via cart.php or direct)
    ├─ Delivery Address
    ├─ Payment Method
    └─ Place Order
    ↓
Order Confirmation ✓
```

---

## 📊 Summary of Changes

### Files Modified
- `shop.php` - Added dual-cart system
- `cart.php` - Added guest support + SweetAlert
- New libraries: SweetAlert2 (CDN)

### Files NOT Modified (Don't Need Changes)
- `checkout.php` - Already requires login
- `login.php` - Already sets localStorage
- `auth-system/cart-api.php` - Works for authenticated users
- Database schema - No changes needed

### What's Preserved
- Existing login system
- Existing database structure
- Authenticated user functionality
- Admin dashboard access
- All other pages

---

## 🚀 Deployment Notes

### Before Going Live
- [ ] Test guest checkout flow
- [ ] Test authenticated checkout flow
- [ ] Test on mobile devices
- [ ] Clear browser cache
- [ ] Test localStorage with quotes in product names
- [ ] Verify SweetAlert CDN is accessible
- [ ] Check console for JavaScript errors

### After Deployment
- [ ] Monitor error logs
- [ ] Check SweetAlert loads correctly
- [ ] Verify payment processing works
- [ ] Test guest order emails
- [ ] Confirm database inserts working

---

## ❓ Common Questions

**Q: Will guest carts persist if browser is closed?**  
A: Yes, localStorage persists until explicitly cleared. Survives browser restart.

**Q: Can guests modify quantities after adding?**  
A: Yes, on cart.php they can remove items and re-add with new quantities.

**Q: What if guest's cart is cleared (local storage)?**  
A: They lose cart data. They can re-add items or login to see their account's cart.

**Q: Can a guest cart be transferred to a user account?**  
A: Current implementation doesn't auto-transfer. User can add items again after login.

**Q: Does SweetAlert work on all browsers?**  
A: Yes, supported on IE11+ and all modern browsers.

**Q: What if user closes SweetAlert?**  
A: Clicking outside closes it, user stays on cart page.

---

## 📞 Support Checklist

If something doesn't work:
- [ ] Check browser console (F12 → Console)
- [ ] Look for red error messages
- [ ] Clear localStorage (`localStorage.clear()`)
- [ ] Clear browser cache (Ctrl+Shift+Del)
- [ ] Try in incognito/private mode
- [ ] Check if SweetAlert loads (check Network tab)
- [ ] Verify login.php sets localStorage correctly
- [ ] Check checkout.php is accessible after login

---

**Status**: ✅ Ready to Use  
**Last Updated**: December 2025  
**Version**: 1.0
