# ArtWall - Quick Start Guide

## 🚀 First Time Setup (5 minutes)

### 1. Database Setup
```bash
# Open MySQL and run:
mysql -u root -p < database/schema.sql

# Verify:
mysql -u root -p
> USE artwall_db;
> SHOW TABLES;
> SELECT * FROM subscription_packages;
```

### 2. Environment Configuration
```bash
# Copy and edit .env file
copy .env.example .env

# Edit these variables:
# DB_HOST=localhost
# DB_USER=root
# DB_PASSWORD= (leave empty for default)
# APP_URL=http://localhost/artwall
```

### 3. Create Admin Account
```php
// Execute in browser or CLI (includes/init.php loaded)
$auth = new Auth();
$result = $auth->createUser(
    email: 'admin@artwall.com',
    password: 'StrongPassword123!',
    user_type: 'admin'
);
// Login at http://localhost/artwall/admin/
```

## 📁 Project Structure

```
config/         → All config, env variables, global constants
includes/       → Database, Security, Auth classes + helpers
admin/          → Admin dashboard pages
gallery/        → Gallery staff dashboard pages
public/         → Public e-catalogue frontend
api/            → API endpoints (search, tracking, upload)
database/       → SQL schema and migrations
logs/           → Daily error logs (logs/YYYY-MM-DD.log)
temp/           → Temp file uploads (before S3)
```

## 🔐 Security Checklist

Before deployment:
- [ ] Change `APP_KEY` to random 64-character string
- [ ] Set strong DB password (not empty)
- [ ] Configure AWS S3 credentials
- [ ] Configure reCAPTCHA keys
- [ ] Enable HTTPS (Cloudflare)
- [ ] Set `APP_ENV=production` in .env
- [ ] Disable `APP_DEBUG=false`

## 📚 Core Classes

### Database (`includes/Database.php`)
```php
$db = new Database();

// SELECT
$user = $db->prepare("SELECT * FROM users WHERE id = ?")->bindArray([1])->getOne();
$users = $db->prepare("SELECT * FROM users")->getAll();

// INSERT
$id = $db->insert('users', ['email' => 'test@example.com', 'password' => '...']);

// UPDATE
$db->update('users', ['name' => 'John'], ['id' => 1]);

// DELETE
$db->delete('users', ['id' => 1]);

// TRANSACTIONS
$db->beginTransaction();
try {
    // operations
    $db->commit();
} catch (Exception $e) {
    $db->rollback();
}
```

### Security (`includes/Security.php`)
```php
// Password
$hash = Security::hashPassword('password');
Security::verifyPassword('password', $hash);

// CSRF
$token = Security::generateCSRFToken();
if (!Security::verifyCSRFToken($_POST['csrf_token'])) {
    die('CSRF token mismatch');
}

// Validation
Security::sanitizeInput($input);
Security::validateEmail($email);
Security::validatePasswordStrength($password);

// Rate Limiting
$rate = Security::checkRateLimit($user_email);
if (!$rate['allowed']) {
    // Too many attempts
}

// File Upload
$validation = Security::validateFileUpload($_FILES['image']);
if (!$validation['valid']) {
    echo $validation['errors'];
}

// IP Address
$ip = Security::getClientIP(); // Handles Cloudflare proxies
```

### Auth (`includes/Auth.php`)
```php
$auth = new Auth();

// Login
$result = $auth->login('email@example.com', 'password');

// Register Gallery
$result = $auth->registerGallery(
    email: 'gallery@example.com',
    password: 'Password123!',
    confirm_password: 'Password123!',
    gallery_name: 'My Art Gallery',
    first_name: 'John',
    last_name: 'Doe'
);

// Logout
$auth->logout();

// Password Reset
$auth->requestPasswordReset('email@example.com');
$auth->resetPassword($token, 'NewPassword123!', 'NewPassword123!');
```

## 🛠️ Helper Functions (`includes/functions.php`)

```php
// Logging
log_error("Something went wrong", "ERROR");
log_activity($user_id, 'UPDATE', 'Updated artwork', 'artworks', $artwork_id, $old, $new);
log_page_view($artwork_id, $gallery_id);
log_contact_view($artwork_id, $gallery_id);

// Session
isLoggedIn();
checkSessionTimeout();
getCurrentUser();
getCurrentUserID();

// Response
json_response(true, "Success", ['id' => 123], 200);
redirect('/admin/dashboard.php');

// reCAPTCHA
if (verify_recaptcha($_POST['recaptcha_token'])) {
    // User passed verification
}

// Pagination
$page_info = paginate(250, 20, $_GET['page'] ?? 1);
// Returns: total_items, per_page, current_page, total_pages, offset, has_prev, has_next
```

## 🗄️ Database Query Examples

### Get All Artworks for Gallery
```php
$artworks = $db->prepare("
    SELECT a.*, ar.name as artist_name, s.name as storage_name
    FROM artworks a
    JOIN artists ar ON a.artist_id = ar.id
    LEFT JOIN storage_locations s ON a.storage_location_id = s.id
    WHERE a.gallery_id = ? AND a.deleted_at IS NULL
    ORDER BY a.created_at DESC
")->bindArray([$gallery_id])->getAll();
```

### Get Public Catalogue (With Subscription Check)
```php
$artworks = $db->prepare("
    SELECT a.*, g.name as gallery_name, ar.name as artist_name
    FROM artworks a
    JOIN galleries g ON a.gallery_id = g.id
    JOIN artists ar ON a.artist_id = ar.id
    WHERE g.subscription_status = 'active'
      AND a.deleted_at IS NULL
      AND a.status IN ('for_sale', 'private_collection')
    ORDER BY a.created_at DESC
")->getAll();
```

### Get Artist Edit Suggestions Pending Review
```php
$suggestions = $db->prepare("
    SELECT aes.*, ar.name as artist_name, g.name as gallery_name
    FROM artist_edit_suggestions aes
    JOIN artists ar ON aes.artist_id = ar.id
    JOIN galleries g ON aes.gallery_id = g.id
    WHERE aes.status = 'pending'
    ORDER BY aes.created_at ASC
")->getAll();
```

### Get Artwork View Analytics
```php
$stats = $db->prepare("
    SELECT artwork_id, COUNT(*) as view_count, COUNT(DISTINCT ip_address) as unique_views
    FROM artwork_views
    WHERE artwork_id = ?
    GROUP BY artwork_id
")->bindArray([$artwork_id])->getOne();
```

## 🎯 Common Tasks

### Add New User (Admin Panel)
```php
$auth = new Auth();
$result = $auth->createUser(
    'gallery@example.com',
    'Password123!',
    'gallery',
    $gallery_id,
    'John',
    'Doe'
);
```

### Create Artwork
```php
$artwork_id = $db->insert('artworks', [
    'gallery_id' => $_SESSION['user']['gallery_id'],
    'artist_id' => $artist_id,
    'name' => 'Artwork Title',
    'year_created' => 2024,
    'price' => 50000.00,
    'price_visibility' => 'visible',
    'status' => 'for_sale',
    'height_cm' => 100,
    'width_cm' => 80,
    'description' => 'Beautiful artwork...'
]);

log_activity(getCurrentUserID(), 'CREATE', 'Added artwork', 'artworks', $artwork_id);
```

### Suggest Artist Edit
```php
$db->insert('artist_edit_suggestions', [
    'artist_id' => $artist_id,
    'gallery_id' => $_SESSION['user']['gallery_id'],
    'field_name' => 'description',
    'old_value' => $current_description,
    'new_value' => $_POST['description'],
    'reason' => $_POST['reason'],
    'status' => 'pending'
]);
```

### Upload Artwork Image
```php
// Validate
$validation = Security::validateFileUpload($_FILES['image'], UPLOAD_ALLOWED_TYPES, UPLOAD_MAX_SIZE);
if (!$validation['valid']) {
    return json_response(false, implode(', ', $validation['errors']), null, 400);
}

// TODO: Upload to S3
// $s3_url = uploadToS3($_FILES['image']);

// Store in database
$db->insert('artwork_images', [
    'artwork_id' => $artwork_id,
    'image_url' => $s3_url,
    'alt_text' => $_POST['alt_text'],
    'is_primary' => $_POST['is_primary'] ? true : false,
    'uploaded_by' => getCurrentUserID()
]);
```

## 🐛 Debugging Tips

### Enable Debug Mode
```php
// In .env: APP_DEBUG=true
// Errors will show in browser + logs/YYYY-MM-DD.log
```

### Check Activity Log
```sql
-- See what user did recently
SELECT * FROM activity_logs 
WHERE user_id = 5 
ORDER BY created_at DESC 
LIMIT 50;

-- See failed logins
SELECT * FROM login_attempts 
WHERE email = 'user@example.com' 
ORDER BY last_attempt DESC;
```

### Test Database Connection
```php
try {
    $db = new Database();
    echo "Connected!";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
```

### View Logs
```bash
# Linux/Mac
tail -f logs/2025-01-24.log

# Windows PowerShell
Get-Content logs/2025-01-24.log -Tail 50 -Wait
```

## 📞 Support & Resources

- **Copilot Instructions:** `.github/copilot-instructions.md` (for AI agents)
- **Full Documentation:** `README.md`
- **Database Schema:** `database/schema.sql`
- **Error Logs:** `logs/YYYY-MM-DD.log`
- **Activity Logs:** `activity_logs` table in database

---

**Quick Tip:** Always check `.github/copilot-instructions.md` when building new features to understand security requirements and architectural patterns!
