# User Self-Delete System Documentation

## Overview
The Payonline backend-v2 system now provides comprehensive user self-delete functionality where:
- ✅ **Users can delete their own accounts** (soft delete)
- ✅ **Users can request account restoration** (via support)
- ✅ **Only admins can actually restore accounts** (maintains control)
- ✅ **Full audit trail** for security and compliance

## User Self-Delete Endpoints

### 1. User Self-Delete Account
**Endpoint:** `DELETE /api/user/delete`
**Authentication:** Required (user must be logged in)
**Purpose:** Allows authenticated users to soft delete their own account

#### Request Parameters (Optional):
```json
{
    "reason": "I no longer need this service",
    "password": "user_password" // Optional password confirmation for security
}
```

#### Response:
```json
{
    "status": "success",
    "message": "Your account has been successfully deleted. Contact support if you need to restore your account.",
    "data": {
        "user_id": 123,
        "deleted_at": "2023-10-23T10:30:00.000000Z",
        "restoration_info": {
            "message": "Your account can be restored by contacting our support team.",
            "support_contact": "Only administrators can restore deleted accounts."
        }
    }
}
```

#### Features:
- 🔒 **Password Confirmation** (optional): Extra security layer
- 📝 **Deletion Reason** (optional): For analytics and feedback
- 💾 **Soft Delete**: Account is not permanently removed
- 📊 **Audit Logging**: Complete activity trail
- 🌐 **IP & User Agent Tracking**: Security monitoring

### 2. Request Account Restoration
**Endpoint:** `POST /api/user/request-restoration`
**Authentication:** Not required (deleted users can't authenticate)
**Rate Limited:** 3 attempts per hour per IP
**Purpose:** Allows users to request restoration of their deleted account

#### Request Parameters:
```json
{
    "email": "user@example.com",
    "reason": "I deleted my account by mistake and need it restored for business purposes"
}
```

#### Validation Rules:
- `email`: Required, valid email format
- `reason`: Required, minimum 10 characters, maximum 500 characters

#### Response:
```json
{
    "status": "success",
    "message": "Your account restoration request has been submitted. Our support team will review it and contact you if your account can be restored."
}
```

#### Security Features:
- 🛡️ **Email Privacy**: Doesn't reveal if email exists in system
- 🚫 **Rate Limited**: Prevents spam (3 requests per hour)
- 📝 **Detailed Logging**: All requests logged for admin review
- 🔍 **IP Tracking**: Monitors request origins

## Admin Restoration Control

### Existing Admin Endpoints:
- `GET /api/user/admin/users/deleted` - View deleted users
- `POST /api/user/admin/users/{id}/restore` - Restore specific user
- `GET /api/user/admin/users/statistics` - View deletion statistics

## Complete User Journey

### 1. User Deletes Account:
```bash
# User is logged in and wants to delete account
DELETE /api/user/delete
Content-Type: application/json

{
    "reason": "Moving to different platform",
    "password": "user_password"
}
```

### 2. User Realizes Mistake and Requests Restoration:
```bash
# User can't log in anymore, requests restoration
POST /api/user/request-restoration
Content-Type: application/json

{
    "email": "user@example.com",
    "reason": "I made a mistake and need my account back for my business"
}
```

### 3. Admin Reviews and Restores:
```bash
# Admin checks restoration requests in logs
# Admin finds the user in deleted users list
GET /api/user/admin/users/deleted

# Admin restores the account
POST /api/user/admin/users/123/restore
```

## Implementation Details

### Database Changes:
- ✅ **No new tables needed** - uses existing `deleted_at` column
- ✅ **Soft Delete trait already implemented**
- ✅ **Full relationship preservation**

### Security Measures:

#### User Self-Delete:
- Password confirmation option
- Complete audit logging
- IP address and user agent tracking
- Reason capture for analytics

#### Restoration Requests:
- Rate limiting (3 per hour)
- Email privacy protection
- Admin-only restoration capability
- Detailed request logging

### Logging & Audit Trail:

#### Self-Delete Logs:
```php
Log::info('User self-deleted account', [
    'user_id' => 123,
    'email' => 'user@example.com',
    'reason' => 'User provided reason',
    'deleted_at' => '2023-10-23T10:30:00Z',
    'ip_address' => '192.168.1.1',
    'user_agent' => 'Mozilla/5.0...'
]);
```

#### Restoration Request Logs:
```php
Log::info('Account restoration requested', [
    'user_id' => 123,
    'email' => 'user@example.com',
    'reason' => 'User restoration reason',
    'requested_at' => '2023-10-23T11:00:00Z',
    'ip_address' => '192.168.1.1',
    'user_agent' => 'Mozilla/5.0...'
]);
```

## Frontend Integration Guide

### User Account Settings Page:
```javascript
// Add delete account button with confirmation
const deleteAccount = async (reason, password) => {
    const response = await fetch('/api/user/delete', {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({ reason, password })
    });
    
    if (response.ok) {
        // Redirect to goodbye page
        // Clear local storage/tokens
        // Show restoration info
    }
};
```

### Public Restoration Request Page:
```javascript
// Create a public page for restoration requests
const requestRestoration = async (email, reason) => {
    const response = await fetch('/api/user/request-restoration', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ email, reason })
    });
    
    // Always show success message for security
    showMessage('Request submitted successfully');
};
```

### Admin Dashboard Integration:
- Add "Restoration Requests" section
- Monitor deletion statistics
- Review restoration request logs
- Quick restore functionality

## Recommended UI Flow

### 1. Account Deletion Flow:
1. **Delete Button** → Confirmation modal
2. **Confirmation Modal** → Password field + reason field
3. **Submit** → Processing spinner
4. **Success** → Clear session + show restoration info
5. **Goodbye Page** → Link to restoration request

### 2. Restoration Request Flow:
1. **Public Form** → Email + detailed reason
2. **Submit** → Rate limit check
3. **Success Message** → "Request submitted"
4. **Admin Notification** → Email/dashboard alert

## Best Practices

### For Users:
- 💭 **Think twice** before deleting
- 📝 **Provide clear reason** for faster restoration
- 🔒 **Use password confirmation** for security
- 📧 **Keep email accessible** for restoration

### For Admins:
- 🔍 **Review restoration requests promptly**
- 📊 **Monitor deletion patterns** for UX improvements
- 🗂️ **Keep audit logs** for compliance
- ⚖️ **Establish restoration policies**

### For Developers:
- 🚫 **Never permanently delete** without explicit admin action
- 📝 **Log everything** for audit trails
- 🛡️ **Implement rate limiting** on public endpoints
- 🔐 **Validate all inputs** thoroughly

## Error Handling

The system handles various scenarios:
- Invalid password confirmation
- Missing required fields
- Rate limit exceeded
- Server errors
- Non-existent email addresses (handled securely)

All errors are logged appropriately while maintaining user privacy and security.
