# 🚀 cPanel Deployment Guide - Textile Manager with MySQL

This comprehensive guide will help you deploy your Textile Manager application on cPanel hosting with MySQL database.

## 📋 Prerequisites

### What You Need:
- ✅ cPanel hosting account with MySQL support
- ✅ Node.js support (check with your hosting provider)
- ✅ SSH access (optional but recommended)
- ✅ Domain name pointed to your hosting
- ✅ FTP/File Manager access

### Hosting Requirements:
- **PHP**: 7.4+ (for phpMyAdmin)
- **MySQL**: 5.7+ or MariaDB 10.3+
- **Node.js**: 16+ (if supported)
- **Storage**: At least 1GB free space
- **Memory**: 512MB+ RAM recommended

## 🗄️ Database Setup

### Step 1: Create MySQL Database

1. **Login to cPanel**
2. **Go to "MySQL Databases"**
3. **Create Database:**
   ```
   Database Name: your_username_textile_manager
   (cPanel usually adds your username as prefix)
   ```

4. **Create Database User:**
   ```
   Username: your_username_textile_user
   Password: [Generate strong password]
   ```

5. **Add User to Database:**
   - Select the user and database
   - Grant ALL PRIVILEGES

6. **Note Down Database Details:**
   ```
   Host: localhost (usually)
   Database: your_username_textile_manager
   Username: your_username_textile_user
   Password: [your password]
   Port: 3306 (default)
   ```

### Step 2: Import Database Schema

1. **Open phpMyAdmin** (from cPanel)
2. **Select your database**
3. **Go to "Import" tab**
4. **Upload and execute:**
   - `database/schema.sql`
   - `database/migrations/001_initial_setup.sql`
   - `database/seeders/default_data.sql`

**Alternative: Manual SQL Execution**
```sql
-- Copy and paste the contents of schema.sql
-- Then copy and paste the contents of seeders/default_data.sql
```

## 📁 File Upload and Configuration

### Step 3: Upload Application Files

**Option A: Using File Manager**
1. **Compress your project** (excluding node_modules)
2. **Upload ZIP file** to public_html or subdirectory
3. **Extract files** using cPanel File Manager

**Option B: Using FTP**
1. **Connect via FTP client** (FileZilla, WinSCP)
2. **Upload all files** except node_modules
3. **Set proper permissions** (755 for directories, 644 for files)

### Step 4: Environment Configuration

1. **Create `.env.local` file** in root directory:
```env
# Database Configuration
DB_HOST=localhost
DB_USER=your_username_textile_user
DB_PASSWORD=your_database_password
DB_NAME=your_username_textile_manager
DB_PORT=3306

# JWT Secret (generate a strong random string)
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production

# Application Settings
NODE_ENV=production
NEXT_PUBLIC_APP_URL=https://yourdomain.com

# Optional: Email Configuration
SMTP_HOST=mail.yourdomain.com
SMTP_PORT=587
SMTP_USER=noreply@yourdomain.com
SMTP_PASS=your_email_password
```

2. **Set File Permissions:**
```bash
chmod 600 .env.local  # Secure environment file
chmod 755 public/     # Public assets
chmod 644 package.json # Package file
```

## 🔧 Node.js Setup (If Supported)

### Step 5: Install Dependencies

**If your host supports Node.js:**

1. **SSH into your server** (if available)
```bash
cd /path/to/your/app
npm install --production
```

2. **Build the application:**
```bash
npm run build
```

3. **Start the application:**
```bash
npm start
```

**If Node.js is not supported:**
- Consider using **Vercel**, **Netlify**, or **Railway** for the frontend
- Use cPanel only for the MySQL database
- Update API endpoints to point to your cPanel domain

## 🌐 Alternative Deployment (Hybrid Approach)

### Step 6: Frontend on Vercel + Database on cPanel

**This is recommended if cPanel doesn't support Node.js:**

1. **Deploy Frontend to Vercel:**
   ```bash
   # Install Vercel CLI
   npm i -g vercel
   
   # Deploy
   vercel --prod
   ```

2. **Configure Environment Variables in Vercel:**
   ```env
   DB_HOST=your-cpanel-domain.com
   DB_USER=your_username_textile_user
   DB_PASSWORD=your_database_password
   DB_NAME=your_username_textile_manager
   DB_PORT=3306
   JWT_SECRET=your-jwt-secret
   ```

3. **Update Database Host:**
   - Use your cPanel domain as DB_HOST
   - Ensure remote MySQL access is enabled

## 🔒 Security Configuration

### Step 7: Secure Your Installation

1. **Database Security:**
   ```sql
   -- Create a read-only user for reports
   CREATE USER 'readonly_user'@'%' IDENTIFIED BY 'strong_password';
   GRANT SELECT ON textile_manager.* TO 'readonly_user'@'%';
   
   -- Limit connections
   SET GLOBAL max_connections = 100;
   ```

2. **File Permissions:**
   ```bash
   # Secure sensitive files
   chmod 600 .env.local
   chmod 600 database/
   
   # Public files
   chmod 755 public/
   chmod 644 public/*
   ```

3. **htaccess Security** (create `.htaccess` in root):
   ```apache
   # Deny access to sensitive files
   <Files ".env*">
       Order allow,deny
       Deny from all
   </Files>
   
   <Files "*.sql">
       Order allow,deny
       Deny from all
   </Files>
   
   # Security headers
   Header always set X-Content-Type-Options nosniff
   Header always set X-Frame-Options DENY
   Header always set X-XSS-Protection "1; mode=block"
   ```

## 📊 Database Management

### Step 8: Database Administration

1. **Create Admin User:**
   ```sql
   INSERT INTO users (email, password_hash, display_name, role, shop_id, is_active) 
   VALUES (
       'admin@yourdomain.com',
       '$2b$10$hashed_password_here',
       'Admin User',
       'owner',
       1,
       TRUE
   );
   ```

2. **Create Shop Profile:**
   ```sql
   INSERT INTO shops (shop_name, email, address, contact, owner_id) 
   VALUES (
       'Your Tailor Shop',
       'contact@yourdomain.com',
       'Your Shop Address',
       '+1234567890',
       1
   );
   ```

3. **Regular Backups:**
   ```bash
   # Create backup script
   mysqldump -u username -p database_name > backup_$(date +%Y%m%d).sql
   ```

## 🚀 Performance Optimization

### Step 9: Optimize for Production

1. **Database Optimization:**
   ```sql
   -- Add indexes for better performance
   CREATE INDEX idx_orders_shop_date ON orders(shop_id, order_date);
   CREATE INDEX idx_customers_shop_name ON customers(shop_id, name);
   
   -- Optimize tables
   OPTIMIZE TABLE orders, customers, inventory;
   ```

2. **Enable Compression:**
   ```apache
   # Add to .htaccess
   <IfModule mod_deflate.c>
       AddOutputFilterByType DEFLATE text/plain
       AddOutputFilterByType DEFLATE text/html
       AddOutputFilterByType DEFLATE text/xml
       AddOutputFilterByType DEFLATE text/css
       AddOutputFilterByType DEFLATE application/xml
       AddOutputFilterByType DEFLATE application/xhtml+xml
       AddOutputFilterByType DEFLATE application/rss+xml
       AddOutputFilterByType DEFLATE application/javascript
       AddOutputFilterByType DEFLATE application/x-javascript
   </IfModule>
   ```

3. **Caching Headers:**
   ```apache
   # Cache static assets
   <IfModule mod_expires.c>
       ExpiresActive On
       ExpiresByType image/jpg "access plus 1 month"
       ExpiresByType image/jpeg "access plus 1 month"
       ExpiresByType image/gif "access plus 1 month"
       ExpiresByType image/png "access plus 1 month"
       ExpiresByType text/css "access plus 1 month"
       ExpiresByType application/pdf "access plus 1 month"
       ExpiresByType application/javascript "access plus 1 month"
   </IfModule>
   ```

## 🔧 Troubleshooting

### Common Issues and Solutions

1. **Database Connection Failed:**
   ```
   Error: ECONNREFUSED
   
   Solutions:
   - Check database credentials in .env.local
   - Verify MySQL service is running
   - Check if remote connections are allowed
   - Ensure correct hostname (localhost vs domain)
   ```

2. **Permission Denied:**
   ```
   Error: Access denied for user
   
   Solutions:
   - Verify database user has correct privileges
   - Check password is correct
   - Ensure user is added to database
   ```

3. **File Upload Issues:**
   ```
   Error: Cannot write to directory
   
   Solutions:
   - Check file permissions (755 for directories)
   - Verify disk space availability
   - Check upload_max_filesize in PHP settings
   ```

4. **Node.js Not Supported:**
   ```
   Solutions:
   - Use Vercel/Netlify for frontend
   - Keep only API routes on cPanel
   - Use static export: npm run export
   ```

## 📱 Mobile Access Setup

### Step 10: Configure for Mobile

1. **PWA Configuration:**
   ```json
   // public/manifest.json
   {
     "name": "Textile Manager",
     "short_name": "TextileApp",
     "start_url": "/",
     "display": "standalone",
     "theme_color": "#468499",
     "background_color": "#f0f2f5"
   }
   ```

2. **Responsive Design:**
   - Ensure all pages work on mobile
   - Test touch interactions
   - Optimize for slow connections

## 🔄 Maintenance

### Step 11: Regular Maintenance

1. **Database Maintenance:**
   ```sql
   -- Weekly cleanup
   DELETE FROM audit_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 90 DAY);
   
   -- Monthly optimization
   OPTIMIZE TABLE orders, customers, inventory;
   
   -- Check table sizes
   SELECT table_name, ROUND(((data_length + index_length) / 1024 / 1024), 2) AS 'Size (MB)'
   FROM information_schema.tables 
   WHERE table_schema = 'your_database_name';
   ```

2. **Backup Schedule:**
   ```bash
   # Daily backup (add to cron)
   0 2 * * * mysqldump -u user -p database > /backups/daily_$(date +\%Y\%m\%d).sql
   
   # Weekly cleanup
   0 3 * * 0 find /backups -name "daily_*.sql" -mtime +7 -delete
   ```

## 📞 Support and Monitoring

### Step 12: Monitoring Setup

1. **Health Check Endpoint:**
   ```javascript
   // pages/api/health.js
   export default function handler(req, res) {
     res.status(200).json({ 
       status: 'healthy', 
       timestamp: new Date().toISOString() 
     });
   }
   ```

2. **Error Logging:**
   ```javascript
   // Log errors to file
   const fs = require('fs');
   
   function logError(error) {
     const log = `${new Date().toISOString()}: ${error.message}\n`;
     fs.appendFileSync('/path/to/error.log', log);
   }
   ```

## ✅ Deployment Checklist

- [ ] MySQL database created and configured
- [ ] Database schema imported successfully
- [ ] Environment variables configured
- [ ] Application files uploaded
- [ ] Dependencies installed (if Node.js supported)
- [ ] Security measures implemented
- [ ] Admin user created
- [ ] Shop profile configured
- [ ] Performance optimizations applied
- [ ] Backup system configured
- [ ] Mobile access tested
- [ ] Health monitoring setup

## 🎉 Success!

Your Textile Manager is now deployed on cPanel with MySQL! 

**Access your application:**
- **Frontend:** https://yourdomain.com
- **Admin Panel:** https://yourdomain.com/login
- **Database:** phpMyAdmin via cPanel

**Default Login:**
- Email: admin@yourdomain.com
- Password: [as configured during setup]

---

## 📚 Additional Resources

- [cPanel Documentation](https://docs.cpanel.net/)
- [MySQL Documentation](https://dev.mysql.com/doc/)
- [Next.js Deployment](https://nextjs.org/docs/deployment)
- [Vercel Deployment](https://vercel.com/docs)

**Need Help?** Check the troubleshooting section or contact your hosting provider for Node.js support details.
