# GlowSpace Migration Guide

## Overview

This guide will help you migrate your GlowSpace eCommerce website from JSON-based storage to MySQL/MariaDB database. This migration will:

- ✅ Preserve all existing products, images, and data
- ✅ Maintain all existing URLs and functionality
- ✅ Add professional user authentication system
- ✅ Enable cart and wishlist synchronization across devices
- ✅ Improve performance and security
- ✅ Provide advanced admin features

## Prerequisites

Before starting the migration, ensure you have:

1. **MySQL/MariaDB Server** installed and running
2. **PHP 7.4+** with PDO MySQL extension enabled
3. **Database access** with CREATE, INSERT, UPDATE, DELETE privileges
4. **Backup** of your current `/data` folder (automatically created by migration script)

## Migration Steps

### Step 1: Configure Database Connection

Edit the `config.php` file and update your database credentials:

```php
// Database Configuration
define('DB_HOST', 'localhost');        // Your database host
define('DB_NAME', 'glowspace');        // Your database name
define('DB_USER', 'root');             // Your database username
define('DB_PASS', '');                 // Your database password
```

### Step 2: Create Database Schema

Run the SQL schema file to create all required tables:

**Option 1: Using phpMyAdmin**
1. Open phpMyAdmin
2. Create a new database named `glowspace`
3. Import the `database/schema.sql` file

**Option 2: Using Command Line**
```bash
mysql -u root -p < database/schema.sql
```

### Step 3: Run Migration Script

Execute the migration script from command line:

```bash
php database/migrate.php
```

The migration script will:

1. **Create backup** of all JSON files in `/data/backup_[timestamp]/`
2. **Migrate data** from JSON to MySQL tables:
   - Products and product images
   - Categories
   - Orders and order items
   - Customers
   - Landing pages
   - Banners
   - Coupons
   - Reviews
   - Admin users
   - Settings
3. **Verify migration** by comparing record counts
4. **Generate migration log** with detailed statistics

### Step 4: Verify Migration

After migration, the script will display statistics like:

```
========================================
  Migration Completed Successfully!
========================================

Statistics:
  products: 4
  categories: 2
  orders: 1
  landing_pages: 4
  banners: 1
  coupons: 0
  reviews: 0
  admins: 0
  settings: 0
  total: 12

Backup location: /data/backup_2026-07-29_08-46-00
```

Check that:
- ✅ All products have been migrated
- ✅ All orders are preserved
- ✅ Image paths remain correct
- ✅ No data loss occurred

### Step 5: Test the Website

1. **Open your website** in a browser
2. **Test product pages** - ensure products load correctly
3. **Test cart functionality** - add items to cart
4. **Test checkout** - place a test order
5. **Test landing pages** - verify landing page functionality
6. **Test admin panel** - access admin.php

## New Features After Migration

### User Authentication

Users can now:
- Register with email and password
- Login with "Remember Me" functionality
- Reset forgotten passwords
- Manage their profiles
- View order history

### User Dashboard

Access at `dashboard.php`:
- Order statistics
- Recent orders
- Wishlist management
- Quick actions

### User Profile

Access at `profile.php`:
- Profile picture upload
- Cover banner
- Account settings
- Address management
- Wishlist preview

### Cart Synchronization

- Cart items sync with user account
- Works across multiple devices
- Persists after login/logout

### Wishlist System

- Add/remove products from wishlist
- Synced with user account
- Move wishlist items to cart

## Database Schema Overview

### Core Tables

- **users** - User accounts and authentication
- **user_profiles** - Extended user information
- **user_addresses** - Saved addresses
- **products** - Product catalog
- **categories** - Product categories
- **orders** - Order management
- **order_items** - Order line items
- **cart** - Shopping cart
- **wishlist** - User wishlists
- **landing_pages** - Landing page configurations
- **settings** - Site settings

### Security Features

- Password hashing with bcrypt
- CSRF token protection
- SQL injection prevention (prepared statements)
- XSS protection
- Secure session management
- Rate limiting support

## Rollback Procedure

If you need to rollback to JSON storage:

1. **Stop using the website**
2. **Restore JSON files** from backup:
   ```bash
   cp -r data/backup_[timestamp]/* data/
   ```
3. **Revert code changes** (if you modified any files)
4. **Test the website** with JSON storage

## Troubleshooting

### Database Connection Error

**Problem**: "Database connection failed"

**Solution**: 
- Check MySQL service is running
- Verify database credentials in `config.php`
- Ensure database exists and user has proper permissions

### Migration Script Fails

**Problem**: Migration script stops with error

**Solution**:
- Check PHP error logs
- Ensure PDO MySQL extension is enabled
- Verify file permissions on `/data` folder
- Check database table creation permissions

### Images Not Loading

**Problem**: Product images show as broken

**Solution**:
- Verify `/uploads` folder exists and has correct permissions
- Check image paths in database match actual file locations
- Ensure web server has read access to uploads folder

### Orders Not Creating

**Problem**: Orders fail to save

**Solution**:
- Check database connection for orders table
- Verify Steadfast API credentials in config
- Check PHP error logs for specific error messages

## File Structure After Migration

```
glowspace/
├── config.php              # Database and system configuration
├── index.php               # Main storefront (updated for MySQL)
├── landing.php             # Landing pages (updated for MySQL)
├── admin.php               # Admin panel (to be updated)
├── login.php               # User login page (NEW)
├── register.php            # User registration page (NEW)
├── profile.php             # User profile page (NEW)
├── dashboard.php           # User dashboard (NEW)
├── database/
│   ├── schema.sql          # Database schema
│   └── migrate.php         # Migration script
├── includes/
│   ├── db.php              # Database helper functions
│   └── auth.php            # Authentication system
├── data/
│   ├── backup_[timestamp]/ # Automatic backup folder
│   └── data/               # Original JSON files (preserved)
└── uploads/                # Product images (unchanged)
```

## Performance Optimizations

The migration includes:

- **Database indexing** on frequently queried columns
- **Prepared statements** for SQL injection prevention
- **Optimized queries** for faster data retrieval
- **Connection pooling** via PDO
- **Lazy loading** for large datasets

## Security Improvements

- **Password hashing** with bcrypt (cost factor 10)
- **CSRF tokens** on all forms
- **Input validation** and sanitization
- **SQL injection prevention** via prepared statements
- **XSS protection** via output encoding
- **Secure session management**
- **Rate limiting** support

## Support

If you encounter any issues during migration:

1. Check the migration log in the backup folder
2. Review PHP error logs
3. Verify database table structure matches schema
4. Test database connection independently
5. Ensure all PHP extensions are enabled

## Next Steps

After successful migration:

1. **Update admin panel** to use database functions (admin.php)
2. **Implement responsive design** improvements
3. **Add additional user features** as needed
4. **Set up regular database backups**
5. **Monitor performance** and optimize queries
6. **Update Steadfast courier** credentials if needed

## Important Notes

- ⚠️ **Never delete** the backup folder until you've thoroughly tested the migration
- ⚠️ **Keep original JSON files** until you're confident the migration is complete
- ⚠️ **Test all functionality** before going live with the migrated system
- ⚠️ **Update your database credentials** in config.php before running migration
- ⚠️ **Ensure proper file permissions** on uploads and data folders

## Migration Checklist

- [ ] Database configured in config.php
- [ ] Database schema created
- [ ] Migration script executed successfully
- [ ] All products migrated correctly
- [ ] All orders preserved
- [ ] Images loading properly
- [ ] User registration working
- [ ] User login working
- [ ] Cart functionality working
- [ ] Checkout process working
- [ ] Landing pages working
- [ ] Admin panel accessible
- [ ] Steadfast integration working
- [ ] Backup folder verified
- [ ] Migration log reviewed
- [ ] Website tested thoroughly

## Success Criteria

Migration is successful when:

✅ All existing products are visible on the website
✅ All historical orders are preserved
✅ New user accounts can be created
✅ Users can login and access their dashboard
✅ Cart and wishlist work correctly
✅ Orders can be placed successfully
✅ Steadfast courier integration works
✅ Landing pages function properly
✅ Admin panel can manage products
✅ No data loss occurred
✅ Website performance is improved

---

**Migration Version**: 1.0  
**Last Updated**: 2026-07-29  
**Compatible With**: GlowSpace v2.0+
