# Database Synchronization Guide - cPanel & Localhost

## Current Situation
You have TWO separate databases:
1. **Localhost Database**: `login-table` (for local development)
2. **cPanel Database**: `mahamusa_db` (for production)

The application automatically detects which environment it's running on and uses the correct database.

---

## ✅ What's Fixed Now

### Navigation System
- Features, pages, and menu order changes made in admin dashboard on one environment will NOT automatically sync to the other
- Each environment maintains its own database independently

### Important: Before Final Deployment

You MUST ensure both databases have identical data before going live on cPanel:
1. All pages configured
2. Featured pages set
3. Menu order correct
4. All admin settings

---

## Solution: Database Synchronization Strategy

### **Option 1: Export/Import (Recommended for First Deployment)**

**Step 1: Export Localhost Database**
1. Use phpMyAdmin on localhost
2. Select `login-table` database
3. Click Export
4. Save as SQL file (e.g., `emporio-sport-export.sql`)

**Step 2: Import to cPanel Database**
1. Access cPanel → Databases → phpMyAdmin
2. Select `mahamusa_db`
3. Click Import
4. Upload the SQL file
5. Click Import

---

### **Option 2: Create Manual Sync Script (For Ongoing Updates)**

If you want to make changes on localhost and push them to cPanel, use this script:

```php
<?php
/**
 * Database Sync - Sync Pages Table from Localhost to cPanel
 * Only syncs the 'pages' table
 * Place on a secure admin-only page or protected endpoint
 */

// Only allow POST requests from admin
session_start();
if (empty($_SESSION['is_admin'])) {
    die('Access Denied');
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_POST['sync_action'])) {
    die('Invalid Request');
}

// Local database (localhost)
$local_conn = new mysqli('localhost', 'root', '', 'login-table');
if ($local_conn->connect_error) {
    die('Local DB Error: ' . $local_conn->connect_error);
}

// Remote database (cPanel)
$remote_conn = new mysqli(
    'maham.usadomainhosting.com',
    'mahamusa_user',
    'tCG!c&lpxW8Q',
    'mahamusa_db'
);
if ($remote_conn->connect_error) {
    die('Remote DB Error: ' . $remote_conn->connect_error);
}

// Get all data from local pages table
$result = $local_conn->query("SELECT * FROM pages");
$pages = [];
while ($row = $result->fetch_assoc()) {
    $pages[] = $row;
}

// Truncate remote pages table
$remote_conn->query("TRUNCATE TABLE pages");

// Insert all pages to remote
$inserted = 0;
foreach ($pages as $page) {
    $stmt = $remote_conn->prepare("
        INSERT INTO pages (id, title, slug, url, is_featured, menu_order, created_at, updated_at) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ");
    
    $stmt->bind_param(
        'isssiiiss',
        $page['id'],
        $page['title'],
        $page['slug'],
        $page['url'],
        $page['is_featured'],
        $page['menu_order'],
        $page['created_at'],
        $page['updated_at']
    );
    
    if ($stmt->execute()) {
        $inserted++;
    }
    $stmt->close();
}

$remote_conn->close();
$local_conn->close();

echo "✓ Synced $inserted pages to cPanel database";
?>
```

---

### **Option 3: Bidirectional Sync (For Active Development)**

If you need changes from cPanel to reflect on localhost:

1. **From Localhost to cPanel**: Use Option 2 script
2. **From cPanel to Localhost**: 
   - SSH into cPanel server
   - Export database
   - Download and import to localhost

---

## How the Application Chooses Database

The app automatically detects environment in `db_config.php`:

```php
$hostname = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? 'localhost';
$is_local = (strpos($hostname, 'localhost') !== false || strpos($hostname, '127.0.0.1') !== false);

if ($is_local) {
    // Use localhost database
    $DB_HOST = 'localhost';
    $DB_USER = 'root';
    $DB_PASS = '';
    $DB_NAME = 'login-table';
} else {
    // Use cPanel database
    $DB_HOST = 'maham.usadomainhosting.com';
    $DB_USER = 'mahamusa_user';
    $DB_PASS = 'tCG!c&lpxW8Q';
    $DB_NAME = 'mahamusa_db';
}
```

---

## ✅ Pre-Deployment Checklist

Before uploading to cPanel:

- [ ] Test all pages on localhost
- [ ] Configure all featured pages on localhost
- [ ] Set menu order correctly on localhost
- [ ] Export localhost database
- [ ] Import to cPanel database
- [ ] Verify cPanel site has all pages
- [ ] Test features on cPanel domain
- [ ] Verify admin dashboard works on cPanel
- [ ] Check that "MORE" dropdown displays correctly

---

## Deployment Steps

### 1. **Sync Database (Do First)**
```
Localhost (login-table) → Export → cPanel (mahamusa_db)
```

### 2. **Upload Files to cPanel**
Use FTP or File Manager to upload all PHP files, CSS, images, etc.

### 3. **Test cPanel Site**
- Visit your cPanel domain
- Click on all navigation links
- Test admin dashboard
- Verify database connection works

### 4. **No More Localhost Changes**
Once on cPanel, manage everything through cPanel admin dashboard.

---

## Important Notes

✅ **Files sync automatically** (FTP, Git, etc.)
❌ **Database does NOT sync automatically**

### For Future Development:
- **Best Practice**: Stop using localhost, use cPanel for all development
- **Alternative**: Create a sync script (Option 2) to push changes before deployment

### If You Continue Both Environments:
- Make changes on **ONE** environment only
- Use sync method to push to other environment
- Never make conflicting changes

---

## Quick Reference

| Environment | Database | Host | User |
|-------------|----------|------|------|
| Localhost | login-table | localhost | root (no password) |
| cPanel | mahamusa_db | maham.usadomainhosting.com | mahamusa_user |

---

## Support Commands

### Export Localhost Database (Command Line)
```bash
mysqldump -u root login-table > emporio-sport-backup.sql
```

### Import to cPanel (Command Line via SSH)
```bash
mysql -h maham.usadomainhosting.com -u mahamusa_user -p mahamusa_db < emporio-sport-backup.sql
```

---

**Recommendation**: For the smoothest deployment, keep development on ONE system. After going live on cPanel, manage everything from the cPanel admin dashboard only.
