# Guest Shopping Cart Implementation Guide

## Overview
The shopping system now supports both authenticated users and guest users to browse products, add items to cart, and proceed to checkout with a login requirement at checkout.

## System Architecture

### 1. **Shop Page (shop.php)**
- **Accessibility**: Open to all users (logged in and guests)
- **Features**:
  - Browse products with images, names, and prices
  - Add to cart button available for all users
  - Favorite hearts for authenticated users only
  - Toast notifications for cart actions
  - Guest alert banner with login option

### 2. **Cart Storage System**

#### For Guest Users (localStorage)
```javascript
// Structure stored in localStorage under key 'guestCart'
[
  {
    product_id: "1",
    product_name: "Nordic Wooden Chair",
    price: "10000",
    image: "assets/img/product/product_1_1.jpg",
    quantity: 2
  }
]
```

#### For Authenticated Users (Database)
- Stored in `cart` table with user_id reference
- Uses existing `cart-api.php` endpoint

### 3. **Cart Page (cart.php)**
- **Accessibility**: Open to both guests and authenticated users
- **For Guests**:
  - Displays cart items from localStorage
  - View and modify quantities
  - Remove items
  - See order summary (subtotal, shipping, tax)
  - Shows "Login to Checkout" button with SweetAlert
  
- **For Authenticated Users**:
  - Displays cart items from database
  - Full checkout capability
  - Option to logout

### 4. **Checkout Flow**

#### Guest User Path:
1. Browse shop.php → Add items to cart (localStorage)
2. Navigate to cart.php → View cart summary
3. Click "Proceed to Checkout" → SweetAlert triggers
4. SweetAlert shows: "🔐 Login Required - Please login to complete your purchase"
5. User clicks "Go to Login" → Redirected to auth-system/login.php
6. After login → Redirected back to checkout.php
7. Cart persists automatically (uses session)

#### Authenticated User Path:
1. Browse shop.php → Add items to cart (database)
2. Navigate to cart.php → View cart summary
3. Click "Proceed to Checkout" → Direct checkout.php access
4. Complete purchase flow

## Files Modified

### 1. **shop.php**
**Changes:**
- Added SweetAlert2 script
- Removed login gate from product cards
- All users can now add to cart
- Implemented dual-cart system in JavaScript:
  - `addToAuthenticatedCart()` - For logged-in users
  - `addToGuestCart()` - For guests (localStorage)

**Key JavaScript Functions:**
```javascript
// Automatically detects login status and routes to appropriate function
addToGuestCart(productId, productName, price, image, quantity, button, originalText, qtyInput)
addToAuthenticatedCart(productId, productName, price, image, quantity, button, originalText, qtyInput)
```

### 2. **cart.php**
**Changes:**
- Removed login redirect at top of file
- Added `$is_guest` variable to detect user status
- Modified action bar to conditionally show login/checkout buttons
- Implemented dual-cart loading system:
  - For guests: Loads from localStorage
  - For authenticated users: Loads from session/database
- Updated `loadCart()` to handle both guest and authenticated carts
- Added `proceedToCheckout()` function with SweetAlert login prompt

**Key Logic:**
```php
$is_guest = !isset($_SESSION['user_id']);
$user_name = $is_guest ? 'Guest User' : htmlspecialchars($_SESSION['user_name']);
```

### 3. **auth-system/login.php** (No changes - already sets localStorage)
- Already includes: `localStorage.setItem('userLoggedIn', 'true');`
- Already stores: userName and userRole

## Usage Flow

### For Guests:
```
shop.php (Add items) 
    ↓
cart.php (Review cart)
    ↓
Click "Proceed to Checkout"
    ↓
SweetAlert Modal: "Login Required"
    ↓
Click "Go to Login" button
    ↓
login.php (Authenticate)
    ↓
Sets localStorage['userLoggedIn'] = 'true'
    ↓
checkout.php (Complete purchase)
```

### For Authenticated Users:
```
shop.php (Add items via database)
    ↓
cart.php (Review cart from database)
    ↓
Click "Proceed to Checkout"
    ↓
Direct access to checkout.php
```

## Technology Stack

### Frontend:
- **localStorage API**: Guest cart persistence
- **SweetAlert2**: Beautiful confirmation dialogs
- **Fetch API**: AJAX requests for cart operations
- **Vanilla JavaScript**: No jQuery dependency

### Backend:
- **PHP Sessions**: Authenticated user tracking
- **MySQL**: Cart storage for authenticated users
- **JSON**: API responses

## Key Features

✅ **Guest Shopping**
- Browse all products
- Add to cart without login
- View cart summary
- Persists across browser sessions (localStorage)

✅ **Seamless Checkout**
- SweetAlert modal for login prompt
- Non-intrusive modal dialog
- Professional UX

✅ **User Authentication**
- Existing login system integration
- Role-based access control
- Admin users cannot shop (if role is not 'customer')

✅ **Responsive Design**
- Works on mobile, tablet, desktop
- Touch-friendly buttons
- Optimized layout for all screen sizes

✅ **Cart Synchronization**
- Guest cart data preserved
- Can be transferred to account after login
- Database cart takes precedence for authenticated users

## Testing Checklist

- [ ] Browse shop.php as guest
- [ ] Add 2-3 items to cart
- [ ] Navigate to cart.php
- [ ] Verify items display correctly
- [ ] Click "Proceed to Checkout"
- [ ] SweetAlert modal appears
- [ ] Click "Go to Login"
- [ ] Login page loads
- [ ] Complete login
- [ ] Verify redirect to checkout.php
- [ ] Add items as logged-in user
- [ ] Verify database cart shows items
- [ ] Test on mobile (480px)
- [ ] Test on tablet (768px)
- [ ] Test on desktop (1024px+)

## Cart Data Management

### Guest Cart (localStorage)
```javascript
// View guest cart
const cart = JSON.parse(localStorage.getItem('guestCart') || '[]');
console.log(cart);

// Clear guest cart
localStorage.removeItem('guestCart');

// Add item programmatically
let cart = JSON.parse(localStorage.getItem('guestCart') || '[]');
cart.push({
    product_id: '1',
    product_name: 'Product Name',
    price: '10000',
    image: 'path/to/image.jpg',
    quantity: 1
});
localStorage.setItem('guestCart', JSON.stringify(cart));
```

### Authenticated Cart (Database via cart-api.php)
- Uses existing `auth-system/cart-api.php`
- Endpoints: add, remove, get, count
- User_id based filtering

## Security Considerations

✅ **Protected Checkout**
- Login required before payment
- Session validation on checkout.php

✅ **Data Validation**
- Product IDs validated
- Quantities checked (positive integers)
- Prices verified

✅ **localStorage Limitations**
- Client-side only (can be cleared)
- No server-side validation until login
- ~5-10MB storage limit per domain

## Future Enhancements

1. **Cart Merge on Login**
   - Transfer guest cart items to authenticated cart
   - Merge quantities if items overlap
   
2. **Guest Email for Notifications**
   - Optional email collection
   - Order confirmation emails
   
3. **Abandoned Cart Recovery**
   - Email reminders to guests
   - Cart recovery links
   
4. **Persistent Guest Cart**
   - Extend localStorage data to 30 days
   - Cookie backup for longer persistence
   
5. **One-Click Checkout**
   - Store guest email in localStorage
   - Speed up repeat guest purchases

## Troubleshooting

### Cart Not Persisting
- Check localStorage quota
- Clear browser cache
- Check browser's localStorage settings

### Login Not Setting localStorage
- Verify login.php is setting localStorage correctly
- Check browser console for errors
- Verify localStorage not disabled

### Checkout Button Not Working
- Verify SweetAlert2 library loaded
- Check proceedToCheckout() function
- Verify userLoggedIn key in localStorage

### Database Cart Not Loading
- Verify session_start() called
- Check $_SESSION['user_id'] set
- Verify cart-api.php endpoint accessible

## Support & Maintenance

For issues or enhancements:
1. Check browser console for JavaScript errors
2. Check PHP error logs
3. Verify database connection
4. Test with fresh browser instance (incognito)
5. Clear localStorage and retry
