# ✅ Email 2FA & OAuth Shopify — Implementation Complete

## What's Done

### 🔐 Email 2FA System
Your login flow now sends actual 2FA codes via email:

```
User logs in
  ↓
6-digit code generated
  ↓
Email sent via SMTP (Mailtrap)
  ↓
User enters code
  ↓
Session created ✅
```

**Files:**
- `app/Services/MailService.php` — Email service with PHPMailer
- `src/auth/loginScript.php` — Updated with email sending
- `src/auth/resendCode.php` — Resend code endpoint

### 🛍️ Shopify OAuth System
Your app now integrates with Shopify stores:

```
Merchant clicks "Add to Shopify"
  ↓
/shopify/install redirects to Shopify OAuth
  ↓
Merchant approves permissions
  ↓
Shopify redirects to /shopify/callback
  ↓
Access token exchanged & stored
  ↓
Shop info fetched via GraphQL
  ↓
Shop saved to database ✅
```

**Files:**
- `app/Services/ShopifyOAuthService.php` — OAuth flow & API calls
- `src/auth/shopify/install.php` — OAuth initiation
- `src/auth/shopify/callback.php` — Token exchange
- `src/auth/shopify/webhooks.php` — Webhook verification

### 📊 Database Schema
Complete schema with 8 tables + migrations:

```
✅ admins — Admin users
✅ admin_2fa — 2FA codes (auto-expiring)
✅ shops — Merchant stores
✅ admin_shop — Admin-to-shop associations
✅ campaigns — Notification campaigns
✅ subscribers — Customer subscribers
✅ notifications — Sent notifications
✅ logs — Event logs
```

Run: `php migrate.php` (when MySQL is ready)

---

## Quick Start

### 1. Configure Environment

Update `config/.env`:

```env
# Email Configuration
MAIL_FROM=noreply@toasty.hypp.dev
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_mailtrap_username
MAIL_PASSWORD=your_mailtrap_password

# Shopify Configuration
SHOPIFY_API_KEY=your_api_key
SHOPIFY_API_SECRET=your_api_secret
SHOPIFY_API_VERSION=2024-01
SHOPIFY_SCOPES=write_products,read_customers
```

Get Mailtrap credentials: https://mailtrap.io (free account)
Get Shopify API keys: https://partners.shopify.com/

### 2. Test Email Sending

```bash
php cli/test-mail.php
```

Emails will appear in Mailtrap dashboard (no real inbox needed).

### 3. Setup Database

Start MAMP, then:

```bash
php migrate.php
```

Or manually:
```bash
mysql -u yihu7512_juli3n -p yihu7512_toasty < database/migrations/001_initial_schema.sql
```

### 4. Create Admin User

```bash
php cli/create-admin.php
```

Then login at: `http://localhost:8888/toasty/login`

### 5. Test Database Connection

```bash
php cli/test-db.php
```

---

## Features Implemented

### Email Service (MailService.php)

✅ **send2FACode()** — Send 6-digit verification codes
```php
$mail = new MailService();
$mail->send2FACode('user@example.com', '123456');
```

✅ **sendWelcome()** — Send welcome emails to new shops
```php
$mail->sendWelcome('shop@example.com', 'Shop Name');
```

✅ **sendPasswordReset()** — Password reset emails
```php
$mail->sendPasswordReset('user@example.com', $resetToken);
```

✅ **send()** — Generic email sending
```php
$mail->send($to, $subject, $body, $htmlBody);
```

### OAuth Service (ShopifyOAuthService.php)

✅ **getAuthorizeUrl()** — Generate OAuth authorization URL
```php
$oauth = new ShopifyOAuthService();
$url = $oauth->getAuthorizeUrl($shop, $redirectUri, $scopes);
```

✅ **exchangeCodeForToken()** — Exchange code for access token
```php
$tokenData = $oauth->exchangeCodeForToken($shop, $code, $state);
// Returns: ['access_token' => '...', 'scope' => '...']
```

✅ **makeRequest()** — Make authenticated API calls to Shopify
```php
$result = $oauth->makeRequest(
    $shop, 
    $accessToken, 
    'GET', 
    'graphql.json', 
    $body
);
```

✅ **verifyWebhookHmac()** — Verify webhook signatures
```php
if ($oauth->verifyWebhookHmac($data, $hmac)) {
    // Process webhook
}
```

---

## Testing Locally

### Email Testing
1. Sign up at https://mailtrap.io
2. Create new inbox
3. Copy SMTP credentials to `config/.env`
4. Run: `php cli/test-mail.php`
5. Emails appear in Mailtrap (no real inbox needed)

### OAuth Testing
1. Create custom Shopify app: https://partners.shopify.com/
2. Set redirect URI: `http://localhost:8888/toasty/shopify/callback`
3. Copy API key/secret to `config/.env`
4. Visit: `http://localhost:8888/toasty/shopify/install?shop=myshop.myshopify.com`

### Full Login Flow
1. Start MAMP (Apache + MySQL)
2. Run database migrations: `php migrate.php`
3. Create admin user: `php cli/create-admin.php`
4. Visit: `http://localhost:8888/toasty/login`
5. Enter email + password
6. Check Mailtrap for 2FA code
7. Enter code to login

---

## Architecture Overview

```
┌─────────────────────────────────────────┐
│ Toasty Application                      │
├─────────────────────────────────────────┤
│                                         │
│ Admin Login                             │
│  ├─ loginScript.php                    │
│  ├─ MailService → send2FACode()        │
│  ├─ resendCode.php                     │
│  └─ verifyCode.php → Create Session    │
│                                         │
│ Shopify OAuth                           │
│  ├─ shopify/install.php                │
│  ├─ ShopifyOAuthService → OAuth flow   │
│  ├─ shopify/callback.php               │
│  ├─ Exchange code → Get token          │
│  ├─ Save shop to DB                    │
│  └─ Create shop session                │
│                                         │
│ Database                                │
│  ├─ admins                              │
│  ├─ shops                               │
│  ├─ campaigns                           │
│  ├─ subscribers                         │
│  └─ notifications                       │
│                                         │
└─────────────────────────────────────────┘
```

---

## Security Notes

✅ 2FA codes expire after 10 minutes
✅ CSRF protection via OAuth state parameter
✅ HMAC verification for webhooks
✅ Prepared statements (no SQL injection)
✅ Foreign key constraints
✅ Password hashed with bcrypt

⚠️ Store all secrets in `config/.env` (not version controlled)
⚠️ Use TLS for all SMTP connections
⚠️ Use HTTPS in production
⚠️ Never commit API keys to Git

---

## Next Steps

**Ready to implement:**
1. ✅ Email 2FA
2. ✅ OAuth Shopify
3. ⏳ Campaign management API
4. ⏳ Subscriber management API
5. ⏳ Notification sending API
6. ⏳ React admin dashboard
7. ⏳ React Shopify app

---

## Troubleshooting

**Email not sending?**
- Check MAIL_HOST and MAIL_PORT in `config/.env`
- Verify Mailtrap credentials
- Run `php cli/test-mail.php` to debug

**OAuth failing?**
- Confirm SHOPIFY_API_KEY and SHOPIFY_API_SECRET
- Check redirect URI matches in Shopify Partners
- Verify session_start() in config/init.php

**Database error?**
- Start MySQL: `sudo /usr/local/mysql/support-files/mysql.server start`
- Or start MAMP directly
- Run `php cli/test-db.php` to debug

---

## Files Added/Modified

```
✅ NEW: app/Services/MailService.php
✅ NEW: app/Services/ShopifyOAuthService.php
✅ NEW: database/migrations/001_initial_schema.sql
✅ NEW: migrate.php (migration runner)
✅ NEW: cli/test-mail.php
✅ NEW: cli/test-db.php
✅ NEW: cli/create-admin.php
✅ NEW: IMPLEMENTATION.md (detailed docs)

✅ UPDATED: src/auth/loginScript.php
✅ UPDATED: src/auth/resendCode.php
✅ UPDATED: src/auth/shopify/install.php
✅ UPDATED: src/auth/shopify/callback.php
✅ UPDATED: config/database.php (path fix)

✅ UPDATED: composer.json (added phpmailer)
✅ UPDATED: composer.lock (phpmailer v7.1.1)
```

---

Enjoy building with Toasty! 🍞
