# Order Email Notifications

## Overview

When a customer places an order, two emails are automatically sent:

1. **Order Confirmation** - Sent to the customer
2. **New Order Alert** - Sent to the admin/store owner

## Implementation Details

### Files Created

1. **Mailable Classes:**

    - `app/Mail/OrderConfirmationMail.php` - Customer order confirmation
    - `app/Mail/NewOrderNotificationMail.php` - Admin new order notification

2. **Email Templates:**

    - `resources/views/mail/order-confirmation.blade.php` - Customer email template
    - `resources/views/mail/new-order-notification.blade.php` - Admin email template

3. **Service Update:**
    - `app/Services/OrderService.php` - Updated to send emails after order creation (lines 158-188)

### Email Flow

```
Order placed → Order saved → Order products saved → Stock reduced →
Commission calculated → Wallet updated → EMAILS SENT → Cart cleared
```

Both emails are sent within try-catch blocks to ensure that if email sending fails, the order process still completes successfully. Errors are logged to `storage/logs/laravel.log`.

---

## Configuration

### 1. Mail Configuration (.env)

The mail settings are already configured in your `.env`:

```env
MAIL_MAILER=smtp
MAIL_HOST=mail.amostore.in
MAIL_PORT=465
MAIL_USERNAME=info@amostore.in
MAIL_PASSWORD=h_r?}KOLZ.DSW%4h
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=info@amostore.in
MAIL_FROM_NAME="${APP_NAME}"
```

### 2. Admin Email Configuration

Admin emails can be configured in **two ways** (in order of priority):

#### Option A: Database Settings (Recommended)

Add an `admin_emails` setting in your settings table:

```sql
INSERT INTO settings (key, value) VALUES ('admin_emails', 'admin1@example.com,admin2@example.com');
```

Or via admin panel if you have a settings interface.

#### Option B: Environment Variable

Add to your `.env` file:

```env
ADMIN_EMAILS=admin@example.com,manager@example.com
```

Multiple emails can be comma-separated.

#### Option C: Fallback to Admin Users

If neither of the above is set, the system will automatically fetch all users with:

-   Role named `admin`, OR
-   `user_type` = `admin`

### 3. Site Name Configuration

The email subject and content use the site name from settings:

```env
APP_NAME="Your Store Name"
```

Or set in database settings as `site_name`.

---

## Email Templates

### Customer Order Confirmation

**Template:** `resources/views/mail/order-confirmation.blade.php`

**Includes:**

-   Order ID and date
-   Payment method and status
-   Order status
-   Itemized list of products with quantities and prices
-   Subtotal, shipping, discounts, and total
-   Shipping address
-   Store branding

**Personalization:**

-   Customer's first name
-   Order number
-   Currency symbol from settings

### Admin New Order Notification

**Template:** `resources/views/mail/new-order-notification.blade.php`

**Includes:**

-   Order ID and timestamp
-   Customer name and email
-   Payment details
-   Order status
-   Complete itemized order
-   Shipping address
-   Direct link to admin panel

**Purpose:** Immediate notification for store admins to process new orders.

---

## Testing

### Manual Testing

1. Place a test order through the frontend
2. Check the customer's email inbox
3. Check the admin email inbox(es)

### Check Logs

If emails fail to send, check the logs:

```bash
tail -f storage/logs/laravel.log
```

Look for:

-   `Order confirmation email failed: ...`
-   `Admin notification email failed: ...`

### Queue Configuration (Optional)

By default, emails are sent synchronously. For better performance, you can queue them:

1. Update the Mailable classes to implement `ShouldQueue`:

    ```php
    use Illuminate\Contracts\Queue\ShouldQueue;
    class OrderConfirmationMail extends Mailable implements ShouldQueue
    ```

2. Run queue worker:
    ```bash
    php artisan queue:work
    ```

---

## Customization

### Modify Email Content

Edit the Blade templates in `resources/views/mail/`:

-   `order-confirmation.blade.php` - Customer email
-   `new-order-notification.blade.php` - Admin email

Both templates use inline CSS for maximum email client compatibility.

### Add CC/BCC

To add CC or BCC recipients, modify the Mailable classes:

```php
public function envelope(): Envelope
{
    return new Envelope(
        subject: '...',
        cc: ['cc@example.com'],
        bcc: ['bcc@example.com']
    );
}
```

### Add Attachments

To attach invoices or other documents:

```php
public function attachments(): array
{
    return [
        Attachment::fromPath('/path/to/invoice.pdf')
            ->as('invoice.pdf')
            ->withMime('application/pdf'),
    ];
}
```

---

## Troubleshooting

### Emails Not Sending

1. Check mail configuration in `.env`
2. Verify SMTP credentials are correct
3. Check firewall/port access (465 for SSL)
4. Review Laravel logs for errors

### Admin Not Receiving Emails

1. Verify `admin_emails` setting is configured
2. Check spam folder
3. Verify admin user records exist with proper role/user_type

### Customer Not Receiving Emails

1. Check customer email is valid
2. Verify mail server isn't blocking outgoing emails
3. Check spam/junk folder

---

## Security Notes

-   Email addresses are sanitized before sending
-   Errors are logged but not exposed to users
-   Admin email list is cached via config system
-   No sensitive order data is exposed in email headers

---

## Support

For issues or questions, refer to:

-   Laravel Mail Documentation: https://laravel.com/docs/mail
-   Project logs: `storage/logs/laravel.log`
