# SmartRide Pro — SaaS Architecture & Deployment Guide

**SmartRide Pro** (`smartride.aonstudio.dev`) is a complete PHP 8 / MySQL 8 / Bootstrap 5 SaaS platform engineered for competitive road cyclists and multi-sport masters athletes. It combines automated Garmin Connect telemetry ingestion, TrainingPeaks-grade readiness modeling (**TSS, ATL, CTL, TSB**), multi-duration **Power Profiling (5s, 1m, 5m, 20m)**, **Pro Athletic Performance** adaptive training schedules (balancing road/indoor cycling, badminton agility, and strength training), and **Anti-Aging Nutrition** protocols.

## 1. Complete Folder & File Structure Tree

```text
smartride-saas/
├── .env.example                      # Environment template (DB, App Encryption Key, Base URL)
├── composer.json                     # Composer dependencies (Stripe SDK, Google/Facebook OAuth, Dotenv)
├── README.md                         # Setup, webhook registration, and deployment instructions
├── config/
│   ├── database.php                  # Singleton PDO connection (UTF8MB4, ERRMODE_EXCEPTION, strict types)
│   ├── security.php                  # AES-256-GCM API key encryption, CSRF token manager, XSS helpers
│   └── settings.php                  # Dynamic loader for encrypted system_settings (Stripe, Google, FB keys)
├── database/
│   └── schema.sql                    # Deliverable 2: Full MySQL 8 schema + default roles & settings seed
├── src/
│   ├── Auth/
│   │   ├── AuthService.php           # Email/Password registration (14-day trial init), Argon2id hashing
│   │   ├── GoogleOAuthController.php # Google OAuth 2.0 callback & account linking
│   │   └── FacebookOAuthController.php # Facebook Graph OAuth callback & account linking
│   ├── Billing/
│   │   ├── StripeService.php         # Deliverable 3: Stripe Checkout Session & Customer Portal builder
│   │   └── AccessGuard.php           # Middleware checking Trial status, Active Stripe Sub, or Admin Override
│   ├── Coaching/
│   │   ├── MetricsCalculator.php     # NP, IF, TSS, exponentially weighted ATL (7d), CTL (42d), TSB (Form)
│   │   ├── PowerProfileEngine.php    # 5s Neuromuscular, 1m Anaerobic, 5m VO2max, 20m FTP W/kg analyzer
│   │   └── SmartCoachScheduler.php   # Dynamic workout + cross-training + anti-aging nutrition generator
│   └── Integrations/
│       └── GarminWebhookHandler.php  # Garmin Connect Ping/Push webhook parser & signature verifier
└── public/                           # Web server DocumentRoot (Apache / Nginx)
    ├── .htaccess                     # Clean URLs, HTTPS enforcement, security headers
    ├── index.php                     # Landing page & pricing tiers (Monthly / Yearly / 14-Day Free Trial)
    ├── login.php                     # Unified Email + Google + Facebook OAuth login screen
    ├── register.php                  # Onboarding with automatic 14-day Free Trial activation
    ├── dashboard.php                 # Deliverable 5: User Dashboard (Modern Clean Bootstrap 5 + Charts)
    ├── profile.php                   # Personal Garmin API Key, FTP, Weight, and Bike setup
    ├── billing.php                   # Deliverable 3: Checkout trigger & subscription status endpoint
    ├── webhooks/
    │   ├── stripe.php                # Deliverable 3: Stripe asynchronous webhook listener
    │   └── garmin.php                # Garmin Connect daily activity & sleep/HRV webhook endpoint
    ├── admin/
    │   ├── index.php                 # Deliverable 4: Admin Dashboard, User Management & Premium Unlock
    │   └── settings.php              # Global API Key Vault (Stripe Secret, Google/FB App Secrets)
    └── assets/
        ├── css/
        │   └── modern-clean.css      # Custom Bootstrap 5 theme (+20% readable typography, glass cards)
        └── js/
            └── dashboard.js          # Fetch API async handlers & ApexCharts power/readiness visualizers
```

## 2. Composer Dependencies (`composer.json`)

```json
{
  "name": "aonstudio/smartride-saas",
  "description": "Smart Cycling Training, Power Profiling & Athletic Performance SaaS",
  "type": "project",
  "require": {
    "php": ">=8.1",
    "ext-pdo": "*",
    "ext-openssl": "*",
    "ext-json": "*",
    "stripe/stripe-php": "^13.0",
    "league/oauth2-google": "^4.0",
    "league/oauth2-facebook": "^2.2",
    "vlucas/phpdotenv": "^5.6"
  },
  "autoload": {
    "psr-4": {
      "SmartRide\\": "src/"
    }
  }
}
```

## 3. Core Physiological & Coaching Algorithms (`@pro-athletic-performance`)

| Metric / Module | Formula & Sports Science Logic | Application in SmartRide SaaS |
| :--- | :--- | :--- |
| **Training Stress Score (TSS)** | $\text{TSS} = \frac{t \times \text{NP} \times \text{IF}}{\text{FTP} \times 3600} \times 100$, where $\text{IF} = \frac{\text{NP}}{\text{FTP}}$ | Computed automatically upon Garmin Connect webhook ingestion (`garmin.php`). |
| **Acute Training Load (ATL - Fatigue)** | $\text{ATL}_{\text{today}} = \text{ATL}_{\text{yesterday}} + (\text{TSS}_{\text{today}} - \text{ATL}_{\text{yesterday}}) \times (1 - e^{-1/7})$ | Tracks 7-day rolling acute physiological stress across cycling and badminton sessions. |
| **Chronic Training Load (CTL - Fitness)** | $\text{CTL}_{\text{today}} = \text{CTL}_{\text{yesterday}} + (\text{TSS}_{\text{today}} - \text{CTL}_{\text{yesterday}}) \times (1 - e^{-1/42})$ | Tracks 42-day rolling aerobic base and long-term training load. |
| **Training Stress Balance (TSB - Form)** | $\text{TSB} = \text{CTL}_{\text{yesterday}} - \text{ATL}_{\text{yesterday}}$ | Combined with Sleep Score & HRV to classify Daily Readiness (**Peak / Optimal / Tired / High Fatigue**). |
| **Power Profile Weakness Detection** | Compares W/kg across **5s (Sprint)**, **1m (Anaerobic)**, **5m ($\text{VO}_2\text{max}$)**, and **20m ($\text{FTP} \approx 95\% \times P_{20\text{m}}$)** against target benchmark ratios | Prescribes targeted interval workouts (e.g., *5-Min Strength Intervals* or *1-Min Anaerobic Repeats*) when TSB $> -10$, or pivots to Active Recovery / Mobility when fatigued. |
| **Anti-Aging & Masters Recovery (40+)** | Dynamic nutrient timing + joint/collagen & antioxidant protocol | Adjusts daily protein ($1.8\text{–}2.2\text{ g/kg}$), Omega-3 (EPA/DHA), Vitamin C + Hydrolyzed Collagen pre-badminton/strength, and tart cherry/polyphenol recovery support. |


## 4. Quick Deployment Steps (`smartride.aonstudio.dev`)

1. **Extract Archive**:
   ```bash
   unzip smartride-saas-complete.zip -d /var/www/html/smartride
   cd /var/www/html/smartride
   cp .env.example .env
   ```
2. **Import MySQL Database**:
   ```bash
   mysql -u root -p < database/schema.sql
   ```
3. **Install Composer Packages (Optional — built-in cURL fallbacks included)**:
   ```bash
   composer install --no-dev --optimize-autoloader
   ```
4. **Configure Apache VirtualHost**:
   Point `DocumentRoot` to `/var/www/html/smartride/public` and enable `mod_rewrite`.
5. **Configure Stripe & Garmin Webhooks**:
   - Stripe Webhook URL: `https://smartride.aonstudio.dev/webhooks/stripe.php`
   - Garmin Connect Webhook URL: `https://smartride.aonstudio.dev/webhooks/garmin.php`
