# Bait Alamer Email System - Implementation Guide

## 📋 Overview

This system implements a two-role pricing calculator with automatic internal cost email notifications for **BOTH** sales consultants and pricing managers.

---

## 🎯 Key Features

### 1. **Two User Roles**

#### **Sales Consultant** (`sales_consultant`)
- **Can View**: Selling prices only (read-only)
- **Cannot View**: Base prices, base grand total, profit margins
- **UI Behavior**: 
  - Selling prices are displayed but not editable
  - Only sees GRAND TOTAL in summary
  - No BASE GRAND TOTAL line visible
- **Email**: Sends internal cost PDF to m.oday@pazogrp.com (but doesn't see it)

#### **Pricing Manager** (`pricing_manager`)
- **Can View**: Base prices (as labels), BASE GRAND TOTAL in summary
- **Can Edit**: Selling prices
- **UI Behavior**:
  - Selling prices are editable inputs
  - Sees GRAND TOTAL (selling)
  - Sees BASE GRAND TOTAL (base) - additional line
  - Has "Save Prices" button to persist changes
- **Email**: Sends internal cost PDF to m.oday@pazogrp.com

---

## 🔄 System Flow

### When ANY User Clicks "Print / Export PDF":

1. **Validation**: System validates all required fields
2. **Calculate Totals**: 
   - Selling Grand Total (visible to all)
   - Base Grand Total (calculated for all, visible only to managers)
3. **Send Email**: 
   - Generates Internal Cost PDF with base prices
   - Emails to: `m.oday@pazogrp.com`
   - Contains: base prices, selling prices, profit analysis
4. **Show Print Dialog**:
   - Customer Invoice PDF appears on screen
   - Safe for customer (no base prices)
   - User can print or save as PDF

---

## 📊 Price Structure

### Two Types of Prices:

1. **Base Unit Price** (Your company's cost)
   - Stored in: `../base_prices.json` (single source of truth)
   - Used by: Both internal calculator and customer calculator
   - Editable: No (only via file update)
   - Visibility: Only pricing managers see it (as label reference)

2. **Selling Unit Price** (Partner's price to end customer)
   - Stored in: `customer/selling_prices.json`
   - Used by: Customer calculator only
   - Editable: Yes (by pricing managers only)
   - Visibility: Both roles see it

---

## 📧 Email Details

### Recipient
**Email Address**: `m.oday@pazogrp.com`

### Email Subject
```
Bait Alamer Order #YYYYMMDD-HHMMSS-RRR – Internal Summary
```

### Email Body
```
Order Details:
━━━━━━━━━━━━━━━━━━━━━━━━
Order #: 20251211-143045-782
Date: 11/12/2025, 14:30
Customer: Al-Noor Construction
Site: Baghdad - Al-Mansour
Prepared By: zaidoun (sales_consultant)

Financial Summary:
━━━━━━━━━━━━━━━━━━━━━━━━
Customer Grand Total: 5,400,000 IQD
Base Grand Total: 4,440,000 IQD
Total Profit: 960,000 IQD
Profit Margin: 17.78%

See attached HTML file for detailed breakdown.
You can open it in any browser and print/save as PDF.
```

### Email Attachment
**File**: `internal_cost_ORDERNUM.html`

**Content**: 
- Header with warning: "⚠️ INTERNAL COPY – NOT FOR CUSTOMER ⚠️"
- Order information
- Table with columns:
  - Item
  - Unit
  - Adj. Qty
  - **Selling Price** (green)
  - **Selling Total** (green)
  - **Base Price** (orange)
  - **Base Total** (orange)
  - **Item Profit** (blue)
- Financial Summary:
  - Customer Grand Total
  - Base Grand Total
  - Total Profit
  - Profit Margin %

---

## 💻 Technical Implementation

### Files Modified/Created:

1. **`customer/send_order_email.php`** ✅ NEW
   - Handles order data reception
   - Generates internal cost HTML/PDF
   - Sends email with attachment
   - Logs all orders to `orders.log`

2. **`customer/calculator_customer.js`** ✅ UPDATED
   - Added base calculation logic (always runs in background)
   - Updated `calculateTotals()` to compute base grand total
   - Updated `printCalculator()` to send data to server
   - Added `sendOrderToServer()` async function
   - Shows BASE GRAND TOTAL for pricing managers only

3. **`customer/customer.php`** ✅ ALREADY UPDATED
   - Loads base prices from shared source
   - Loads selling prices from JSON
   - Injects price data and role into JavaScript

4. **`customer/users.php`** ✅ UPDATED
   - Added user: `zaidoun` (sales_consultant)
   - Existing users maintained

5. **`customer/print-styles.css`** ✅ UPDATED
   - Hides BASE GRAND TOTAL from customer PDF
   - Ensures clean customer-facing print output

---

## 🔐 Security Features

### Sales Consultants:
- ❌ Cannot see base prices in UI
- ❌ Cannot see BASE GRAND TOTAL in summary
- ❌ Cannot edit selling prices
- ✅ Internal PDF email sent (but they never see it)

### Pricing Managers:
- ✅ Can see base prices (as non-editable labels)
- ✅ Can see BASE GRAND TOTAL in summary
- ✅ Can edit selling prices
- ✅ Internal PDF email sent

### Customer PDF (Printed):
- ❌ Never shows base prices
- ❌ Never shows BASE GRAND TOTAL
- ❌ Never shows profit margins
- ✅ Only shows selling prices and totals

---

## 👥 User Credentials

### Pricing Managers:
```
Username: manager
Password: manager123
Role: pricing_manager

Username: admin
Password: admin2025
Role: pricing_manager
```

### Sales Consultants:
```
Username: sales
Password: sales123
Role: sales_consultant

Username: zaidoun
Password: sales123
Role: sales_consultant
```

---

## 📝 Order Logging

All orders are logged to: `customer/orders.log`

**Format**:
```
2025-12-11 14:30:45 | Order #20251211-143045-782 | zaidoun (sales_consultant) | Customer: Al-Noor Construction | Total: 5400000 IQD | Profit: 960000 IQD | Email: Sent
```

---

## 🧪 Testing Checklist

### Test as Sales Consultant (zaidoun):
- [ ] Login with: `zaidoun` / `sales123`
- [ ] Verify selling prices are read-only (grayed out)
- [ ] Verify NO base prices visible
- [ ] Verify NO BASE GRAND TOTAL line visible
- [ ] Select items, enter quantities
- [ ] Click "Calculate Total"
- [ ] Verify only GRAND TOTAL shows
- [ ] Click "Print / Export PDF"
- [ ] Verify customer PDF appears on screen (no base prices)
- [ ] Check email: m.oday@pazogrp.com
- [ ] Verify internal PDF received with base prices

### Test as Pricing Manager (manager):
- [ ] Login with: `manager` / `manager123`
- [ ] Verify selling prices are editable (orange border)
- [ ] Verify base prices visible as labels
- [ ] Verify "Save Prices" button visible
- [ ] Select items, enter quantities
- [ ] Edit some selling prices
- [ ] Click "Save Prices"
- [ ] Click "Calculate Total"
- [ ] Verify GRAND TOTAL shows
- [ ] Verify BASE GRAND TOTAL shows (second line)
- [ ] Click "Print / Export PDF"
- [ ] Verify customer PDF appears on screen (no base prices)
- [ ] Check email: m.oday@pazogrp.com
- [ ] Verify internal PDF received with base prices

---

## 🚀 Deployment Notes

### Email Configuration:
The system uses PHP's native `mail()` function. For production use:

1. **Configure PHP mail settings** in `php.ini`:
   ```ini
   [mail function]
   SMTP = smtp.yourserver.com
   smtp_port = 25
   sendmail_from = noreply@baitalamer.com
   ```

2. **Or use PHPMailer** (recommended for production):
   - Install: `composer require phpmailer/phpmailer`
   - Update `send_order_email.php` to use PHPMailer
   - Configure SMTP credentials

3. **Test email delivery**:
   ```php
   mail('m.oday@pazogrp.com', 'Test', 'Email system working!');
   ```

### File Permissions:
```bash
chmod 644 customer/selling_prices.json
chmod 644 customer/orders.log
chmod 755 customer/send_order_email.php
```

---

## 🔧 Configuration

### Change Email Recipient:
Edit `customer/send_order_email.php`:
```php
$to = 'm.oday@pazogrp.com'; // Line 67
```

### Add More Users:
Edit `customer/users.php` and add to the `$users` array.

### Update Base Prices:
Edit `../base_prices.json` - affects both internal and customer calculators.

### Update Selling Prices:
Use the "Save Prices" button as pricing manager, or manually edit `customer/selling_prices.json`.

---

## 📞 Support

For questions or issues:
- Check `customer/orders.log` for email status
- Check browser console for JavaScript errors
- Check PHP error logs for server-side issues

---

**Last Updated**: December 11, 2025
**Version**: 2.0 - Email System Implementation

