# Rebuild Roadmap - From Current State to Modern Design

## EXECUTIVE SUMMARY

**Current State:** 60% complete - Core pages exist but lack modern features
**Target State:** Full-featured, production-ready charity event platform
**Estimated Effort:** 150-200 hours (depending on payment gateway complexity)
**Priority:** Payment integration > Form completion > Security > Performance

---

## PHASE 1: FOUNDATION & CRITICAL FEATURES (Weeks 1-2)

### 1.1 Database Setup
- [ ] Create MySQL database schema
- [ ] Tables needed:
  - `users` (admin accounts)
  - `event_registrations` (team signups)
  - `activity_registrations` (participants)
  - `stall_registrations` (vendor applications)
  - `donations` (transaction records)
  - `contact_messages` (inquiries)

**SQL Template:**
```sql
CREATE TABLE event_registrations (
    id INT AUTO_INCREMENT PRIMARY KEY,
    team_name VARCHAR(255),
    category VARCHAR(50),
    num_rowers INT,
    captain_name VARCHAR(255),
    email VARCHAR(255),
    phone VARCHAR(20),
    organization VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    status ENUM('pending', 'confirmed', 'cancelled') DEFAULT 'pending'
);
```

### 1.2 Complete Empty Pages
- [ ] **register-activity.php** - Full form
  - Activity selection
  - Participant details (name, email, dietary prefs)
  - Accessibility requirements
  - Submit button with validation

- [ ] **register-stall.php** - Full form
  - Business/organization name
  - Stall size selection
  - Contact person details
  - Payment method selection

### 1.3 Payment Gateway Integration
**Choose: Stripe or PayPal**

**Recommended: Stripe** (more flexible, better for recurring)

**Implementation:**
- [ ] Install Stripe PHP SDK via Composer
- [ ] Create Stripe account & get API keys
- [ ] Add donation payment page
- [ ] Add stall registration payment
- [ ] Add team registration payment (optional)
- [ ] Implement webhook handlers for payment confirmation
- [ ] Test with Stripe test cards

**Code Template:**
```php
<?php
require 'vendor/autoload.php';
\Stripe\Stripe::setApiKey($_ENV['STRIPE_SECRET_KEY']);

try {
    $intent = \Stripe\PaymentIntent::create([
        'amount' => $amount * 100, // in cents
        'currency' => 'gbp',
        'metadata' => ['registration_id' => $reg_id]
    ]);
} catch(\Stripe\Exception\ApiErrorException $e) {
    // Handle error
}
?>
```

### 1.4 Email System
- [ ] Install PHPMailer via Composer
- [ ] Configure SMTP settings
- [ ] Create email templates for:
  - Registration confirmation
  - Contact form acknowledgment
  - Donation receipt
  - Admin notifications
- [ ] Implement function `send_email($to, $subject, $template_name, $data)`

**Email Templates Needed:**
- `registration_confirmed.html` - Sent to registrant
- `contact_received.html` - Auto-reply to contact form
- `donation_receipt.html` - Tax receipt for donations
- `admin_notification.html` - Alerts admin of new registrations

---

## PHASE 2: FORM COMPLETION & VALIDATION (Weeks 2-3)

### 2.1 Client-Side Form Validation
- [ ] Add HTML5 validation attributes
- [ ] Create `js/form-validation.js`
- [ ] Validate on blur + submit
- [ ] Show real-time error messages
- [ ] Disable submit button until valid

**JavaScript Approach:**
```javascript
function validateForm(formId) {
    const form = document.getElementById(formId);
    const inputs = form.querySelectorAll('input, textarea, select');
    let isValid = true;
    
    inputs.forEach(input => {
        if (!input.value.trim()) {
            showError(input, 'This field is required');
            isValid = false;
        }
        if (input.type === 'email' && !validateEmail(input.value)) {
            showError(input, 'Invalid email');
            isValid = false;
        }
    });
    return isValid;
}
```

### 2.2 Server-Side Validation
- [ ] Validate all inputs in handlers
- [ ] Sanitize and type-cast values
- [ ] Check for duplicates
- [ ] Validate relationships (category exists, etc.)
- [ ] Return specific error messages

### 2.3 Error Handling & User Feedback
- [ ] Create error display component (inline)
- [ ] Implement success toast notifications
- [ ] Add loading spinners during submission
- [ ] Show "thank you" page after submission
- [ ] Email confirmation to user

---

## PHASE 3: SECURITY HARDENING (Week 3)

### 3.1 CSRF Protection
- [ ] Generate CSRF token in forms
- [ ] Validate token in handlers
- [ ] Regenerate token after submission

**Implementation:**
```php
// Generate token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// In form
echo '<input type="hidden" name="csrf_token" value="' . $_SESSION['csrf_token'] . '">';

// In handler
if (hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    // Process form
}
```

### 3.2 Input Sanitization & Validation
- [ ] Sanitize all inputs properly
- [ ] Validate data types and formats
- [ ] Use prepared statements for database
- [ ] Escape output for display
- [ ] Validate file uploads

### 3.3 HTTPS & Security Headers
- [ ] Force HTTPS on production
- [ ] Add security headers:
  - X-Content-Type-Options: nosniff
  - X-Frame-Options: SAMEORIGIN
  - X-XSS-Protection: 1; mode=block
  - Strict-Transport-Security

### 3.4 Prevent Common Attacks
- [ ] Rate limiting on forms (max 5 submissions/minute)
- [ ] Honeypot field (fake hidden field to catch bots)
- [ ] SQL injection prevention (prepared statements)
- [ ] XSS prevention (HTML escape output)

---

## PHASE 4: SEO & METADATA (Week 3)

### 4.1 Meta Tags
Add to every page:
```html
<meta name="description" content="Charity Boat Race 2026...">
<meta name="keywords" content="charity, boat race, community, fundraising">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="canonical" href="https://example.com/page">

<!-- Open Graph -->
<meta property="og:title" content="Title">
<meta property="og:description" content="Description">
<meta property="og:image" content="Image URL">
<meta property="og:url" content="Page URL">

<!-- Twitter -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Title">
<meta name="twitter:description" content="Description">
<meta name="twitter:image" content="Image URL">
```

### 4.2 Schema Markup (JSON-LD)
```html
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "Event",
  "name": "Charity Boat Race 2026",
  "startDate": "2026-06-14",
  "endDate": "2026-06-14",
  "location": {
    "@type": "Place",
    "name": "London Regatta Centre",
    "address": "Dockside Road, London, E16 2QT"
  },
  "organizer": {
    "@type": "Organization",
    "name": "Bridgewater Trust"
  }
}
</script>
```

### 4.3 Structured Data for Pages
- [ ] Organization schema on homepage
- [ ] Event schema on events page
- [ ] Breadcrumb schema on internal pages
- [ ] FAQ schema on FAQ page
- [ ] Product schema on donation page

---

## PHASE 5: ACCESSIBILITY (Week 4)

### 5.1 HTML/ARIA Improvements
- [ ] Add `role` attributes to custom components
- [ ] Add `aria-label` to icon buttons
- [ ] Add `aria-describedby` to form errors
- [ ] Add `aria-live="polite"` to dynamic content
- [ ] Ensure proper heading hierarchy

### 5.2 Keyboard Navigation
- [ ] Test all interactive elements with Tab key
- [ ] Visible focus indicators (outline)
- [ ] Trap focus in modals
- [ ] Allow Escape to close modals
- [ ] Skip to main content link

### 5.3 Color Contrast & Visual
- [ ] Test color contrast (min 4.5:1 for AA)
- [ ] Don't rely on color alone for meaning
- [ ] Add focus states to all buttons
- [ ] Ensure text is resizable (no fixed font-size)
- [ ] Support high contrast mode

### 5.4 Screen Reader & Alt Text
- [ ] Alt text on all images (descriptive)
- [ ] Skip icon-only buttons with aria-label
- [ ] Use semantic HTML (nav, main, aside, footer)
- [ ] Form labels associated with inputs
- [ ] Error messages linked to inputs

---

## PHASE 6: PERFORMANCE OPTIMIZATION (Week 4)

### 6.1 Image Optimization
- [ ] Convert images to WebP format
- [ ] Use responsive images with `srcset`
- [ ] Implement lazy loading
- [ ] Compress images (TinyPNG, ImageOptim)
- [ ] Use CDN for images

**Example:**
```html
<img src="image.webp" 
     srcset="image-small.webp 480w, image-medium.webp 768w, image-large.webp 1200w"
     sizes="(max-width: 600px) 100vw, (max-width: 1200px) 50vw, 1200px"
     alt="Description"
     loading="lazy">
```

### 6.2 CSS & JavaScript
- [ ] Minify CSS & JS
- [ ] Remove unused CSS
- [ ] Inline critical CSS
- [ ] Defer non-critical JavaScript
- [ ] Split code into chunks

**Build Setup (if applicable):**
```json
// package.json
{
  "scripts": {
    "build": "sass css/style.scss css/style.min.css && uglifyjs js/main.js -o js/main.min.js"
  }
}
```

### 6.3 Font Optimization
- [ ] Use font-display: swap
- [ ] Subset fonts (load only needed characters)
- [ ] Preload key fonts
- [ ] Consider system fonts for body text

```html
<link rel="preload" href="font.woff2" as="font" type="font/woff2" crossorigin>
<style>
  @font-face {
    font-family: 'Poppins';
    src: url('poppins.woff2');
    font-display: swap;
  }
</style>
```

### 6.4 Caching & Compression
- [ ] Enable gzip compression
- [ ] Set browser cache headers
- [ ] Use service worker for offline support
- [ ] Cache API responses

---

## PHASE 7: MODERN FEATURES (Weeks 5-6)

### 7.1 Admin Dashboard
Create `/admin/dashboard.php`:
- [ ] View all registrations
- [ ] Search & filter registrations
- [ ] Download registration list (CSV)
- [ ] View donation stats
- [ ] Manage messages
- [ ] Send announcements

**Database queries needed:**
```php
// Get all registrations
$registrations = $db->query("
    SELECT * FROM event_registrations 
    WHERE created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)
    ORDER BY created_at DESC
");

// Get donation stats
$stats = $db->query("
    SELECT 
        COUNT(*) as total_donations,
        SUM(amount) as total_amount,
        AVG(amount) as avg_donation
    FROM donations
    WHERE status = 'completed'
");
```

### 7.2 User Accounts (Optional)
- [ ] User registration/login
- [ ] View registration history
- [ ] Manage profile
- [ ] Download receipts
- [ ] Email preferences

### 7.3 Email Newsletter
- [ ] Newsletter signup form
- [ ] Email list management
- [ ] Automated email campaigns
- [ ] Unsubscribe link

### 7.4 Analytics Integration
- [ ] Google Analytics 4
- [ ] Conversion tracking (registration, donation)
- [ ] Heatmap tracking (Hotjar)
- [ ] Form analytics

```html
<!-- Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_ID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'GA_ID');
</script>

<!-- Conversion tracking -->
<script>
  gtag('event', 'registration_complete', {
    'transaction_id': '<?php echo $registration_id; ?>'
  });
</script>
```

---

## PHASE 8: ENHANCED UX (Week 6)

### 8.1 Animations & Transitions
- [ ] Page transition animations
- [ ] Scroll animations (on scroll, fade in)
- [ ] Button hover effects
- [ ] Loading spinners
- [ ] Success animations

**Install AOS (Animate on Scroll):**
```html
<link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" />
<script src="https://unpkg.com/aos@next/dist/aos.umd.js"></script>
<script>
  AOS.init();
</script>

<div data-aos="fade-up" data-aos-duration="1000">
  Content slides up
</div>
```

### 8.2 Interactive Components
- [ ] Image carousel/slider
- [ ] Accordion components
- [ ] Tabs
- [ ] Modals
- [ ] Tooltips

**Example Carousel:**
```html
<div id="carousel" class="carousel slide">
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img src="image1.jpg">
    </div>
  </div>
</div>
<script>
  new bootstrap.Carousel(document.getElementById('carousel'))
</script>
```

### 8.3 Loading States & Feedback
- [ ] Show spinners during form submission
- [ ] Disable buttons while processing
- [ ] Show success/error messages
- [ ] Toast notifications

```html
<!-- Loading spinner -->
<div id="loading" style="display: none;" class="spinner-border text-primary" role="status">
  <span class="visually-hidden">Loading...</span>
</div>

<script>
  function submitForm() {
    document.getElementById('loading').style.display = 'block';
    // Submit form
  }
</script>
```

---

## PHASE 9: TESTING & QA (Week 7)

### 9.1 Manual Testing
- [ ] Test all forms (valid & invalid data)
- [ ] Test payment gateway (use test cards)
- [ ] Test email notifications
- [ ] Test on different browsers (Chrome, Firefox, Safari, Edge)
- [ ] Test on mobile devices
- [ ] Test accessibility (keyboard, screen reader)

### 9.2 Automated Testing
- [ ] Unit tests for PHP functions
- [ ] Integration tests for database
- [ ] Form validation tests
- [ ] Security tests (CSRF, SQL injection)

```php
// PHPUnit example
class RegistrationTest extends PHPUnit\Framework\TestCase {
    public function testValidRegistration() {
        $result = validateRegistration([
            'team_name' => 'Thunder Rowers',
            'email' => 'team@example.com'
        ]);
        $this->assertTrue($result);
    }
}
```

### 9.3 Performance Testing
- [ ] Page load speed (target: <3s)
- [ ] Lighthouse score (target: >90)
- [ ] Mobile performance
- [ ] Database query performance

### 9.4 Security Testing
- [ ] Penetration testing (basic)
- [ ] OWASP Top 10 check
- [ ] SSL/HTTPS validation
- [ ] Header validation

---

## PHASE 10: DEPLOYMENT & MAINTENANCE (Week 8)

### 10.1 Deployment Preparation
- [ ] Set up staging environment
- [ ] Database migrations script
- [ ] Environment variables (.env file)
- [ ] Backup strategy
- [ ] Rollback plan

### 10.2 Server Configuration
- [ ] PHP 8.1+ installed
- [ ] MySQL 5.7+ installed
- [ ] SSL certificate
- [ ] gzip compression enabled
- [ ] Security headers configured

### 10.3 Monitoring & Logging
- [ ] Error logging (log all errors to file)
- [ ] Uptime monitoring
- [ ] Email alerts for errors
- [ ] Database backups (daily)
- [ ] Visitor analytics

### 10.4 Maintenance Plan
- [ ] Regular backups
- [ ] Security updates
- [ ] Monitor server resources
- [ ] Handle user support
- [ ] Collect feedback

---

## QUICK IMPLEMENTATION CHECKLIST

### Files to Create/Modify

#### New Files
- [ ] `config/database.php` - Database configuration
- [ ] `config/constants.php` - App constants
- [ ] `includes/auth.php` - Authentication functions
- [ ] `includes/email.php` - Email functions
- [ ] `includes/helpers.php` - Utility functions
- [ ] `js/form-validation.js` - Client-side validation
- [ ] `js/animations.js` - Scroll animations
- [ ] `admin/dashboard.php` - Admin interface
- [ ] `admin/registrations.php` - Registration management
- [ ] `.env.example` - Environment template
- [ ] `database-migrations.sql` - Database setup

#### Modified Files
- [ ] `register-event.php` - Add validation, submission
- [ ] `register-activity.php` - Complete implementation
- [ ] `register-stall.php` - Complete implementation
- [ ] `donate.php` - Add payment integration
- [ ] `handlers/registration-handler.php` - Database storage
- [ ] `handlers/contact-handler.php` - Email sending
- [ ] `includes/header.php` - Add meta tags, analytics
- [ ] `css/style.css` - Add animations, improve responsive
- [ ] `js/main.js` - Add form validation

---

## ESTIMATED EFFORT BREAKDOWN

| Phase | Task | Hours | Priority |
|-------|------|-------|----------|
| 1 | Database setup | 8 | Critical |
| 1 | Complete forms | 12 | Critical |
| 1 | Payment gateway | 16 | Critical |
| 1 | Email system | 8 | Critical |
| 2 | Form validation | 12 | High |
| 2 | Error handling | 8 | High |
| 3 | Security hardening | 12 | High |
| 4 | SEO & metadata | 8 | Medium |
| 5 | Accessibility | 12 | Medium |
| 6 | Performance | 10 | Medium |
| 7 | Admin dashboard | 16 | Medium |
| 8 | Animations & UX | 10 | Low |
| 9 | Testing & QA | 16 | High |
| 10 | Deployment | 12 | High |
| **Total** | | **160** | |

---

## TECH STACK RECOMMENDATIONS

### Backend
- **Language:** PHP 8.1+
- **Framework:** Laravel 10 (optional, for larger app)
- **Database:** MySQL 5.7+ or PostgreSQL
- **Package Manager:** Composer

### Frontend
- **CSS:** Bootstrap 5 (keep existing)
- **Icons:** Lucide Icons (keep existing)
- **Animations:** AOS.js
- **Form Validation:** Parsley.js or native HTML5

### Third-Party Services
- **Payments:** Stripe or PayPal
- **Email:** SendGrid or AWS SES
- **Analytics:** Google Analytics 4
- **Heatmaps:** Hotjar (optional)
- **Backup:** AWS S3 or Backblaze

### Development Tools
- **Version Control:** Git
- **IDE:** VS Code
- **Local Dev:** Docker or MAMP (existing)
- **Testing:** PHPUnit
- **CI/CD:** GitHub Actions

---

## Success Criteria

✅ **MVP (Minimum Viable Product):**
- All forms complete and functional
- Database storage of registrations
- Email confirmations sent
- Basic admin dashboard
- Contact form working
- Mobile responsive

✅ **Production Ready:**
- Payment gateway integrated
- Security hardened (CSRF, input validation)
- HTTPS enforced
- SEO optimized (meta tags, schema)
- Accessibility compliant (WCAG AA)
- Performance optimized (Lighthouse >90)
- Error logging in place
- Daily backups
- Staging environment

✅ **Excellent:**
- Admin dashboard fully featured
- User accounts
- Newsletter system
- Analytics integrated
- Animations & smooth UX
- 99.9% uptime
- <2s page load time

---

## Next Steps

1. **Start with Phase 1 (Database & Forms)** - This is critical path
2. **Then Phase 3 (Security)** - Must be done before launch
3. **Then Phase 4 (SEO)** - Important for discoverability
4. **Then remaining phases** - Based on priority

**Recommended:** Start with database schema design, then implement payment integration while forms are being completed.

---

