# Rebrandly AI - Namecheap Deployment Guide

Complete guide for deploying Rebrandly AI on Namecheap hosting with MySQL database.

---

## Table of Contents

1. [Prerequisites](#prerequisites)
2. [Database Setup](#database-setup)
3. [SMTP Email Configuration](#smtp-email-configuration)
4. [Environment Variables](#environment-variables)
5. [File Upload](#file-upload)
6. [Installation Steps](#installation-steps)
7. [Stripe Configuration](#stripe-configuration)
8. [Testing](#testing)
9. [Troubleshooting](#troubleshooting)

---

## Prerequisites

### Required Namecheap Services

- **Hosting Plan**: Shared hosting with Node.js support OR VPS hosting
- **MySQL Database**: Available through cPanel
- **Private Email** (optional but recommended): For SMTP email sending
- **Domain**: rebrandlyai.com (already configured)

### Required External Services

- **Stripe Account**: For payment processing
- **OpenAI API Key**: For AI rebranding features

---

## Database Setup

### Step 1: Create MySQL Database

1. Log into your **Namecheap cPanel**
2. Navigate to **MySQL Databases**
3. Create a new database:
   - Database name: `rebrandlyai_db` (or your preferred name)
   - Click **Create Database**

### Step 2: Create Database User

1. In the same MySQL Databases section, scroll to **MySQL Users**
2. Create a new user:
   - Username: `rebrandly_user` (or your preferred username)
   - Password: Generate a strong password (save this!)
   - Click **Create User**

### Step 3: Add User to Database

1. Scroll to **Add User to Database**
2. Select the user you just created
3. Select the database you just created
4. Click **Add**
5. On the privileges page, select **ALL PRIVILEGES**
6. Click **Make Changes**

### Step 4: Import Database Schema

1. In cPanel, navigate to **phpMyAdmin**
2. Select your database from the left sidebar
3. Click the **Import** tab
4. Click **Choose File** and select `database/schema.sql` from your project
5. Click **Go** to import the schema
6. Verify all tables were created successfully:
   - users
   - sessions
   - analysis_runs
   - exports
   - billing_events
   - admin_logs

### Step 5: Note Database Connection Details

Save these details for environment variables:
- **Host**: Usually `localhost` (check cPanel for exact value)
- **Port**: `3306` (default)
- **Database Name**: Your database name
- **Username**: Your database username
- **Password**: Your database password

---

## SMTP Email Configuration

### Option 1: Namecheap Private Email (Recommended)

1. Purchase **Namecheap Private Email** if not already active
2. Create an email account: `noreply@rebrandlyai.com`
3. Note the SMTP settings:
   - **Host**: `mail.privateemail.com`
   - **Port**: `587`
   - **Username**: `noreply@rebrandlyai.com`
   - **Password**: Your email password
   - **Secure**: `false` (use STARTTLS)

### Option 2: Gmail SMTP

1. Enable 2-factor authentication on your Gmail account
2. Generate an App Password:
   - Go to Google Account Settings
   - Security → App Passwords
   - Generate password for "Mail"
3. SMTP settings:
   - **Host**: `smtp.gmail.com`
   - **Port**: `587`
   - **Username**: Your Gmail address
   - **Password**: The app password you generated
   - **Secure**: `false`

### Option 3: SendGrid (High Volume)

1. Create a SendGrid account
2. Generate an API key
3. SMTP settings:
   - **Host**: `smtp.sendgrid.net`
   - **Port**: `587`
   - **Username**: `apikey`
   - **Password**: Your SendGrid API key
   - **Secure**: `false`

---

## Environment Variables

### Step 1: Create .env File

Copy `.env.example` to `.env`:

```bash
cp .env.example .env
```

### Step 2: Configure All Variables

Edit `.env` with your actual values:

```env
# Application URL
NEXT_PUBLIC_APP_URL=https://rebrandlyai.com

# MySQL Database (from Database Setup)
MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_USER=rebrandly_user
MYSQL_PASSWORD=your_database_password_here
MYSQL_DATABASE=rebrandlyai_db

# SMTP Email (from SMTP Configuration)
SMTP_HOST=mail.privateemail.com
SMTP_PORT=587
SMTP_SECURE=false
SMTP_USER=noreply@rebrandlyai.com
SMTP_PASS=your_email_password_here
SMTP_FROM_EMAIL=noreply@rebrandlyai.com
SMTP_FROM_NAME=Rebrandly AI

# Stripe (see Stripe Configuration section)
STRIPE_SECRET_KEY=sk_live_your_stripe_secret_key
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_live_your_stripe_publishable_key
STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret

# Stripe Price IDs (create in Stripe Dashboard)
STRIPE_PRICE_ID_PREMIUM=price_xxxxxxxxxxxxx
STRIPE_PRICE_ID_EXTRA_PREMIUM=price_xxxxxxxxxxxxx
STRIPE_PRICE_ID_PLATINUM=price_xxxxxxxxxxxxx

# OpenAI API
OPENAI_API_KEY=sk-your_openai_api_key_here

# Session Security
SESSION_SECRET=generate_random_32_char_string_here

# Environment
NODE_ENV=production
```

### Step 3: Generate Session Secret

Run this command to generate a secure session secret:

```bash
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
```

Copy the output to `SESSION_SECRET` in your `.env` file.

---

## File Upload

### For Shared Hosting

1. **Via FTP**:
   - Use FileZilla or similar FTP client
   - Connect using credentials from Namecheap
   - Upload all project files to `public_html` or your domain's directory
   - Ensure `.env` file is uploaded (may be hidden by default)

2. **Via cPanel File Manager**:
   - Log into cPanel
   - Navigate to File Manager
   - Go to your domain's directory
   - Click Upload
   - Upload project files as a ZIP
   - Extract the ZIP file
   - Upload `.env` separately

### For VPS Hosting

1. **Via Git** (Recommended):
   ```bash
   ssh user@your-vps-ip
   cd /var/www
   git clone your-repository-url rebrandlyai
   cd rebrandlyai
   cp .env.example .env
   nano .env  # Edit with your values
   ```

2. **Via SCP**:
   ```bash
   scp -r /path/to/project user@your-vps-ip:/var/www/rebrandlyai
   ```

---

## Installation Steps

### For Shared Hosting with Node.js

1. **Enable Node.js in cPanel**:
   - Navigate to **Setup Node.js App**
   - Click **Create Application**
   - Node.js version: Select latest LTS (18.x or 20.x)
   - Application mode: Production
   - Application root: Path to your project
   - Application URL: rebrandlyai.com
   - Application startup file: `server.js` or leave default

2. **Install Dependencies**:
   - In the Node.js app interface, click **Run NPM Install**
   - Or via SSH:
     ```bash
     cd /path/to/your/app
     npm install
     ```

3. **Build the Application**:
   ```bash
   npm run build
   ```

4. **Start the Application**:
   - Click **Start** in the Node.js app interface
   - Or via command line:
     ```bash
     npm start
     ```

### For VPS Hosting

1. **Install Node.js**:
   ```bash
   curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
   sudo apt-get install -y nodejs
   ```

2. **Install Dependencies**:
   ```bash
   cd /var/www/rebrandlyai
   npm install
   # or if using pnpm
   npm install -g pnpm
   pnpm install
   ```

3. **Build Application**:
   ```bash
   npm run build
   ```

4. **Install PM2** (Process Manager):
   ```bash
   sudo npm install -g pm2
   ```

5. **Start with PM2**:
   ```bash
   pm2 start npm --name "rebrandly" -- start
   pm2 save
   pm2 startup
   ```

6. **Configure Nginx** (Reverse Proxy):
   
   Create `/etc/nginx/sites-available/rebrandlyai.com`:
   ```nginx
   server {
       listen 80;
       server_name rebrandlyai.com www.rebrandlyai.com;

       location / {
           proxy_pass http://localhost:3000;
           proxy_http_version 1.1;
           proxy_set_header Upgrade $http_upgrade;
           proxy_set_header Connection 'upgrade';
           proxy_set_header Host $host;
           proxy_cache_bypass $http_upgrade;
           proxy_set_header X-Real-IP $remote_addr;
           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
           proxy_set_header X-Forwarded-Proto $scheme;
       }
   }
   ```

   Enable the site:
   ```bash
   sudo ln -s /etc/nginx/sites-available/rebrandlyai.com /etc/nginx/sites-enabled/
   sudo nginx -t
   sudo systemctl reload nginx
   ```

7. **Install SSL Certificate** (Let's Encrypt):
   ```bash
   sudo apt-get install certbot python3-certbot-nginx
   sudo certbot --nginx -d rebrandlyai.com -d www.rebrandlyai.com
   ```

---

## Stripe Configuration

### Step 1: Create Stripe Account

1. Go to [stripe.com](https://stripe.com)
2. Sign up or log in
3. Complete account verification

### Step 2: Get API Keys

1. Navigate to **Developers → API Keys**
2. Copy your **Publishable key** → Add to `.env` as `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY`
3. Click **Reveal test key** or **Reveal live key**
4. Copy your **Secret key** → Add to `.env` as `STRIPE_SECRET_KEY`

### Step 3: Create Products and Prices

1. Navigate to **Products** in Stripe Dashboard
2. Create three products:

   **Premium Plan**:
   - Name: Premium
   - Description: 100 products / 1 run per day
   - Pricing: Monthly subscription (e.g., $29/month)
   - Copy the Price ID → Add to `.env` as `STRIPE_PRICE_ID_PREMIUM`

   **Extra Premium Plan**:
   - Name: Extra Premium
   - Description: 600 products / 2 runs per day
   - Pricing: Monthly subscription (e.g., $79/month)
   - Copy the Price ID → Add to `.env` as `STRIPE_PRICE_ID_EXTRA_PREMIUM`

   **Platinum Plan**:
   - Name: Platinum
   - Description: 10,000 products / 10 runs per day
   - Pricing: Monthly subscription (e.g., $199/month)
   - Copy the Price ID → Add to `.env` as `STRIPE_PRICE_ID_PLATINUM`

### Step 4: Configure Webhook

1. Navigate to **Developers → Webhooks**
2. Click **Add endpoint**
3. Endpoint URL: `https://rebrandlyai.com/api/stripe/webhook`
4. Select events to listen to:
   - `checkout.session.completed`
   - `customer.subscription.created`
   - `customer.subscription.updated`
   - `customer.subscription.deleted`
   - `invoice.payment_succeeded`
   - `invoice.payment_failed`
5. Click **Add endpoint**
6. Copy the **Signing secret** → Add to `.env` as `STRIPE_WEBHOOK_SECRET`

---

## Testing

### Test Database Connection

Create a test file `test-db.js`:

```javascript
const mysql = require('mysql2/promise');

async function testConnection() {
  try {
    const connection = await mysql.createConnection({
      host: process.env.MYSQL_HOST,
      user: process.env.MYSQL_USER,
      password: process.env.MYSQL_PASSWORD,
      database: process.env.MYSQL_DATABASE,
    });
    
    console.log('✅ Database connection successful!');
    
    const [rows] = await connection.execute('SELECT COUNT(*) as count FROM users');
    console.log('✅ Users table accessible:', rows[0].count, 'users');
    
    await connection.end();
  } catch (error) {
    console.error('❌ Database connection failed:', error.message);
  }
}

testConnection();
```

Run: `node test-db.js`

### Test Email Sending

Create a test file `test-email.js`:

```javascript
const nodemailer = require('nodemailer');

async function testEmail() {
  try {
    const transporter = nodemailer.createTransport({
      host: process.env.SMTP_HOST,
      port: parseInt(process.env.SMTP_PORT),
      secure: process.env.SMTP_SECURE === 'true',
      auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASS,
      },
    });

    await transporter.verify();
    console.log('✅ SMTP connection successful!');

    const info = await transporter.sendMail({
      from: process.env.SMTP_FROM_EMAIL,
      to: 'your-test-email@example.com',
      subject: 'Test Email from Rebrandly AI',
      text: 'If you receive this, email is working!',
    });

    console.log('✅ Test email sent:', info.messageId);
  } catch (error) {
    console.error('❌ Email test failed:', error.message);
  }
}

testEmail();
```

Run: `node test-email.js`

### Test Application

1. Visit `https://rebrandlyai.com`
2. Test sign up flow
3. Check email for verification
4. Test login
5. Test dashboard access
6. Test admin panel (if admin user created)

---

## Troubleshooting

### Database Connection Issues

**Error: Access denied for user**
- Verify database credentials in `.env`
- Check user has been added to database with ALL PRIVILEGES
- Try connecting via phpMyAdmin with same credentials

**Error: Unknown database**
- Verify database name is correct
- Check database exists in phpMyAdmin

**Error: Can't connect to MySQL server**
- Verify `MYSQL_HOST` is correct (usually `localhost`)
- Check MySQL service is running
- For VPS: `sudo systemctl status mysql`

### Email Sending Issues

**Error: Invalid login**
- Verify SMTP credentials
- For Gmail: Ensure app password is used, not regular password
- Check SMTP port and host are correct

**Error: Connection timeout**
- Try different SMTP port (587, 465, or 25)
- Check firewall isn't blocking SMTP
- Verify SMTP_SECURE setting matches port (587 = false, 465 = true)

### Application Not Starting

**Module not found errors**
- Run `npm install` again
- Delete `node_modules` and `package-lock.json`, then `npm install`
- Check Node.js version: `node -v` (should be 18.x or 20.x)

**Port already in use**
- For VPS: `sudo lsof -i :3000` to find process
- Kill process: `kill -9 <PID>`
- Or change port in application

### Stripe Webhook Issues

**Webhook not receiving events**
- Verify webhook URL is correct and accessible
- Check webhook signing secret matches `.env`
- Test webhook in Stripe Dashboard → Send test webhook
- Check application logs for errors

### Permission Issues (VPS)

**EACCES errors**
```bash
sudo chown -R $USER:$USER /var/www/rebrandlyai
chmod -R 755 /var/www/rebrandlyai
```

### SSL Certificate Issues

**Certificate not working**
```bash
sudo certbot renew --dry-run
sudo systemctl reload nginx
```

---

## Post-Deployment Checklist

- [ ] Database schema imported successfully
- [ ] All environment variables configured
- [ ] Application builds without errors
- [ ] Application starts successfully
- [ ] Database connection working
- [ ] Email sending working
- [ ] Sign up flow working
- [ ] Email verification working
- [ ] Login working
- [ ] Dashboard accessible
- [ ] Stripe checkout working
- [ ] Stripe webhook configured
- [ ] SSL certificate installed (for production)
- [ ] Domain pointing to correct server
- [ ] Admin user created (if needed)

---

## Creating First Admin User

### Option 1: Via Database

1. Sign up normally through the website
2. In phpMyAdmin, find your user in the `users` table
3. Edit the row and set:
   - `is_admin` = `1`
   - `email_verified` = `1`
   - `plan` = `platinum`

### Option 2: Via SQL

```sql
-- After signing up, run this query with your email
UPDATE users 
SET is_admin = TRUE, 
    email_verified = TRUE, 
    plan = 'platinum' 
WHERE email = 'your-email@example.com';
```

---

## Maintenance

### Regular Tasks

**Daily**:
- Monitor application logs
- Check error rates

**Weekly**:
- Review database size
- Clean up expired sessions: `DELETE FROM sessions WHERE expires_at < NOW()`
- Check email delivery rates

**Monthly**:
- Update dependencies: `npm update`
- Review and rotate API keys
- Backup database

### Database Backup

**Via cPanel**:
1. Navigate to **Backup** in cPanel
2. Click **Download a MySQL Database Backup**
3. Select your database
4. Save the backup file

**Via Command Line**:
```bash
mysqldump -u rebrandly_user -p rebrandlyai_db > backup_$(date +%Y%m%d).sql
```

### Restore Database

```bash
mysql -u rebrandly_user -p rebrandlyai_db < backup_20240323.sql
```

---

## Support

For issues specific to:
- **Namecheap Hosting**: Contact Namecheap support
- **Stripe**: Check Stripe documentation or support
- **OpenAI**: Check OpenAI platform status
- **Application Bugs**: Check application logs and error messages

---

## Security Best Practices

1. **Never commit `.env` file** to version control
2. **Use strong passwords** for database and email
3. **Rotate API keys** regularly
4. **Enable SSL/HTTPS** in production
5. **Keep dependencies updated**: `npm audit fix`
6. **Monitor logs** for suspicious activity
7. **Backup database** regularly
8. **Use environment-specific keys** (test vs production)

---

**Deployment Complete!** 🎉

Your Rebrandly AI application should now be running on Namecheap hosting with MySQL database.
