# 🔧 Troubleshooting Guide - Bait Alamer Email System

## Issues Reported

### 1. ❌ BASE GRAND TOTAL Not Showing for Pricing Manager
### 2. ❌ No Email Sent by Both Users (Pricing Manager & Sales)

---

## 🔍 Diagnostic Steps

### Step 1: Open Browser Developer Console

**How to Open Console:**
- **Chrome/Edge**: Press `F12` or `Ctrl+Shift+I`
- **Firefox**: Press `F12` or `Ctrl+Shift+K`
- Click on "Console" tab

**What to Look For:**
- 🟢 Green messages starting with ✅
- 🔴 Red error messages
- 🟡 Yellow warning messages

### Step 2: Check User Role

1. Open the calculator page
2. Look in console for:
   ```
   👤 User Role: pricing_manager  (or sales_consultant)
   🔒 Pricing Manager: true  (or false)
   ```

3. If role is incorrect:
   - Logout
   - Login again with correct credentials
   - Clear browser cache (Ctrl+Shift+Delete)

### Step 3: Test BASE GRAND TOTAL

**For Pricing Managers:**

1. Login as pricing manager (e.g., `manager` / `manager123`)
2. Select any item (checkbox)
3. Enter dimensions/quantities
4. Click **"📊 Calculate Total"**
5. Look in browser console for:
   ```
   🔍 Checking BASE GRAND TOTAL display:
   isPricingManager: true
   baseGrandTotal: [some number]
   grandTotal: [some number]
   ✅ Pricing Manager - Showing BASE GRAND TOTAL
   ✅ BASE GRAND TOTAL element created
   ```

6. On the page, you should see TWO lines:
   - **GRAND TOTAL:** 624,000 IQD (orange background)
   - **BASE GRAND TOTAL:** 500,000 IQD (darker orange background, below GRAND TOTAL)

**If BASE GRAND TOTAL doesn't appear:**

A. Check console errors
B. Try hard refresh: `Ctrl+F5` or `Ctrl+Shift+R`
C. Clear browser cache
D. Check if `IS_PRICING_MANAGER` is `true` in console

### Step 4: Test Email Sending

#### Quick Test Method:

1. Open: `http://your-domain/Bait-alamer/customer/debug_test.php`
2. Click **"📧 Test Email Send"**
3. Watch the console output (black box on page)
4. Look for:
   ```
   Sending POST request to send_order_email.php...
   Response Status: 200 OK
   ✅ Email sent successfully!
   ```

#### Full Test Method:

1. Login to calculator (as any role)
2. Fill in:
   - Customer Name: "Test Customer"
   - Site Location: "Test Site"
3. Select 1-2 items
4. Enter quantities
5. Click **"📊 Calculate Total"**
6. Open Browser Console (F12)
7. Click **"🖨️ Print / Export PDF"**

**Watch Console For:**
```
📧 Starting email send process...
User Role: pricing_manager (or sales_consultant)
📋 Order Number: 20251211-143045-782
📦 Order Data: {...}
📊 Items count: 2
💰 Selling Grand Total: 624000
💰 Base Grand Total: 500000
🌐 Sending POST request to send_order_email.php...
📡 Response status: 200 OK
📨 Server Response: {...}
✅ Order email sent successfully!
📧 Order Number: 20251211-143045-782
📬 Email sent: true
```

**If Email Fails:**

Look for error messages:
- ❌ HTTP Error (403, 404, 500)
- ❌ Error sending order
- ⚠️ Email sending failed

---

## 🛠️ Common Issues & Fixes

### Issue: BASE GRAND TOTAL Not Showing

**Possible Causes:**

1. **Not a Pricing Manager**
   - Solution: Login with manager credentials
   - Check console: `IS_PRICING_MANAGER` should be `true`

2. **Cache Issue**
   - Solution: Hard refresh `Ctrl+F5`
   - Clear browser cache
   - Try different browser

3. **JavaScript Not Loading**
   - Check console for errors
   - Make sure `calculator_customer.js` is loaded
   - Check Network tab in DevTools

4. **Element Not Created**
   - Check console for: "✅ BASE GRAND TOTAL element created"
   - If missing, check for JavaScript errors

**Manual Fix:**
Open browser console and run:
```javascript
console.log('IS_PRICING_MANAGER:', IS_PRICING_MANAGER);
console.log('state.baseGrandTotal:', state.baseGrandTotal);
```

### Issue: Email Not Sending

**Possible Causes:**

1. **PHP mail() Not Configured**
   - Run: `http://your-domain/Bait-alamer/customer/test_email.php`
   - Check if test email arrives
   - If not, configure PHP mail in `php.ini`

2. **File Permissions**
   - Check `send_order_email.php` exists
   - Check `orders.log` is writable
   ```bash
   ls -la send_order_email.php
   chmod 644 send_order_email.php
   chmod 666 orders.log
   ```

3. **Session Not Active**
   - Make sure you're logged in
   - Check if session expired

4. **AJAX Request Blocked**
   - Check browser console for CORS errors
   - Check Network tab in DevTools
   - Look for failed POST request to `send_order_email.php`

5. **Server Error**
   - Check PHP error logs
   - Check server error logs (Apache/Nginx)
   - Look in: `/var/log/apache2/error.log` or similar

**Test Email Configuration:**

Open terminal/SSH and run:
```php
<?php
$to = 'm.oday@pazogrp.com';
$subject = 'Test Email';
$message = 'This is a test';
$headers = 'From: noreply@baitalamer.com';
$result = mail($to, $subject, $message, $headers);
echo $result ? 'Email sent' : 'Email failed';
?>
```

### Issue: Orders.log Shows "Email: Failed"

Check file: `customer/orders.log`

If you see:
```
2025-12-11 14:30:45 | Order #... | Email: Failed
```

**Solutions:**

1. **Check PHP mail() function**
   ```php
   php -r "echo function_exists('mail') ? 'OK' : 'NOT AVAILABLE';"
   ```

2. **Check SMTP settings in php.ini**
   ```ini
   [mail function]
   SMTP = smtp.yourserver.com
   smtp_port = 25
   sendmail_from = noreply@baitalamer.com
   ```

3. **Install PHPMailer (Production)**
   ```bash
   composer require phpmailer/phpmailer
   ```

---

## 📧 Email Delivery Issues

### Email Not Arriving in Inbox

**Check:**

1. **Spam/Junk Folder**
   - Check m.oday@pazogrp.com spam folder
   - Add noreply@baitalamer.com to whitelist

2. **Email Server Logs**
   - Check mail server logs
   - Look for bounces or rejections

3. **Email Address Correct**
   - Verify: `m.oday@pazogrp.com` (no typos)
   - Check in `send_order_email.php` line 67

4. **Email Service Blocking**
   - Some email providers block PHP mail()
   - Solution: Use SMTP or PHPMailer

### Email Arrives But No Attachment

**Check:**

1. **HTML File Generated**
   - Look in console for successful generation
   - Check temp directory

2. **MIME Boundaries**
   - Check email source
   - Verify boundary markers

3. **File Size Limits**
   - Check if HTML is too large
   - Check email server limits

---

## 🧪 Debug Tools

### Tool 1: test_email.php
**Location:** `customer/test_email.php`

**What it does:**
- Tests if mail() function works
- Sends simple test email
- Sends HTML attachment test
- Checks file permissions

**How to use:**
1. Open in browser: `http://your-domain/Bait-alamer/customer/test_email.php`
2. Check results on page
3. Check m.oday@pazogrp.com inbox

### Tool 2: debug_test.php
**Location:** `customer/debug_test.php`

**What it does:**
- Shows current user & role
- Tests JavaScript variables
- Tests email send with mock data
- Shows real-time console output

**How to use:**
1. Login first
2. Open: `http://your-domain/Bait-alamer/customer/debug_test.php`
3. Click buttons to test
4. Watch console output

### Tool 3: Browser Console
**How to use:**
1. Press F12
2. Go to Console tab
3. Create order and click Print
4. Watch for detailed logs

**Look for these messages:**
- ✅ Green checkmarks = Success
- ❌ Red X = Error
- ⚠️ Yellow warning = Warning
- 📧 📊 💰 = Status updates

---

## 📋 Checklist Before Going Live

- [ ] Test as pricing manager - BASE GRAND TOTAL shows
- [ ] Test as sales consultant - BASE GRAND TOTAL hidden
- [ ] Test email from pricing manager
- [ ] Test email from sales consultant
- [ ] Verify email arrives at m.oday@pazogrp.com
- [ ] Verify HTML attachment opens correctly
- [ ] Check orders.log for "Email: Sent"
- [ ] Test customer PDF (no base prices shown)
- [ ] Test print functionality
- [ ] Clear all console errors
- [ ] Test on different browsers (Chrome, Firefox, Edge)
- [ ] Test on mobile devices
- [ ] Update all passwords from test passwords
- [ ] Configure production SMTP (if needed)
- [ ] Set up email monitoring/alerts

---

## 🆘 Still Having Issues?

### Collect This Information:

1. **From Browser Console:**
   - Copy all red error messages
   - Copy output from clicking Print/Export
   - Take screenshot

2. **From Server:**
   - PHP error log: `/var/log/php_errors.log`
   - Apache/Nginx error log
   - Last 10 lines from `customer/orders.log`

3. **Configuration:**
   - PHP version: `php -v`
   - Check if mail works: `php -r "mail('test@test.com','test','test');"`
   - Check `send_order_email.php` exists and is readable

4. **Test Results:**
   - Run `test_email.php` - what happened?
   - Run `debug_test.php` - what was in console?
   - What role are you logged in as?

### Contact Information:
Provide all above information when asking for help.

---

## ✅ Quick Fix Commands

**Clear Browser Cache:**
- Chrome: `Ctrl+Shift+Delete` → Check "Cached images and files" → Clear
- Firefox: `Ctrl+Shift+Delete` → Check "Cache" → Clear
- Edge: `Ctrl+Shift+Delete` → Check "Cached data and files" → Clear

**Hard Refresh:**
- Windows: `Ctrl+F5` or `Ctrl+Shift+R`
- Mac: `Cmd+Shift+R`

**View PHP Errors:**
```bash
tail -f /var/log/apache2/error.log
```

**Test Email from Command Line:**
```bash
echo "Test email" | mail -s "Test Subject" m.oday@pazogrp.com
```

**Check File Permissions:**
```bash
ls -la customer/send_order_email.php
ls -la customer/orders.log
```

**Make Files Writable:**
```bash
chmod 666 customer/orders.log
chmod 644 customer/send_order_email.php
```

---

**Last Updated:** December 11, 2025
**Version:** 2.0 - Debug Edition

