# Favorites/Wishlist System Documentation

## Overview
A complete backend and frontend system for users to save their favorite products to a wishlist.

## Files Created/Modified

### 1. **Backend API**
**File:** `auth-system/favorites-api.php`

**Actions Available:**
- `add` - Add product to favorites
- `remove` - Remove product from favorites
- `check` - Check if product is in favorites
- `get_all` - Get all user's favorite products

**Endpoints:**
```
POST /auth-system/favorites-api.php?action=add
POST /auth-system/favorites-api.php?action=remove
GET  /auth-system/favorites-api.php?action=check&product_id=1
GET  /auth-system/favorites-api.php?action=get_all
```

### 2. **Database Setup**
**File:** `auth-system/setup-favorites.php`

**Table Created:** `favorites`

**Columns:**
- `id` - Primary key (auto-increment)
- `user_id` - User ID (foreign key to users table)
- `product_id` - Product ID
- `product_name` - Product name
- `product_price` - Product price
- `product_image` - Product image URL
- `added_at` - Timestamp when added

**Run Once:** Visit `http://localhost/interior/auth-system/setup-favorites.php` to create the table.

### 3. **Shop Page Updates**
**File:** `shop.php`

**Changes:**
- Added favorite button (heart icon) to each product card
- Button appears only for logged-in customers
- Favorite button styling with hover effects
- Favorite buttons highlight in red when product is in wishlist
- JavaScript to handle favorite/unfavorite actions
- Auto-loads favorite status on page load

**Features:**
- Real-time favorite status display
- Toast notifications for user feedback
- Responsive design for all screen sizes
- Easy add/remove functionality

### 4. **Wishlist Page**
**File:** `my-wishlist.php`

**Features:**
- Display all user's favorite products
- Beautiful grid layout for products
- Product cards show:
  - Product image
  - Product name
  - Product price
  - Remove from wishlist button
  - Add to cart button
- Summary section showing:
  - Total number of items
  - Total value of all items
- Empty state when no favorites
- Direct links to shop and cart
- Add to cart functionality

## How to Use

### For End Users

**1. Adding to Favorites:**
1. Log in as a customer
2. Go to shop.php
3. Click the heart icon (♡) on any product
4. Icon turns red (♥) when added to favorites
5. See toast notification "Added to favorites"

**2. Viewing Wishlist:**
1. Log in as a customer
2. Click on "My Wishlist" in navigation (or visit my-wishlist.php)
3. See all your favorite products
4. View total items and total value

**3. Managing Wishlist:**
1. On wishlist page, click "❌ Remove" to remove a product
2. Click "🛒 Add Cart" to add product to shopping cart
3. Continue shopping or go to cart

### For Developers

**Adding Favorite Button to New Pages:**

```php
<?php if (isset($_SESSION['user_id']) && $_SESSION['user_role'] === 'customer'): ?>
    <button class="btn-favorite" 
            data-product-id="<?php echo $product_id; ?>" 
            data-name="<?php echo $product_name; ?>" 
            data-price="<?php echo $product_price; ?>" 
            data-image="<?php echo $product_image; ?>" 
            title="Add to favorites">♡</button>
<?php endif; ?>
```

**Add CSS:**
```css
.btn-favorite {
    background: none;
    border: none;
    font-size: 1.5rem;
    cursor: pointer;
    color: #999;
    transition: all 0.3s ease;
}

.btn-favorite:hover {
    color: #d4a574;
}

.btn-favorite.active {
    color: #ff4444;
}
```

**Add JavaScript:**
```javascript
document.querySelectorAll('.btn-favorite').forEach(button => {
    button.addEventListener('click', async function(e) {
        e.preventDefault();
        const productId = this.getAttribute('data-product-id');
        const isFavorite = this.classList.contains('active');
        const action = isFavorite ? 'remove' : 'add';
        
        const response = await fetch(`auth-system/favorites-api.php?action=${action}`, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                product_id: productId,
                product_name: this.getAttribute('data-name'),
                product_price: this.getAttribute('data-price'),
                product_image: this.getAttribute('data-image')
            })
        });
        
        const data = await response.json();
        if (data.success) {
            this.classList.toggle('active');
        }
    });
});
```

## Database Security

- Uses prepared statements to prevent SQL injection
- User authentication required for all operations
- Unique constraint prevents duplicate favorites
- Foreign key enforces user-product relationship

## API Response Examples

### Add to Favorites (Success)
```json
{
    "success": true,
    "message": "Added to favorites",
    "product_id": 1
}
```

### Add to Favorites (Already Favorited)
```json
{
    "success": false,
    "message": "Product already in favorites"
}
```

### Get All Favorites
```json
{
    "success": true,
    "count": 3,
    "favorites": [
        {
            "id": 1,
            "product_id": 1,
            "product_name": "Nordic Wooden Chair",
            "product_price": "10000.00",
            "product_image": "assets/img/product/product_1_1.jpg",
            "added_at": "2025-12-20 10:30:00"
        },
        ...
    ]
}
```

## Integration Steps

1. **Setup Database:**
   - Visit `http://localhost/interior/auth-system/setup-favorites.php`
   - Table will be created automatically

2. **Update Navigation:**
   - Add link to "My Wishlist" (my-wishlist.php) in header or navigation menu
   - Link: `<a href="my-wishlist.php">❤️ My Wishlist</a>`

3. **Add to Header/Footer:**
   ```html
   <a href="my-wishlist.php" class="nav-link">❤️ Wishlist</a>
   ```

## Features & Benefits

✅ **User-Friendly:**
- Simple heart icon interface
- Visual feedback with red color when favorited
- Toast notifications for all actions

✅ **Responsive:**
- Works on all screen sizes
- Mobile-optimized
- Touch-friendly buttons

✅ **Secure:**
- Requires user authentication
- Prevents SQL injection
- Session-based security

✅ **Performant:**
- Efficient database queries
- Indexed lookups
- Cached favorite status

✅ **Scalable:**
- Supports unlimited products
- No performance degradation
- Prepared statements for safety

## Troubleshooting

**Issue:** Favorite button not showing
- **Solution:** Verify user is logged in and has customer role

**Issue:** Adding to favorites not working
- **Solution:** Check browser console for errors, verify database connection

**Issue:** Wishlist page shows empty
- **Solution:** Verify user has added products to favorites, check database

**Issue:** Database table not created
- **Solution:** Run setup script: `http://localhost/interior/auth-system/setup-favorites.php`

## Future Enhancements

- Share wishlist with friends
- Price drop notifications
- Wishlist categories
- Export wishlist to PDF
- Wishlist analytics
- Compare products from wishlist
