# Remote Database Sync - Quick Reference

## ⚡ 30-Second Setup

1. **Edit `.env`:**
```bash
REMOTE_DB_HOST=your-remote-server-ip
REMOTE_DB_PORT=3306
REMOTE_DB_DATABASE=adms
REMOTE_DB_USERNAME=remote_user
REMOTE_DB_PASSWORD=password
```

2. **Create remote table:**
```bash
php artisan migrate --database=remote_mysql
```

3. **Test connection:**
```bash
php artisan timesync:test --stats
```

✅ **Done!** Time logs now auto-sync to remote database

---

## 📊 What Happens When Device Sends Data

```
Device POST → /iclock/cdata
                  ↓
         receiveRecords() method
                  ↓
         TimeSyncHelper::insertTimeLog()
                  ↓
      ┌──────────┴──────────┐
      ↓                     ↓
Local DB              Remote DB
finger_log            finger_log
(INSERT OK)           (INSERT OK)
      └──────────┬──────────┘
                  ↓
         Response "OK" to device
```

---

## 🔧 Key Files Modified

| File | Change |
|------|--------|
| `config/database.php` | Added `remote_mysql` connection config |
| `app/Helpers/TimeSyncHelper.php` | ✨ **NEW** - Handles dual insertion |
| `app/Http/Controllers/iclockController.php` | Updated to use TimeSyncHelper |
| `.env.example` | Added REMOTE_DB_* variables |
| `app/Console/Commands/TestRemoteDatabase.php` | ✨ **NEW** - Test & monitor command |
| `database/migrations/2026_06_02_create_remote_finger_log.php` | ✨ **NEW** - Create remote table |

---

## 📝 Useful Commands

```bash
# Test remote connection
php artisan timesync:test

# View sync statistics
php artisan timesync:test --stats

# Create remote table
php artisan migrate --database=remote_mysql

# View error logs
tail -f storage/logs/iclock-$(date +%Y-%m-%d).log

# Check remote table has data
mysql -h 123.45.67.89 -u remote_user -p adms
  → SELECT COUNT(*) FROM finger_log;
```

---

## ⚙️ How the System Works

### 1. Detect Time Log Data
When device sends data, `receiveRecords()` method is called with:
- `SN` - Device serial number
- `table` - Data type (e.g., "ATTLOG")
- Raw content with actual records

### 2. Local Insertion
```php
DB::table('finger_log')->insert($data);
// ✅ Your primary system
```

### 3. Remote Check
```php
if (TimeSyncHelper::isRemoteDatabaseConfigured()) {
    // Remote DB is enabled
}
```

### 4. Remote Insertion
```php
DB::connection('remote_mysql')->table('finger_log')->insert($data);
// ✅ Auto-synced to remote server
```

### 5. Logging
Both successes and failures are logged to `storage/logs/iclock-YYYY-MM-DD.log`

---

## 🚨 Error Scenarios

| Scenario | Local Insert | Remote Insert | Result |
|----------|--------------|---------------|--------|
| ✅ Both OK | SUCCESS | SUCCESS | Data in both DBs |
| ⚠️ Remote down | SUCCESS | FAILED | Data in local, logged error |
| ❌ Local down | FAILED | SKIPPED | System error, no insert |

**Key Point:** Local database is always the priority. Remote failures are logged but don't break your system.

---

## 🔍 Monitoring

### Check Logs
```bash
# All sync activity
grep "insertion\|insertion result" storage/logs/iclock-*.log

# Errors only
grep "❌\|error\|Error\|ERROR" storage/logs/iclock-*.log
```

### Get Statistics
```bash
php artisan timesync:test --stats

# Output:
# Local finger_log records: 45,230
# Remote finger_log records: 45,215
# Sync percentage: 99.97%
```

### Monitor Real-Time
```bash
# Watch logs as devices send data
tail -f storage/logs/iclock-$(date +%Y-%m-%d).log | grep -i "insertion"
```

---

## 🛑 Disable Remote Sync

To temporarily disable without code changes:

```bash
# In .env, comment out or set to localhost:
REMOTE_DB_HOST=127.0.0.1

# System will detect and skip remote sync automatically
```

---

## 📚 Full Documentation

See `REMOTE_DATABASE_SETUP.md` for complete details:
- Architecture explanation
- Step-by-step setup
- Troubleshooting guide
- Performance considerations
- Security best practices

---

## 💡 Common Questions

**Q: Will slow remote database affect local system?**
A: No. Local insert completes first. Remote sync is separate. If remote is slow, local is unaffected.

**Q: What if remote database becomes unavailable?**
A: System logs the error and continues. Local database keeps working perfectly. No data is lost.

**Q: How do I verify sync is working?**
A: Run `php artisan timesync:test --stats` - shows record counts in both databases.

**Q: Can I use this with multiple remote databases?**
A: Current implementation supports one remote database. Contact support for multi-database sync.

---

## 🚀 Next Steps

1. ✅ Files are created and configured
2. ⏭️ Update `.env` with remote database credentials
3. ⏭️ Run migration: `php artisan migrate --database=remote_mysql`
4. ⏭️ Test: `php artisan timesync:test --stats`
5. ⏭️ Monitor logs: `tail -f storage/logs/iclock-*.log`

---

**Version:** 1.0 | **Date:** 2026-06-02 | **Status:** Production Ready ✅
