# Photo Manager - S3 Upload Activation Guide

## Overview
The Photo Manager currently simulates uploads. To enable **real S3 uploads**, you need to integrate AWS SDK with your Cognito Identity Pool credentials.

## Prerequisites
1. AWS Account with S3 bucket access
2. Cognito Identity Pool configured (you already have: `us-east-1:79f92923-df36-437e-9210-dc97785c5734`)
3. S3 bucket with proper CORS configuration

## Step 1: Configure S3 Bucket CORS

Add this CORS configuration to your `bird-created` S3 bucket:

```json
[
    {
        "AllowedHeaders": ["*"],
        "AllowedMethods": ["GET", "PUT", "POST", "DELETE"],
        "AllowedOrigins": ["*"],
        "ExposeHeaders": ["ETag"]
    }
]
```

**How to add CORS:**
1. Go to AWS S3 Console
2. Select `bird-created` bucket
3. Click "Permissions" tab
4. Scroll to "Cross-origin resource sharing (CORS)"
5. Click "Edit" and paste the JSON above

## Step 2: Install AWS SDK

Add these script tags to `photo-manager.html` (before the closing `</body>` tag):

```html
<!-- AWS SDK v3 -->
<script src="https://cdn.jsdelivr.net/npm/@aws-sdk/client-s3@3.382.0/dist-es/index.browser.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@aws-sdk/client-cognito-identity@3.382.0/dist-es/index.browser.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@aws-sdk/credential-provider-cognito-identity@3.382.0/dist-es/index.browser.min.js"></script>
```

## Step 3: Replace the Upload Function

Replace the `uploadPhotos()` function in `photo-manager.html` with this code:

```javascript
// Initialize S3 Client
const { S3Client, PutObjectCommand } = window['@aws-sdk/client-s3'];
const { CognitoIdentityClient } = window['@aws-sdk/client-cognito-identity'];
const { fromCognitoIdentityPool } = window['@aws-sdk/credential-provider-cognito-identity'];

const s3Client = new S3Client({
    region: REGION,
    credentials: fromCognitoIdentityPool({
        client: new CognitoIdentityClient({ region: REGION }),
        identityPoolId: "us-east-1:79f92923-df36-437e-9210-dc97785c5734"
    })
});

// Upload photos to S3 (REAL IMPLEMENTATION)
async function uploadPhotos() {
    const currentAlbum = document.getElementById('currentAlbum').value;
    if (!currentAlbum || selectedFiles.length === 0) {
        alert('Please select an album and add photos');
        return;
    }

    const progressContainer = document.querySelector('.progress-bar-container');
    const progressBar = document.getElementById('uploadProgress');
    const statusText = document.getElementById('uploadStatus');

    progressContainer.style.display = 'block';

    try {
        for (let i = 0; i < selectedFiles.length; i++) {
            const file = selectedFiles[i];
            const progress = ((i + 1) / selectedFiles.length) * 100;

            progressBar.style.width = progress + '%';
            statusText.textContent = `Uploading ${i + 1} of ${selectedFiles.length}: ${file.name}`;

            // Upload to S3
            const key = BASE_PATH + currentAlbum + file.name;
            const command = new PutObjectCommand({
                Bucket: BUCKET_NAME,
                Key: key,
                Body: file,
                ContentType: file.type
            });

            await s3Client.send(command);
        }

        // Update album photo count
        const album = albums.find(a => a.path === currentAlbum);
        if (album) {
            album.photoCount = (album.photoCount || 0) + selectedFiles.length;
            localStorage.setItem('photoAlbums', JSON.stringify(albums));
        }

        // Success
        progressBar.classList.remove('progress-bar-animated');
        progressBar.classList.add('bg-success');
        statusText.textContent = `✅ Successfully uploaded ${selectedFiles.length} photos to S3!`;

        setTimeout(() => {
            selectedFiles = [];
            displayPhotoPreview();
            progressContainer.style.display = 'none';
            progressBar.classList.add('progress-bar-animated');
            progressBar.classList.remove('bg-success');
            progressBar.style.width = '0%';
            loadAlbums();
        }, 2000);

    } catch (error) {
        console.error('Upload error:', error);
        progressBar.classList.add('bg-danger');
        statusText.textContent = `❌ Error: ${error.message}`;
        alert(`Upload failed: ${error.message}\n\nMake sure:\n1. CORS is configured on S3 bucket\n2. Cognito Identity Pool has S3 permissions\n3. You're logged in`);
    }
}
```

## Step 4: Verify Cognito Permissions

Ensure your Cognito Identity Pool has these IAM permissions:

```json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:PutObjectAcl",
                "s3:GetObject",
                "s3:DeleteObject"
            ],
            "Resource": "arn:aws:s3:::bird-created/eqsong-images/*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket"
            ],
            "Resource": "arn:aws:s3:::bird-created"
        }
    ]
}
```

## Alternative: Use PHP Upload Backend (RECOMMENDED - Already Created!)

✅ **This is the recommended approach and is already implemented!**

The `upload-photo.php` file has been created and is ready to use. It provides:

- ✅ Server-side security (credentials not exposed to browser)
- ✅ File validation (type, size, format)
- ✅ Password protection via .htaccess
- ✅ Uses AWS CLI for uploads (simple, no SDK required)

### Setup Instructions for PHP Backend:

**Step 1: Configure AWS CLI on your server**

Run the automated setup script:

```bash
cd /home/eqsong/website
./setup-s3-upload.sh
```

This will:
- Check if AWS CLI is installed
- Verify AWS credentials are configured
- Test S3 bucket access
- Test upload permissions

**Step 2: If AWS CLI is not configured, set it up:**

```bash
aws configure
```

Enter:
- AWS Access Key ID: [Your AWS key]
- AWS Secret Access Key: [Your AWS secret]
- Default region: us-east-1
- Default output format: json

**Step 3: Test the upload**

1. Open `photo-manager.html` in your browser
2. Login with your credentials
3. Create or select an album
4. Upload a test photo
5. Check your S3 bucket at: https://s3.console.aws.amazon.com/s3/buckets/bird-created?prefix=eqsong-images/

**That's it!** The photo manager is now fully functional with real S3 uploads.

### How it Works:

The `upload-photo.php` script:
1. Receives file upload via POST request
2. Validates file type and size (max 10MB)
3. Uses AWS CLI to upload to S3: `aws s3 cp [file] s3://bird-created/eqsong-images/[album]/[filename]`
4. Returns success/error response as JSON

### Alternative: Use AWS SDK for PHP

If you prefer using AWS SDK instead of AWS CLI, here's the code:

## Testing

1. Open `photo-manager.html` in your browser
2. Login with your credentials
3. Select an album
4. Upload a test image
5. Check S3 bucket to verify the file was uploaded
6. Verify it appears in the public gallery

## Troubleshooting

**Error: "Access Denied"**
- Check Cognito IAM role permissions
- Verify S3 bucket policy allows Cognito Identity Pool

**Error: "CORS policy blocked"**
- Add CORS configuration to S3 bucket
- Ensure AllowedOrigins includes your domain

**Error: "Network error"**
- Check browser console for details
- Verify AWS SDK loaded correctly
- Test with a smaller image file

## Security Notes

- Client-side uploads expose AWS credentials in browser
- Consider using pre-signed URLs for better security
- PHP backend approach is more secure
- Always validate file types and sizes
- Consider adding virus scanning for production use

## Need Help?

Check the AWS Documentation:
- S3 Browser Upload: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-photo-album.html
- Cognito Identity Pools: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html
