# VPS Checkout Enhancement - 2026-02-10

## Overview
Enhanced the VPS checkout flow with OS selection, SSH key configuration, and automatic server building. Created a premium ordering experience matching modern cloud platforms.

## Frontend Changes

### Enhanced Checkout Page (`resources/ts/Pages/Checkout/Show.vue`)

**New Features:**
1. **Server Configuration Card** (VPS only)
   - Operating System selection dropdown with 9 options:
     - Ubuntu 24.04 LTS, 22.04 LTS, 20.04 LTS
     - Debian 12, 11
     - AlmaLinux 9
     - Rocky Linux 9
     - CentOS Stream 9
     - Fedora 39
   - Each OS has an icon (Ubuntu, Debian, RedHat, Fedora)

2. **Authentication Method Toggle**
   - **Auto-Generated Password** (default): VirtFusion generates and emails password
   - **SSH Key**: User pastes their SSH public key
   - Smooth transitions between modes
   - Helpful tooltips and documentation links

3. **Configuration Preview** (Sidebar)
   - Shows selected OS and auth method
   - Updates in real-time
   - Compact, professional display

4. **Visual Enhancements**
   - Premium card design with hover effects
   - Purple theme gradient on primary button
   - Smooth expand/collapse animations
   - Professional icons throughout
   - Enhanced spacing and typography
   - Secure checkout badge at bottom

## Backend Changes

### 1. Checkout Controller (`app/Http/Controllers/Account/CheckoutController.php`)
```php
// Added validation for configuration
'configuration' => ['nullable', 'array'],
'configuration.os_template_id' => ['nullable', 'integer'],
'configuration.auth_method' => ['nullable', 'in:password,ssh'],
'configuration.ssh_key' => ['nullable', 'string', 'max:4096'],

// Store configuration in session for provisioning
if ($request->has('configuration')) {
    session(['subscription_config_'.$subscription->id => $request->input('configuration')]);
}
```

### 2. VirtFusion Service (`app/Services/Provisioning/VirtFusionService.php`)

**New Build Step:**
After creating server and changing package, now automatically builds with:
- Selected OS template
- SSH key (if provided)
- Stores provisioning info in service record

```php
// Build server with OS template and SSH key
$config = session('subscription_config_'.$subscription->id, []);
$templateId = $config['os_template_id'] ?? 1; // Default to Ubuntu 24.04
$sshKey = $config['auth_method'] === 'ssh' && !empty($config['ssh_key']) ? $config['ssh_key'] : null;

$buildPayload = ['templateId' => $templateId];
if ($sshKey) {
    $buildPayload['sshKeys'] = [$sshKey];
}

$buildResponse = $this->client()->post("/servers/{$serverId}/build", $buildPayload);
```

**Complete Provisioning Flow:**
1. Create server (package 43)
2. Change package to match plan specs
3. **Build server with selected OS + SSH key**
4. Send credentials email

### 3. Subscription Cancellation (`app/Listeners/HandleSubscriptionCancelled.php`)

**Added 5-Minute Grace Period:**
```php
// Wait 5 minutes before terminating services (grace period)
sleep(300);
```

This prevents accidental immediate termination and gives users time to reconsider.

## User Experience Flow

### Ordering VPS

1. **Select Plan** → Navigate to checkout
2. **Configure Server**:
   - Choose operating system from dropdown
   - Select authentication method (password or SSH key)
   - If SSH: paste public key with helpful instructions
   - See live preview in sidebar
3. **Choose Payment Method**
   - Stripe (saved cards) or PayPal
   - Apply coupon if available
4. **Complete Order**
   - Premium gradient button with security badge
   - Processing state with loading indicator
5. **Provisioning** (background):
   - Create VirtFusion user (if needed)
   - Create server
   - Change to correct package specs
   - **Build with selected OS and SSH key**
   - Email credentials to customer

### Canceling Subscription

1. Cancel subscription via dashboard
2. **5-minute grace period** before termination
3. Service terminated on VirtFusion
4. Service status updated to "terminated"
5. Cancellation notification sent

## Configuration Storage

- **Frontend → Backend**: Passed in `configuration` object
- **Backend → Session**: Stored temporarily during checkout
- **Session → Provisioning**: Read during VirtFusion provisioning
- **Service Record**: Final config saved to `provisioning_info` JSON field

## VirtFusion API Calls

### Complete Provisioning Sequence:
```
POST /sanctum/csrf-cookie           # Get CSRF token
GET  /users?email={email}           # Check if user exists
POST /users                         # Create user (if needed)
POST /servers                       # Create server (package 43)
POST /servers/{id}/changePackage    # Change to plan specs
POST /servers/{id}/build            # Build with OS + SSH key ← NEW
```

### Build Payload:
```json
{
  "templateId": 1,
  "sshKeys": ["ssh-rsa AAAAB3NzaC1yc2E..."]  // optional
}
```

## Database Schema

### Services Table
- `provisioning_info` (JSON): Stores OS template ID and auth method
```json
{
  "os_template_id": 1,
  "auth_method": "ssh"
}
```

### Provisioning Logs
New entries for `build` action:
- `provision` → `change_package` → **`build`** → complete

## Testing

1. ✅ Frontend builds without errors
2. ✅ Horizon restarted to reload code
3. ⏳ Create VPS subscription with:
   - Ubuntu 24.04 + Password
   - Debian 12 + SSH Key
4. ⏳ Verify VirtFusion server is actually built and installed
5. ⏳ Cancel subscription and verify 5-minute delay

## Default Values

- **Default OS**: Ubuntu 24.04 LTS (template ID 1)
- **Default Auth**: Auto-generated password
- **Grace Period**: 5 minutes (300 seconds)

## Visual Design

**Aesthetic**: Refined, professional cloud platform
- Clean card layout with subtle shadows
- Purple accent color (#7367F0)
- Smooth transitions and hover effects
- Professional icons (Material Design Icons)
- Monospace font for SSH key input
- Security badges and trust indicators
- Responsive layout (mobile-friendly)

**Key Design Elements:**
- Server config card has purple top border
- OS dropdown with icons for each option
- Toggle button for auth method selection
- Expandable SSH key textarea
- Live configuration preview in sidebar
- Gradient on checkout button
- Secure checkout badge

## Future Enhancements

1. **Fetch Templates from VirtFusion API** (currently hardcoded)
2. **Show available templates per hypervisor**
3. **SSH key validation** (format checking)
4. **Multiple SSH keys** support
5. **Save SSH keys** to user profile for reuse
6. **OS logos** instead of generic icons
7. **Template descriptions** with tooltips
