# OTP Integration - Quick Troubleshooting Guide

## ❌ "Network error. Please try again."

### Causes & Solutions:

**1. Invalid SMTP Credentials**
- Open `.env` file
- Check `SMTP_USERNAME` and `SMTP_PASSWORD`
- For Gmail: Use app password (16 chars), not regular password
- For Gmail: Ensure 2-Factor Authentication is enabled

**2. SMTP Connection Failed**
```php
// Test SMTP in terminal:
php -r "
require 'includes/vendor/autoload.php';
\$mail = new PHPMailer\PHPMailer\PHPMailer(true);
\$mail->isSMTP();
\$mail->Host = 'smtp.gmail.com';
\$mail->SMTPAuth = true;
\$mail->Username = 'your-email@gmail.com';
\$mail->Password = 'your-app-password';
\$mail->SMTPSecure = 'tls';
\$mail->Port = 587;
try {
    \$mail->smtpConnect();
    echo 'SMTP connection successful!';
} catch (Exception \$e) {
    echo 'Error: ' . \$e->getMessage();
}
"
```

**3. Browser Console Error**
- Open DevTools (F12)
- Check Console tab
- Look for detailed error message
- Check Network tab for response details

**4. Firewall/Proxy Blocking**
- Port 587 needs to be open outbound
- Contact your ISP if port blocked
- Try port 465 (SMTP_SECURE: 'ssl') if 587 fails

## ⏱️ OTP Expired / Invalid

- OTP valid for 10 minutes only
- Time set on server - check system time is correct
- Database expires_at field in UTC timezone

## 📨 Email Not Received

Check in this order:
1. Spam/Junk folder (add noreply@powerzone.com to contacts)
2. Check database: `SELECT * FROM otp_verification WHERE email='test@example.com';`
3. Check PHP error logs: `/xampp/php/logs/php_error.log`
4. Check mail.log: Check your server's mail logs

## 🔄 OTP Not Verifying

**Issue: "Invalid OTP" after entering correct code**

Solutions:
1. Check code hasn't expired: expires_at > NOW()
2. Check code matches exactly: No spaces, exact match
3. Check verified flag: Should be FALSE before verification
4. Check attempts: attempts < max_attempts (5)
5. Check database email matches: Case-sensitive

**Test Query:**
```sql
SELECT email, otp, attempts, expires_at, verified, 
       NOW() as current_time,
       TIMESTAMPDIFF(SECOND, NOW(), expires_at) as seconds_left
FROM otp_verification 
ORDER BY created_at DESC LIMIT 1;
```

## 🧪 Testing Checklist

- [ ] Update .env with your SMTP details
- [ ] Test register form fills completely
- [ ] Click "Send OTP" button
- [ ] Check for API response in Network tab (F12)
- [ ] Verify email received (including spam folder)
- [ ] Enter OTP code
- [ ] Verify auto-submits when 6 digits entered
- [ ] Check redirect to member dashboard

## 📱 Real-Time Features

✅ **Working Features:**
- Auto-fills when 6 digits entered
- Numeric-only input (letters blocked)
- Smart paste (removes non-numeric from pasted content)
- Shows "Ready to verify" indicator
- Auto-submits verification
- 10-minute countdown timer
- Resend OTP button
- Back to register button

## 🔐 Security Check

- [ ] .env file created and not in git
- [ ] SMTP password is app password, not regular password
- [ ] .gitignore includes .env file
- [ ] OTP response doesn't include code in production
- [ ] HTTPS enabled for registration/OTP pages
- [ ] Database passwords secured
- [ ] Error logs not exposed publicly

## 📊 Database Check

```sql
-- View recent OTP records
SELECT id, email, otp, verified, attempts, 
       DATE_SUB(expires_at, INTERVAL 5 HOUR 30 MINUTE) as expires_ist,
       created_at
FROM otp_verification 
ORDER BY id DESC LIMIT 10;

-- Check for pending verifications
SELECT * FROM otp_verification 
WHERE verified = 0 
  AND expires_at > NOW()
ORDER BY created_at DESC;

-- Count by status
SELECT 
    verified,
    COUNT(*) as count,
    MAX(created_at) as latest
FROM otp_verification
GROUP BY verified;
```

## 🔧 Manual Reset (Testing Only)

```sql
-- Delete old/test OTP records
DELETE FROM otp_verification 
WHERE created_at < DATE_SUB(NOW(), INTERVAL 1 HOUR);

-- Reset specific email
DELETE FROM otp_verification WHERE email = 'test@example.com';
```

## 💡 Pro Tips

1. **Development:** OTP returned in response for testing
   - Remove before production deployment
   - Check OTP_INTEGRATION_GUIDE.md "Production Checklist"

2. **Email Testing:** Use Mailtrap or similar service
   - Replace SMTP credentials
   - Test without real email credentials

3. **Debugging:** Enable SMTP debug
   - Set `$this->mail->SMTPDebug = 3;` in mailer.php
   - Check detailed SMTP logs

4. **Logging:** Check error logs frequently
   - error_log() calls in otp.php
   - /xampp/php/logs/php_error.log

## 🆘 Still Having Issues?

1. Check OTP_INTEGRATION_GUIDE.md for complete documentation
2. Review error logs in browser console (F12)
3. Check PHP error logs in /xampp/php/logs/
4. Verify .env file has correct SMTP settings
5. Test SMTP connection manually (see above)
6. Check database connection works

---
Last Updated: 2026-01-28
Fitness App OTP System
