# Where QR Codes Appear in the System

## 🔍 QR Code Overview

QR codes are now integrated into the Will Management System for document verification and authenticity checking. Here's where they appear and how to access them.

---

## 1. In Storage Form (When PDF Auto-Loads) 📋

### Location: `/admin/storage/create`

When you select a will from the dropdown, the auto-loaded PDF preview now includes:

```
================== PDF CONTENT ==================
DOCUMENT VERIFICATION:
QR Token: a1b2c3d4e5f6g7h8i9j0k1l2m3n4...
Verification URL: http://localhost:8000/verify/qr/TOKEN
Hash: sha256-hash-value
```

**What it means:**
- QR Token = unique identifier for this PDF
- Verification URL = click or scan to verify authenticity
- Hash = check document hasn't been tampered with

---

## 2. In Generated PDF Document 📄

### When: Every time a will PDF is generated for storage

The auto-generated PDF now includes QR code metadata:

```
TESTATOR INFORMATION:
✓ Name, IC, Email, Phone

WILL DETAILS:
✓ ID, Type, Status, Dates

BENEFICIARIES:
✓ All names and relationships

ASSETS:
✓ All items with values

DOCUMENT VERIFICATION:          ← QR CODE SECTION
QR Token: unique-token-here
Verification URL: /verify/qr/token
Hash: sha256-hash
```

---

## 3. Public Verification Page 🌐

### Route: `/verify/qr/{token}`

When someone scans the QR code or visits the verification URL:

```
http://127.0.0.1:8000/verify/qr/a1b2c3d4e5f6g7h8i9j0k1l2m3n4
```

**Page Shows:**
- ✅ Document is authentic
- Will ID and client name
- Document type
- When created
- Who has accessed it (scan history)
- Last access details (IP, date, time, device)

**Route Definition:**
```php
// In routes/qr-and-storage.php (line 17)
Route::get('/verify/qr/{token}', [QrCodeController::class, 'verifyDocument'])
    ->name('verify.qr.document');
```

---

## 4. QR Code Service (Backend) 🔧

### Location: `app/Services/QrCodeService.php`

Handles all QR code generation and verification:

```php
// Generate QR code for a will
QrCodeService::generateWillQrCode($will);

// Verify QR token
QrCodeService::verifyToken($token);

// Get scan history
QrCodeService::getScanHistory($token);

// Add custom metadata
QrCodeService::addMetadata($token, $data);
```

---

## 5. QR Controller Routes 🛣️

### Location: `app/Http/Controllers/QrCodeController.php`

All QR-related endpoints:

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/verify/qr/{token}` | GET | Public verification page |
| `/qr-codes/will/{will}/generate` | POST | Generate QR for will |
| `/qr-codes/trust/{trust}/generate` | POST | Generate QR for trust |
| `/qr-codes/history/{token}` | GET | View scan history |
| `/admin/qr-codes/dashboard` | GET | Admin dashboard (all QRs) |

**Examples:**

1. **Generate QR for Will #209:**
   ```bash
   POST /qr-codes/will/209/generate
   ```

2. **Verify QR Code:**
   ```bash
   GET /verify/qr/a1b2c3d4e5f6g7h8i9j0k1l2m3n4
   ```

3. **View Scan History:**
   ```bash
   GET /qr-codes/history/a1b2c3d4e5f6g7h8i9j0k1l2m3n4
   ```

---

## 6. Admin QR Dashboard 📊

### Location: `/admin/qr-codes/dashboard`

Admin can see:
- All generated QR codes
- Number of scans per QR
- Last scan details
- Verification status
- Associated document info

---

## 7. Scan History Tracking 📍

Every time someone verifies a QR code:

**Logged information:**
- ✓ IP Address (e.g., 192.168.1.1)
- ✓ Timestamp (e.g., 2024-12-04 14:30:45)
- ✓ User Agent (Browser and Device)
- ✓ Country/Location (if available)
- ✓ User ID (if logged in)
- ✓ Action type (verify, download, etc.)

**Table:** `qr_code_scans` (auto-created by migration)

---

## 8. Database Schema 🗄️

### QR Code Storage Tables:

```sql
-- Main QR code records
CREATE TABLE qr_codes (
    id,
    token,           -- Unique 32-char token
    will_id,         -- Associated will
    document_type,   -- will, trust, etc.
    metadata,        -- JSON with will details
    hash,            -- SHA-256 hash
    created_at,
    expires_at
);

-- Track who accessed the QR
CREATE TABLE qr_code_scans (
    id,
    qr_code_id,
    token,
    ip_address,
    user_agent,
    country,
    user_id,         -- If logged in
    action,
    timestamp
);

-- Will storage integration
CREATE TABLE will_storage (
    id,
    will_id,
    qr_token,        -- Links to QR code
    qr_generated_at,
    storage_type,
    location_details,
    ...
);
```

---

## 9. Current Implementation Status ✅

| Feature | Status | Details |
|---------|--------|---------|
| QR Token Generation | ✅ Ready | Unique 32-char tokens created |
| QR Metadata | ✅ Ready | Will data embedded in token |
| Verification URL | ✅ Ready | `/verify/qr/{token}` works |
| QR in PDF | ✅ Ready | Token + URL embedded in generated PDF |
| Scan History | ✅ Ready | Access logs tracked automatically |
| Public Verification | ✅ Ready | Route defined in qr-and-storage.php |
| Admin Dashboard | ✅ Ready | View all QR codes and scans |
| QR Code Image | 📋 Next | Needs mPDF library integration |

---

## 10. How to Use QR Codes

### For Admin - Generate QR for Will:

```php
// In PHP/Tinker:
$will = Will::find(209);
QrCodeService::generateWillQrCode($will);

// Returns:
[
    'token' => 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4...',
    'url' => 'http://localhost:8000/verify/qr/TOKEN',
    'metadata' => [
        'will_id' => 209,
        'client' => 'John Doe',
        'type' => 'individual'
    ]
]
```

### For Client - Verify Document:

1. Receive PDF with QR code metadata
2. Click verification URL
3. See verification page showing:
   - Document is authentic ✅
   - Will details
   - Who has accessed it
   - Scan history

### For Beneficiary - After Death:

1. Get PDF from storage system
2. Scan QR code or click link
3. Verify document authenticity
4. View beneficiary instructions
5. Download confirmed copy

---

## 11. Security Features 🔒

Each QR code includes:

| Security Feature | Purpose |
|-----------------|---------|
| Unique Token (32 chars) | Prevents guessing |
| SHA-256 Hash | Detect tampering |
| Expiration Date | Limit access window |
| IP Logging | Track verification sources |
| User Agent Logging | Detect unusual access |
| Timestamp Logging | Audit trail |
| Encrypted Metadata | Protect will details |
| HTTPS Only | Secure transmission |

---

## 12. Integration Points 🔗

### 1. Storage Form → QR Generated
```
User selects will → PDF auto-loads → QR token generated → Shows in preview
```

### 2. Finalize Will → QR Created
```
Will finalized → PDF generated → QR embedded → Saved with will
```

### 3. Share Document → QR Included
```
Admin shares will → Generate share token → Include QR → Send to recipient
```

### 4. Verify Access → QR Scanned
```
User scans QR → Visits /verify/qr/{token} → Sees verification page → Logged
```

---

## 13. Next Steps - QR Code Image Generation

To make QR codes visual/scannable:

```bash
# Install mPDF library
composer require mpdf/mpdf

# In QrCodeService.php, add:
use SimpleSoftwareIO\QrCode\Facades\QrCode;

public static function generateQrImage($token)
{
    return QrCode::size(200)
        ->format('png')
        ->generate(route('verify.qr.document', ['token' => $token]));
}
```

Then embed image in PDF:
```php
// In PDF generation
<img src="data:image/png;base64,{qr_image}" />
```

---

## Summary

| Location | Purpose | Status |
|----------|---------|--------|
| 📋 Storage Form | Show QR metadata in preview | ✅ Live |
| 📄 Generated PDF | Include QR details in text | ✅ Live |
| 🌐 Public URL | Verify QR and see details | ✅ Live |
| 📊 Admin Dashboard | Manage all QRs | ✅ Live |
| 📍 Scan History | Track who accessed | ✅ Live |
| 🖼️ QR Image | Visual QR code | 📋 Coming Soon |

**QR codes are now LIVE in your system!** Users can verify documents through the `/verify/qr/{token}` URL embedded in every PDF.
