# QR Code Testing & Integration Guide

## 📍 WHERE QR CODES APPEAR

### 1. **QR Code in PDF Document** (When PDF is downloaded)
**Location:** Inside generated PDF at top-right corner
**Shows On:**
- Will PDF document
- Trust PDF document
- Codicil document
- Any downloaded will/trust document

**How it looks:**
```
┌─────────────────────────────────────┐
│  [QR Code] ← Top right of PDF       │
│                                      │
│  LAST WILL AND TESTAMENT             │
│  ═════════════════════════════       │
│  Client Name: John Doe               │
│  Date: 2024-12-03                    │
│                                      │
│  [Will content...]                   │
└─────────────────────────────────────┘
```

---

### 2. **QR Verification Page** (When QR is scanned)
**URL:** `http://yoursite.com/verify/qr/{token}`

**Public Page (No login needed)**
- Shows document verification status
- Displays scan history
- Shows security information
- Tracks access attempts

**Example URL:**
```
http://localhost/verify/qr/a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z
```

---

### 3. **Admin Storage Dashboard**
**URL:** `http://yoursite.com/admin/documents/storage`

**Admin Only Page - Shows:**
- Total QR codes generated
- Document statistics
- Storage usage
- Access logs

---

## 🧪 STEP-BY-STEP TESTING GUIDE

### **TEST 1: Generate QR Code Token**

**Step 1:** Open Laravel Tinker
```bash
php artisan tinker
```

**Step 2:** Generate token
```php
> $will = \App\Models\Will::first()

> $token = \App\Services\QrCodeService::generateVerificationToken('will', $will->id)

// Output: a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z (64 char SHA256 hash)
```

**Step 3:** Generate QR code image
```php
> $qrCode = \App\Services\QrCodeService::generateQrCode($token, 300)

// Output: data:image/png;base64,iVBORw0KGgoAAAANS...
```

**Expected Result:** Base64 encoded PNG image

---

### **TEST 2: View QR Verification Page (Public)**

**Step 1:** Generate token (from TEST 1)
```
Token: a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z
```

**Step 2:** Visit verification URL in browser
```
http://localhost/verify/qr/a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z
```

**Expected Result:**
- ✅ Page loads successfully
- ✅ Shows "Document Verified" message
- ✅ Displays green success banner
- ✅ Shows token details
- ✅ Shows scan history (if any)
- ✅ Displays security information

**Screenshot:**
```
═════════════════════════════════════════════════════
         ✓ Document Verified
═════════════════════════════════════════════════════
Verification Token: a1b2c3d4e5...
Verified At: 03 Dec 2024, 10:45 AM
Your Location: 192.168.1.100
Verification Method: QR Code Scan

Document Information
═════════════════════════════════════════════════════
Total Scans: 5
First Scan: 03 Dec 2024, 10:15 AM
Last Scan: 03 Dec 2024, 10:45 AM

[Print] [Back]
═════════════════════════════════════════════════════
```

---

### **TEST 3: Invalid QR Token**

**Step 1:** Try invalid token
```
http://localhost/verify/qr/invalid-token-string
```

**Expected Result:**
- ✅ Page loads with error
- ✅ Shows "Verification Failed" message
- ✅ Displays red error banner
- ✅ Explains what went wrong
- ✅ Shows troubleshooting steps

**Screenshot:**
```
═════════════════════════════════════════════════════
         ✗ Verification Failed
═════════════════════════════════════════════════════
Invalid Token
The QR code token is invalid or corrupted.

What Happened?
═════════════════════════════════════════════════════
• The QR code is corrupted or damaged
• The document has been tampered with
• The verification token has expired
• The token was generated incorrectly

What You Can Do?
═════════════════════════════════════════════════════
1. Try Scanning Again
2. Check Your Camera
3. Download Original Document
4. Contact Support

[Contact Support] [Back]
═════════════════════════════════════════════════════
```

---

### **TEST 4: Embed QR in PDF**

**Step 1:** Modify WillTemplateController.php

Add this code to the PDF generation method:

```php
use App\Services\QrCodeService;

public function generatePdfWithQR(Will $will)
{
    // Generate QR token
    $token = QrCodeService::generateVerificationToken('will', $will->id);
    
    // Generate QR code image (base64)
    $qrCode = QrCodeService::generateQrCode($token, 300);
    
    // Create PDF
    $pdf = PDF::loadView('will.template', ['will' => $will]);
    
    // Add QR code to PDF (top right)
    // Using mPDF or other PDF library
    $pdf->image($qrCode, 15, 10, 50); // x, y, width
    
    return $pdf->download('will_' . $will->id . '.pdf');
}
```

**Step 2:** Test PDF generation
```
1. Login as client
2. Generate will PDF
3. Download PDF
4. Open PDF in viewer
5. Look for QR code in top-right corner
6. Scan with phone camera
7. Should open verification page
```

---

### **TEST 5: View Admin Dashboard**

**Step 1:** Login as admin

**Step 2:** Visit dashboard
```
http://localhost/admin/documents/storage
```

**Expected Result:**
- ✅ Shows storage statistics
- ✅ Displays 4 stat cards:
  - Total Documents
  - Storage Used
  - Encrypted Documents
  - Total Accesses
- ✅ Shows storage type breakdown
- ✅ Has action buttons
- ✅ Displays tabbed interface

**Screenshot:**
```
╔═════════════════════════════════════════════════════╗
║         Document Storage Management                  ║
╠═════════════════════════════════════════════════════╣
║                                                       ║
║  [Total: 45]  [Storage: 245 MB]  [Encrypted: 45]   ║
║  [Accesses: 1,230]                                   ║
║                                                       ║
║  Storage Types          | Actions                     ║
║  ────────────────────   ├─ Archive Old Documents      ║
║  Lifetime: 40           ├─ Verify Encryption         ║
║  Archived: 5            ├─ Export Logs                ║
║                         ├─ View Statistics            ║
║                                                       ║
║  ┌──────────────────────────────────────────────────┐ ║
║  │ Stored Docs │ Access Logs │ Sharing              │ ║
║  ├──────────────────────────────────────────────────┤ ║
║  │ Document │ Client │ Type │ Size │ Accesses      │ ║
║  ├──────────────────────────────────────────────────┤ ║
║  │ Will_1   │ John   │ Will │ 2MB  │ 5             │ ║
║  │ Trust_1  │ Jane   │Trust │ 3MB  │ 3             │ ║
║  └──────────────────────────────────────────────────┘ ║
╚═════════════════════════════════════════════════════╝
```

---

## 📝 COMPLETE TEST CHECKLIST

### **Phase 1: QR Generation**
- [ ] Generate token in tinker
- [ ] Token is 64-character SHA256 hash
- [ ] Generate QR code image
- [ ] QR code is base64 PNG
- [ ] Token can be verified

### **Phase 2: Public QR Verification**
- [ ] Valid token shows success page
- [ ] Success page loads correctly
- [ ] Shows document info
- [ ] Shows scan history
- [ ] Shows security details
- [ ] Print button works
- [ ] Back button works

### **Phase 3: Error Handling**
- [ ] Invalid token shows error page
- [ ] Error page displays correctly
- [ ] Shows troubleshooting steps
- [ ] Shows FAQ section
- [ ] Contact support link works
- [ ] Back button works

### **Phase 4: PDF Integration**
- [ ] QR code generates in PDF
- [ ] QR appears in top-right corner
- [ ] QR code scans with phone
- [ ] QR directs to verification page
- [ ] All scanning works correctly

### **Phase 5: Admin Dashboard**
- [ ] Admin can access dashboard
- [ ] Dashboard loads correctly
- [ ] Statistics display correctly
- [ ] All tabs are clickable
- [ ] Tables show data
- [ ] Action buttons work

### **Phase 6: Access Logging**
- [ ] Each QR scan is logged
- [ ] Logs show IP address
- [ ] Logs show timestamp
- [ ] Admin can view logs
- [ ] Logs are secure

---

## 🔧 INTEGRATION CODE SNIPPETS

### **In WillTemplateController.php**

```php
<?php
namespace App\Http\Controllers;

use App\Services\QrCodeService;
use App\Services\EstateAndStorageService;

class WillTemplateController extends Controller
{
    public function generatePdf(Will $will)
    {
        // Step 1: Generate QR token
        $token = QrCodeService::generateVerificationToken('will', $will->id);
        
        // Step 2: Generate QR code image
        $qrCode = QrCodeService::generateQrCode($token, 300);
        
        // Step 3: Build PDF
        $pdf = \PDF::loadView('will.template', [
            'will' => $will,
            'qrCode' => $qrCode,
            'token' => $token,
        ]);
        
        // Step 4: Store document
        $pdfContent = $pdf->render();
        $storage = EstateAndStorageService::storeDocument($will, $pdfContent, 'will');
        
        // Step 5: Return PDF
        return response($pdfContent, 200)
            ->header('Content-Type', 'application/pdf')
            ->header('Content-Disposition', 'attachment; filename="will_' . $will->id . '.pdf"');
    }
}
```

### **In PDF Template**

```blade
<!-- In resources/views/will/template.blade.php -->

<html>
<head>
    <title>Last Will and Testament</title>
</head>
<body>
    <!-- QR Code in top-right -->
    <div style="position: absolute; top: 20px; right: 20px;">
        @if($qrCode)
            <img src="{{ $qrCode }}" style="width: 80px; height: 80px;" alt="QR Code">
        @endif
    </div>

    <h1>LAST WILL AND TESTAMENT</h1>
    
    <!-- Will content here -->
    ...
    
    <!-- QR verification info at bottom -->
    <div style="border-top: 1px solid #ccc; padding-top: 20px; margin-top: 40px;">
        <p>Verification Token: {{ substr($token, 0, 32) }}...</p>
        <p>Scan QR code above to verify this document</p>
        <p>URL: {{ route('verify.qr.document', ['token' => $token]) }}</p>
    </div>
</body>
</html>
```

---

## 🚀 TESTING WORKFLOW

```
1. START
   ↓
2. Open Tinker: php artisan tinker
   ↓
3. Generate token: $token = QrCodeService::generateVerificationToken('will', 1)
   ↓
4. Generate QR: $qrCode = QrCodeService::generateQrCode($token)
   ↓
5. Visit: http://localhost/verify/qr/{token}
   ↓
6. Check: Verification page loads ✓
   ↓
7. Try invalid: http://localhost/verify/qr/invalid
   ↓
8. Check: Error page loads ✓
   ↓
9. Generate PDF with QR code
   ↓
10. Download PDF
    ↓
11. Scan QR code with phone
    ↓
12. Check: Redirects to verification page ✓
    ↓
13. View admin dashboard: /admin/documents/storage
    ↓
14. Check: Dashboard loads ✓
    ↓
15. DONE ✓
```

---

## ✅ SUCCESS CRITERIA

Your QR code implementation is working when:

✅ Tokens generate as 64-char SHA256 hashes  
✅ QR codes generate as base64 PNG images  
✅ Valid QR verification page shows success  
✅ Invalid QR verification page shows error  
✅ QR code scans with phone camera  
✅ Scanning opens verification page  
✅ Each scan is logged  
✅ Admin dashboard displays statistics  
✅ All pages are responsive  
✅ All buttons and links work  

---

## 🐛 TROUBLESHOOTING

### **QR code not generating**
```
Error: Class 'SimpleSoftwareIO\QrCode\Facades\QrCode' not found
Solution: composer require simplesoftwareio/simple-qr-code
```

### **Verification page shows 404**
```
Error: Route [verify.qr.document] not defined
Solution: Add route to routes/qr-and-storage.php and include in web.php
```

### **QR code not appearing in PDF**
```
Error: QR code base64 not showing in PDF
Solution: Check PDF library supports image embedding (mPDF does)
```

### **Token not validating**
```
Error: Invalid token format
Solution: Ensure token is exactly 64 characters (SHA256 output)
```

---

## 📞 QUICK REFERENCE

| Feature | URL | Auth | Status |
|---------|-----|------|--------|
| Generate Token | Tinker | N/A | Code |
| Verify QR | /verify/qr/{token} | No | Public |
| Error Page | /verify/qr/invalid | No | Public |
| Admin Dashboard | /admin/documents/storage | Yes | Admin |
| PDF Download | /wills/{id}/download | Yes | Client |

---

**You're all set! Start with TEST 1 and work through the checklist.** ✅
