# Cleanup and Deployment Guide

## ✅ Migration Complete!

All frontend and backend code has been successfully migrated from Supabase to MySQL. This guide will help you clean up old files and deploy the application.

---

## 🧹 Step 1: Remove Supabase Dependencies

### Remove Supabase Packages
```bash
npm uninstall @supabase/ssr @supabase/supabase-js
```

### Delete Supabase Files
```bash
# Windows (PowerShell)
Remove-Item -Recurse -Force lib\supabase

# Linux/Mac
rm -rf lib/supabase/
```

---

## 📦 Step 2: Install Dependencies

```bash
npm install
```

This will install all required dependencies:
- `mysql2` - MySQL database client
- `bcrypt` - Password hashing
- `nodemailer` - Email sending
- `@types/bcrypt` - TypeScript types
- `@types/nodemailer` - TypeScript types

---

## 🗄️ Step 3: Set Up Database

### 1. Create MySQL Database

**On Namecheap cPanel:**
1. Go to **MySQL Databases**
2. Create a new database (e.g., `rebrandly_db`)
3. Create a database user with a strong password
4. Add the user to the database with **ALL PRIVILEGES**
5. Note down the database name, username, password, and host

### 2. Import Schema

**Option A: Using phpMyAdmin (Recommended for Namecheap)**
1. Go to **phpMyAdmin** in cPanel
2. Select your database
3. Click **Import** tab
4. Choose `database/schema.sql`
5. Click **Go**

**Option B: Using MySQL Command Line**
```bash
mysql -h localhost -u your_username -p your_database < database/schema.sql
```

### 3. Verify Tables

Check that all 6 tables were created:
- `users`
- `sessions`
- `analysis_runs`
- `exports`
- `billing_events`
- `admin_logs`

---

## ⚙️ Step 4: Configure Environment

### 1. Copy Environment Template
```bash
cp .env.example .env
```

### 2. Fill in Required Variables

Edit `.env` with your actual credentials:

```env
# MySQL Database
MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_USER=your_db_user
MYSQL_PASSWORD=your_db_password
MYSQL_DATABASE=rebrandly_db

# App URL
NEXT_PUBLIC_APP_URL=https://rebrandlyai.com

# Session Secret (generate a random 32+ character string)
SESSION_SECRET=your-super-secret-random-string-here

# SMTP Email
SMTP_HOST=business187.web-hosting.com
SMTP_PORT=465
SMTP_SECURE=true
SMTP_USER=noreply@rebrandlyai.com
SMTP_PASSWORD=your_email_password
SMTP_FROM_NAME=Rebrandly AI
SMTP_FROM_EMAIL=noreply@rebrandlyai.com

# Groq API (for AI rebranding)
GROQ_API_KEY=gsk_your_groq_api_key

# Stripe
STRIPE_SECRET_KEY=sk_live_...
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_live_...
STRIPE_WEBHOOK_SECRET=whsec_...

# OpenAI (optional - alternative to Groq)
OPENAI_API_KEY=sk-...
```

### 3. Generate Session Secret

**Option A: Node.js**
```bash
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
```

**Option B: OpenSSL**
```bash
openssl rand -hex 32
```

---

## 🧪 Step 5: Test Locally

### 1. Build the Application
```bash
npm run build
```

### 2. Start Development Server
```bash
npm run dev
```

### 3. Test Key Features

**Authentication:**
- [ ] Sign up at `http://localhost:3000/auth/sign-up`
- [ ] Check email for verification link
- [ ] Verify email
- [ ] Log in at `http://localhost:3000/auth/login`
- [ ] Log out

**User Features:**
- [ ] View dashboard
- [ ] Update profile in settings
- [ ] Check billing page

**Admin Features (create admin user first):**
```sql
UPDATE users SET is_admin = 1 WHERE email = 'your@email.com';
```
- [ ] Access admin panel at `/admin`
- [ ] View all users
- [ ] Update user plans
- [ ] Toggle admin status

**Stripe Integration:**
- [ ] Create checkout session
- [ ] Complete test payment (use Stripe test mode)
- [ ] Verify webhook received
- [ ] Check subscription status updated
- [ ] Access customer portal

---

## 🚀 Step 6: Deploy to Namecheap

### Option A: Shared Hosting (Node.js App)

1. **Upload Files via FTP/cPanel File Manager**
   - Upload all files to `public_html` or subdirectory
   - Exclude `node_modules/` and `.next/`

2. **Install Dependencies on Server**
   ```bash
   npm install --production
   ```

3. **Build on Server**
   ```bash
   npm run build
   ```

4. **Set Up Node.js App in cPanel**
   - Go to **Setup Node.js App**
   - Application root: `/home/username/public_html`
   - Application URL: `https://rebrandlyai.com`
   - Application startup file: `server.js` (create if needed)
   - Node.js version: 18.x or higher

5. **Create `server.js`** (if not exists)
   ```javascript
   const { createServer } = require('http')
   const { parse } = require('url')
   const next = require('next')

   const dev = process.env.NODE_ENV !== 'production'
   const hostname = 'localhost'
   const port = process.env.PORT || 3000

   const app = next({ dev, hostname, port })
   const handle = app.getRequestHandler()

   app.prepare().then(() => {
     createServer(async (req, res) => {
       try {
         const parsedUrl = parse(req.url, true)
         await handle(req, res, parsedUrl)
       } catch (err) {
         console.error('Error occurred handling', req.url, err)
         res.statusCode = 500
         res.end('internal server error')
       }
     }).listen(port, (err) => {
       if (err) throw err
       console.log(`> Ready on http://${hostname}:${port}`)
     })
   })
   ```

6. **Restart Application**

### Option B: VPS Hosting (Recommended)

See `NAMECHEAP_DEPLOYMENT.md` for detailed VPS deployment instructions.

---

## 🔐 Step 7: Configure Stripe Webhooks

1. **Go to Stripe Dashboard**
   - Navigate to **Developers** → **Webhooks**

2. **Add Endpoint**
   - URL: `https://rebrandlyai.com/api/stripe/webhook`
   - Events to send:
     - `checkout.session.completed`
     - `customer.subscription.updated`
     - `customer.subscription.deleted`
     - `invoice.payment_succeeded`
     - `invoice.payment_failed`

3. **Copy Webhook Secret**
   - Update `STRIPE_WEBHOOK_SECRET` in `.env`

4. **Test Webhook**
   ```bash
   stripe listen --forward-to localhost:3000/api/stripe/webhook
   ```

---

## ✅ Step 8: Post-Deployment Checklist

### Database
- [ ] All 6 tables created successfully
- [ ] Indexes created on key columns
- [ ] Foreign keys working correctly

### Environment
- [ ] All `.env` variables configured
- [ ] Session secret is strong and unique
- [ ] SMTP credentials working
- [ ] Stripe keys are production keys (not test)

### Application
- [ ] Build completes without errors
- [ ] Application starts successfully
- [ ] No console errors on homepage

### Authentication
- [ ] Signup creates user in database
- [ ] Verification email sent
- [ ] Email verification works
- [ ] Login creates session
- [ ] Session persists across page loads
- [ ] Logout clears session

### Features
- [ ] Dashboard loads user data
- [ ] Settings page updates profile
- [ ] Billing page shows correct plan
- [ ] Admin panel accessible (for admin users)
- [ ] Admin can update user plans

### Stripe
- [ ] Checkout creates session
- [ ] Payment completes successfully
- [ ] Webhook received and processed
- [ ] User plan updated in database
- [ ] Confirmation email sent
- [ ] Customer portal accessible

### Email
- [ ] Verification emails delivered
- [ ] Password reset emails delivered
- [ ] Welcome emails delivered
- [ ] Subscription emails delivered

---

## 🐛 Troubleshooting

### Database Connection Errors

**Error:** `ER_ACCESS_DENIED_ERROR`
- Check MySQL username and password in `.env`
- Verify user has privileges on the database

**Error:** `ECONNREFUSED`
- Check `MYSQL_HOST` and `MYSQL_PORT`
- Ensure MySQL server is running
- Check firewall rules

### Email Not Sending

**Error:** `Invalid login`
- Verify SMTP credentials
- Check if SMTP port is correct (465 for SSL, 587 for TLS)
- Ensure `SMTP_SECURE` matches port

**Error:** `Connection timeout`
- Check firewall/hosting provider blocks SMTP
- Try alternative SMTP port
- Consider using email service (SendGrid, Mailgun)

### Stripe Webhook Errors

**Error:** `Webhook signature verification failed`
- Verify `STRIPE_WEBHOOK_SECRET` matches Stripe dashboard
- Check webhook endpoint URL is correct
- Ensure raw body is passed to verification

### Build Errors

**Error:** `Module not found`
- Run `npm install` to install dependencies
- Clear `.next` folder and rebuild
- Check `package.json` for missing dependencies

---

## 📞 Support Resources

- **Database Setup:** See `DATABASE_SETUP.md`
- **Quick Start:** See `QUICKSTART.md`
- **Deployment:** See `NAMECHEAP_DEPLOYMENT.md`
- **Migration Notes:** See `MIGRATION_NOTES.md`

---

## 🎉 Success!

Your Rebrandly AI application is now fully migrated to MySQL and ready for production deployment on Namecheap hosting!

**Next Steps:**
1. Monitor application logs for errors
2. Test all features thoroughly
3. Set up automated backups for MySQL database
4. Configure SSL certificate (Let's Encrypt)
5. Set up monitoring/alerting

**Maintenance:**
- Regularly backup MySQL database
- Monitor disk space and database size
- Review admin logs for suspicious activity
- Keep dependencies updated
- Monitor Stripe webhook deliveries
