# Real-Time Shopping Cart System Setup Guide

## Overview
Your interior design website now has a complete real-time shopping cart system with PHP authentication and AJAX functionality.

## Features

✅ **User Authentication Required** - Only logged-in customers can shop
✅ **Real-Time Add to Cart** - Add products without page reload (AJAX)
✅ **Real-Time Remove from Cart** - Remove items instantly without page refresh
✅ **Real-Time Cart Count** - Cart count updates automatically
✅ **Toast Notifications** - Visual feedback for user actions
✅ **Role-Based Access** - Admin users cannot purchase
✅ **Database Integration** - All cart data persisted in MySQL

## Files Created/Modified

### New Files:
1. **auth-system/cart-api.php** - Backend API for cart operations (add, remove, get, count)
2. **auth-system/migrate-cart.php** - Database migration script to create cart table
3. **shop.php** - Shopping page with real-time cart functionality
4. **cart.php** - Shopping cart display page with remove functionality

### Database Changes:
- New `cart` table with columns: id, user_id, product_id, product_name, price, image, quantity, timestamps

## Setup Instructions

### Step 1: Create the Cart Table
Run this PHP file in your browser:
```
http://localhost/interior/auth-system/migrate-cart.php
```

Or you can manually run this SQL in phpMyAdmin:
```sql
CREATE TABLE IF NOT EXISTS cart (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    product_id INT NOT NULL,
    product_name VARCHAR(255) NOT NULL,
    price DECIMAL(10, 2) NOT NULL,
    image VARCHAR(255),
    quantity INT NOT NULL DEFAULT 1,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    INDEX (user_id),
    INDEX (product_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```

### Step 2: Test the System

1. **Register a new customer** (if not already):
   - Go to: `http://localhost/interior/auth-system/register.php`
   - Select "Customer" as role
   - Create account

2. **Login as Customer**:
   - Go to: `http://localhost/interior/auth-system/login.php`
   - Login with customer credentials

3. **Visit Shop Page**:
   - Go to: `http://localhost/interior/shop.php`
   - You should see products and can add to cart in real-time

4. **View Cart**:
   - Go to: `http://localhost/interior/cart.php`
   - See all cart items and remove them in real-time

## How It Works

### Adding to Cart (Real-Time AJAX)
```
1. User clicks "ADD TO CART" button
2. JavaScript captures product data
3. AJAX request sent to auth-system/cart-api.php?action=add
4. PHP validates user is authenticated & is a customer
5. Database inserts/updates cart item
6. Toast notification shows success
7. Cart count updates in real-time (no page reload)
```

### Removing from Cart (Real-Time AJAX)
```
1. User clicks "Remove" button on cart.php
2. AJAX request sent to auth-system/cart-api.php?action=remove
3. PHP verifies ownership (cart belongs to user)
4. Database deletes cart item
5. Cart reloads immediately (no page refresh)
6. Toast notification shows success
```

### Security Features
- Session-based authentication check
- User ID verification (users can only access their own cart)
- SQL prepared statements (prevents SQL injection)
- Role-based access control (only customers can shop)
- CSRF protection ready (can add tokens if needed)

## API Endpoints

### Add to Cart
```
POST /auth-system/cart-api.php?action=add
Body: {
    product_id: 1,
    product_name: "Product Name",
    price: 10000,
    image: "assets/img/product.jpg",
    quantity: 2
}
Response: { success: true, message: "...", cart_count: 5 }
```

### Remove from Cart
```
POST /auth-system/cart-api.php?action=remove
Body: { cart_id: 123 }
Response: { success: true, message: "...", cart_count: 4 }
```

### Get Cart Items
```
GET /auth-system/cart-api.php?action=get
Response: {
    success: true,
    items: [...],
    total: 45000,
    count: 3
}
```

### Get Cart Count
```
GET /auth-system/cart-api.php?action=count
Response: { success: true, count: 5 }
```

## Authentication Flow

### Non-Logged-In User
- Sees login/register prompt on shop.php
- Cannot add products to cart
- Redirected to login on cart.php

### Admin User
- Sees "Admin Access" message
- Cannot purchase products
- Needs to logout and login as customer

### Customer User
- Can see all products
- Can add to cart in real-time
- Can view and manage cart
- Can remove items in real-time

## Customization Options

### Add More Products
Edit `shop.php` and add new product cards:
```html
<div class="col-xl-4 col-md-6">
    <div class="th-product product-grid">
        <div class="product-img">
            <img src="assets/img/product/YOUR_IMAGE.jpg" alt="Product">
        </div>
        <div class="product-content">
            <h3 class="product-title">Product Name</h3>
            <span class="price">Rs.PRICE</span>
            <div class="btn-group justify-content-between">
                <button class="add-to-cart-btn" 
                    data-product-id="10" 
                    data-product-name="Product Name" 
                    data-price="10000" 
                    data-image="assets/img/product/YOUR_IMAGE.jpg">
                    ADD TO CART
                </button>
                <div class="quantity">
                    <input type="number" class="qty-input" 
                        step="1" min="1" max="100" value="1" 
                        data-product-id="10">
                </div>
            </div>
        </div>
    </div>
</div>
```

### Change Toast Notification Color
Edit the CSS in `shop.php` or `cart.php`:
```css
.toast-notification.success {
    background: linear-gradient(135deg, #YOUR_COLOR1, #YOUR_COLOR2);
}
```

### Adjust Cart Item Display
Modify the `renderCart()` method in `cart.php` to change layout, styling, or information displayed.

## Testing Checklist

- [ ] Database migration ran successfully
- [ ] Can register as customer
- [ ] Can login as customer
- [ ] Shop page shows products
- [ ] Can add product to cart (real-time)
- [ ] Toast notification appears on add
- [ ] Cart count updates
- [ ] Can view cart page
- [ ] Cart items display correctly
- [ ] Can remove items from cart (real-time)
- [ ] Toast notification appears on remove
- [ ] Admin cannot add to cart
- [ ] Non-logged user sees login prompt

## Troubleshooting

### "User not authenticated" error
- Make sure you're logged in
- Check if session is active
- Clear browser cookies and login again

### Cart items not showing
- Verify database migration ran
- Check if user_id is correctly stored
- Check browser console for JavaScript errors

### AJAX requests failing
- Check if cart-api.php path is correct
- Verify database connection in config/db.php
- Check if user has permission to access files

### Styling issues
- Make sure Bootstrap CSS is loaded
- Check for CSS conflicts in style.css
- Clear browser cache

## Future Enhancements

✓ Payment gateway integration (Stripe, PayPal)
✓ Order history and tracking
✓ Wishlist functionality
✓ Product reviews and ratings
✓ Inventory management
✓ Email notifications
✓ Discount codes and coupons
✓ Multiple payment methods

---

**Setup Complete!** Your real-time shopping cart is ready to use.
