# 🍞 Toasty — Email & OAuth Configuration

## Overview

This document details the implementation of:
1. **2FA Email Delivery** — Sends 6-digit verification codes via SMTP
2. **Shopify OAuth** — Exchanges authorization codes for access tokens

---

## 1. 2FA Email Delivery

### Services

**`app/Services/MailService.php`** — Email sending with PHPMailer

```php
use App\Services\MailService;

$mailService = new MailService();
$mailService->send2FACode('user@example.com', '123456');
```

Methods:
- `send()` — Send any email
- `send2FACode()` — Send 2FA verification code
- `sendPasswordReset()` — Send password reset link
- `sendWelcome()` — Send welcome email

### Configuration

Update `config/.env`:

```env
# MAIL =====
MAIL_FROM=noreply@toasty.hypp.dev
MAIL_HOST=smtp.mailtrap.io          # or your SMTP provider
MAIL_PORT=2525
MAIL_USERNAME=your_mailtrap_username
MAIL_PASSWORD=your_mailtrap_password
```

### Test with Mailtrap

1. Sign up at https://mailtrap.io
2. Create a new inbox
3. Copy credentials to `config/.env`
4. Test: `php cli/test-mail.php`

### Implementation

Files updated:
- ✅ `src/auth/loginScript.php` — Sends code after login
- ✅ `src/auth/resendCode.php` — Resends code if needed
- ✅ `src/auth/verifyCode.php` — Unchanged (validates code)

Flow:
```
User enters email + password
    ↓
loginScript.php generates 6-digit code
    ↓
MailService.send2FACode() sends via SMTP
    ↓
User enters code
    ↓
verifyCode.php validates & creates session
```

---

## 2. Shopify OAuth Implementation

### Service

**`app/Services/ShopifyOAuthService.php`** — OAuth flow management

```php
use App\Services\ShopifyOAuthService;

$oauth = new ShopifyOAuthService();

// 1. Generate authorize URL
$url = $oauth->getAuthorizeUrl($shop, $redirectUri, $scopes);

// 2. Exchange code for token
$tokenData = $oauth->exchangeCodeForToken($shop, $code, $state);

// 3. Make API calls
$result = $oauth->makeRequest($shop, $accessToken, 'GET', 'graphql.json', $body);

// 4. Verify webhooks
if ($oauth->verifyWebhookHmac($data, $hmac)) { ... }
```

### Configuration

Update `config/.env`:

```env
# SHOPIFY =====
SHOPIFY_API_KEY=your_api_key_from_partners
SHOPIFY_API_SECRET=your_api_secret_from_partners
SHOPIFY_API_VERSION=2024-01
SHOPIFY_SCOPES=write_products,read_customers,write_orders
```

### Flow

```
1. Merchant clicks "Add to Shopify"
   ↓
2. /shopify/install redirects to Shopify OAuth
   ↓
3. Merchant approves app
   ↓
4. Shopify redirects to /shopify/callback
   ↓
5. callback.php exchanges code for access token
   ↓
6. Fetches shop info via GraphQL
   ↓
7. Saves shop & token to database
   ↓
8. Redirects to /app
```

### Database

Tables created:
- `shops` — Stores shop domain, access token, plan
- `admin_shop` — Links admins to shops
- `campaigns` — Notifications campaigns
- `subscribers` — Customer subscribers
- `notifications` — Sent notifications
- `logs` — Event logs

### Files Updated

- ✅ `src/auth/shopify/install.php` — Initiates OAuth
- ✅ `src/auth/shopify/callback.php` — Handles callback & token exchange
- ✅ `src/auth/shopify/webhooks.php` — Verifies HMAC (ready for webhooks)

---

## Database Setup

### Run Migrations

```bash
cd /Applications/MAMP/htdocs/toasty
php migrate.php
```

Or manually:

```bash
mysql -h localhost -u yihu7512_juli3n -p yihu7512_toasty < database/migrations/001_initial_schema.sql
```

Password: `N$=#TFDG1FV.`

### Seed Admin User (Optional)

```php
<?php
require_once 'vendor/autoload.php';
require_once 'app/Helpers/env.php';
require_once 'app/Helpers/db.php';

$db = get_db();

$email = 'admin@toasty.local';
$password = password_hash('YourSecurePassword123', PASSWORD_BCRYPT);
$name = 'Admin User';

$stmt = $db->prepare('INSERT INTO admins (email, name, password_hash) VALUES (?, ?, ?)');
$stmt->execute([$email, $name, $password]);

echo "✅ Admin created: {$email}\n";
?>
```

---

## Testing Locally

### Prerequisites

1. Start MAMP (Apache + PHP 8.1+ + MySQL)
2. Configure localhost DNS (update `/etc/hosts` if needed)
3. Verify database connection

### Test Email

```bash
php -r "
require 'vendor/autoload.php';
require 'app/Helpers/env.php';

\$mail = new App\Services\MailService();
\$result = \$mail->send2FACode('your-email@example.com', '123456');
echo \$result ? '✅ Email sent' : '❌ Email failed';
"
```

### Test OAuth

For local Shopify OAuth testing:

1. Create a custom Shopify app in Partners
2. Set redirect URI to `http://localhost:8888/toasty/shopify/callback`
3. Update `config/.env` with API key/secret
4. Visit `http://localhost:8888/toasty/shopify/install?shop=myshop.myshopify.com`

---

## Security Considerations

### Email

- ✅ Codes expire after 10 minutes
- ✅ One-use codes (deleted after verification)
- ⚠️ Use TLS/SSL for SMTP connections
- ⚠️ Store mail credentials in environment variables only

### OAuth

- ✅ CSRF protection via state parameter
- ✅ HMAC verification for webhooks
- ✅ Access tokens stored securely
- ⚠️ Never commit API keys to Git
- ⚠️ Use HTTPS in production

### Database

- ✅ Prepared statements (PDO)
- ✅ Foreign key constraints
- ✅ Automatic timestamps
- ✅ Indexing on frequently queried columns

---

## Troubleshooting

### Email Not Sending

```
Error: Connection timeout
Solution: Check SMTP credentials in config/.env
          Verify MAIL_HOST and MAIL_PORT are correct
          Test connection: telnet smtp.mailtrap.io 2525
```

### OAuth State Mismatch

```
Error: Invalid OAuth state
Solution: Sessions not persisting
          Check PHP session_start() is called
          Verify cookies enabled in browser
          Check config/init.php line 5
```

### Database Connection Error

```
Error: SQLSTATE[HY000] [2002] No such file or directory
Solution: MySQL not running
          Start MAMP via Applications → MAMP → Start Servers
          Or: sudo /usr/local/mysql/support-files/mysql.server start
          Check credentials in config/.env
```

---

## Next Steps

1. ✅ Email 2FA implemented
2. ✅ OAuth flow implemented
3. ⏳ Test locally with MAMP running
4. ⏳ Implement webhook handlers (shopify/webhooks.php)
5. ⏳ Create React dashboard (admin & app)
6. ⏳ Add campaign management API endpoints

---

## Files Changed

```
Created:
  - app/Services/MailService.php
  - app/Services/ShopifyOAuthService.php
  - database/migrations/001_initial_schema.sql
  - migrate.php

Updated:
  - src/auth/loginScript.php (+ email sending)
  - src/auth/resendCode.php (+ email sending)
  - src/auth/shopify/install.php (+ OAuth service)
  - src/auth/shopify/callback.php (+ token exchange)
  - config/database.php (path fix)
  - composer.json (added phpmailer/phpmailer)

Composer Dependencies Added:
  - phpmailer/phpmailer v7.1.1 ✅
```

---

## References

- [PHPMailer Docs](https://github.com/PHPMailer/PHPMailer)
- [Shopify OAuth](https://shopify.dev/docs/api/admin-rest/2024-01/resources/oauth)
- [Shopify API Reference](https://shopify.dev/docs/api/admin-graphql)
- [SMTP Testing with Mailtrap](https://mailtrap.io/blog/php-mail-function/)
