# Team Management Implementation Details

## System Architecture

### Overview
```
┌─────────────────────────────────────────────────────────┐
│                  ADMIN DASHBOARD                        │
│  • Team Members Navigation Item (Sidebar)              │
│  • Team Management Panel (Main Content)                │
│  • Add/Edit/Delete UI Components                       │
└────────────────┬────────────────────────────────────────┘
                 │
                 │ POST Requests (JSON)
                 ▼
┌─────────────────────────────────────────────────────────┐
│            API ENDPOINT: api/manage-team.php            │
│  • Action Router (add/edit/delete/get_all)             │
│  • Database Queries                                    │
│  • File Upload Handler                                │
│  • Error Management                                   │
└────────────────┬────────────────────────────────────────┘
                 │
                 │ SQL Operations
                 ▼
┌─────────────────────────────────────────────────────────┐
│            DATABASE: team_members Table                 │
│  • All team member data stored here                    │
│  • Auto-indexed for performance                        │
│  • Timestamps for tracking changes                     │
└────────────────┬────────────────────────────────────────┘
                 │
                 │ Data Query
                 ▼
┌─────────────────────────────────────────────────────────┐
│           FRONTEND: team.php                            │
│  • Fetches data from database on page load             │
│  • Renders responsive grid layout                      │
│  • Displays member cards with social links             │
│  • No manual updates needed                            │
└─────────────────────────────────────────────────────────┘
```

## API Endpoint Reference

### Base URL
```
POST /api/manage-team.php
```

### Actions & Request/Response

#### 1. GET_ALL - Retrieve All Team Members
```javascript
Request:
POST /api/manage-team.php
{
    "action": "get_all"
}

Response (Success):
{
    "success": true,
    "data": [
        {
            "id": 1,
            "name": "John Doe",
            "designation": "CEO",
            "image_path": "assets/img/team/team_1234567890.jpg",
            "twitter_url": "https://twitter.com/johndoe",
            "linkedin_url": "https://linkedin.com/in/johndoe",
            "created_at": "2025-01-15 10:30:00",
            "updated_at": "2025-01-15 10:30:00"
        },
        ...
    ]
}

Response (Error):
{
    "success": false,
    "message": "Error loading team members"
}
```

#### 2. ADD - Create New Team Member
```javascript
Request (FormData):
POST /api/manage-team.php
{
    "action": "add",
    "name": "Jane Smith",
    "designation": "Architect",
    "twitter_url": "https://twitter.com/janesmith",
    "linkedin_url": "https://linkedin.com/in/janesmith",
    "image": <File Object>
}

Response (Success):
{
    "success": true,
    "message": "Team member added successfully",
    "id": 7
}

Response (Error):
{
    "success": false,
    "message": "Invalid image file"
}
```

#### 3. EDIT - Update Existing Team Member
```javascript
Request (FormData):
POST /api/manage-team.php
{
    "action": "edit",
    "id": 1,
    "name": "John Updated",
    "designation": "Chief Executive Officer",
    "twitter_url": "https://twitter.com/updated",
    "linkedin_url": "https://linkedin.com/in/updated",
    "image": <File Object> // Optional
}

Response (Success):
{
    "success": true,
    "message": "Team member updated successfully"
}
```

#### 4. DELETE - Remove Team Member
```javascript
Request (FormData):
POST /api/manage-team.php
{
    "action": "delete",
    "id": 1
}

Response (Success):
{
    "success": true,
    "message": "Team member deleted successfully"
}

Response (Error):
{
    "success": false,
    "message": "Invalid ID"
}
```

## Frontend JavaScript Functions

### Core Functions

#### `loadTeamMembers()`
- Fetches all team members from API
- Called when team panel is clicked
- Handles loading and error states
```javascript
loadTeamMembers()
// Internally calls displayTeamMembers(data)
```

#### `displayTeamMembers(members)`
- Renders grid of team member cards
- Creates HTML for each member
- Attaches event listeners to buttons
- Shows "No members" message if empty

#### `openAddTeamModal()`
- Opens modal dialog for adding new member
- Displays form with fields:
  - Name (required)
  - Designation (required)
  - Twitter URL (optional)
  - LinkedIn URL (optional)
  - Image upload (required)
- Form validation on submit

#### `submitAddTeam(event)`
- Validates form input
- Creates FormData with image file
- Sends POST request to api/manage-team.php
- Reloads members on success
- Shows error message on failure

#### `openEditTeamModal(id, name, designation, image, twitter, linkedin)`
- Opens edit modal with pre-filled data
- Shows current member image
- Allows updating all fields
- Image update is optional

#### `submitEditTeam(event, id)`
- Validates form changes
- Sends update request with optional image
- Reloads members on success
- Preserves old image if not changed

#### `deleteTeamMember(id)`
- Shows confirmation dialog
- Sends DELETE action request
- Reloads members on success
- Shows error on failure

#### `htmlEscape(str)`
- Prevents XSS by escaping HTML characters
- Used for all user input display

#### `addSlashes(str)`
- Escapes single quotes in strings
- Used in JavaScript string handling

## Database Operations

### Table Creation
```sql
CREATE TABLE IF NOT EXISTS team_members (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    designation VARCHAR(100) NOT NULL,
    image_path VARCHAR(255),
    twitter_url VARCHAR(255),
    linkedin_url VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_created (created_at)
)
```
- Auto-executed when api/manage-team.php is first accessed
- Creates index for faster queries

### Default Data Initialization
When team.php loads, it checks if table is empty:
```php
if ($count_row['count'] == 0) {
    // Insert default team members
    INSERT INTO team_members VALUES
    (NULL, 'Jake Saper', 'CEO & Founder', 'assets/img/team/team_1_1.png', ...),
    (NULL, 'Mari Doly', 'Chief Architect', 'assets/img/team/team_1_2.png', ...),
    // ... more defaults
}
```
- Preserves original team.html data
- Only runs once on first load

## File Upload Handling

### Process Flow
```
1. User selects file in form
2. Form submits via AJAX
3. Server validates:
   - File type (MIME check)
   - File size (max 5MB)
   - Allowed formats: JPEG, PNG, GIF, WebP
4. Generate unique filename:
   - Format: team_[timestamp]_[random].ext
   - Example: team_1705343400_5678.jpg
5. Save to assets/img/team/ directory
6. Store path in database: assets/img/team/[filename]
7. Return success/error response
```

### Security Measures
- MIME type validation on server
- File extension validation
- File size limit enforcement
- Unique filename generation (prevents overwrites)
- Directory permissions check

### Image Cleanup
- Old image deleted on edit (if replaced)
- Image deleted on member deletion
- Prevents orphaned files
- Uses `unlink()` PHP function

## Responsive Design

### CSS Grid Layout
```css
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
```

### Breakpoints
- **Desktop**: Full width with multiple columns
- **Tablet**: Reduces column width
- **Mobile**: Single column view

### Card Components
Each team card displays:
- 200px height image with object-fit: cover
- Member name (16px, bold)
- Designation (13px, gold color)
- Social media icons (30px circles)
- Edit and Delete buttons

## Error Handling

### Admin Dashboard
- Toast messages for success/error
- Modal validation before submission
- Form field validation
- Server response error messages

### team.php
- Automatic table creation
- Default data initialization
- SQL error suppression
- Fallback to empty display

### API
- Session validation (admin check)
- Input validation (required fields)
- File validation (type, size)
- SQL injection prevention (prepared statements)
- Response formatting (JSON)

## Performance Optimization

### Database
- Indexed `created_at` for sorting
- Prepared statements prevent query issues
- Efficient SELECT * query (only what's needed)

### Frontend
- Single AJAX request for all members
- Grid layout uses CSS (no JS layout)
- Event delegation for buttons
- Minimal DOM manipulation

### Image Optimization
- Client-side file size validation
- Server-side MIME type check
- Automatic filename generation

## Security Checklist

✅ **Authentication**
- Session validation on every API call
- Admin-only access verified
- Prevents unauthorized modifications

✅ **File Handling**
- MIME type validation
- File size limits
- Filename sanitization
- Unique filename generation

✅ **Data Protection**
- Prepared statements (SQL injection prevention)
- HTML escaping on display (XSS prevention)
- CSRF protection via session

✅ **Error Messages**
- No sensitive database info exposed
- User-friendly error messages
- Console error logging for debugging

## Integration Points

1. **Session Management**: Uses existing `$_SESSION['user_id']` and `$_SESSION['user_role']`
2. **Database Connection**: Uses existing `config/db.php` connection
3. **Admin Dashboard**: Integrated as new panel in navigation
4. **Frontend**: team.php fetches on every page load
5. **File Storage**: Uses existing `assets/img/` directory structure

## Maintenance Notes

### Backup Recommendations
- Regular database backups
- Image file backups from `/assets/img/team/`

### Monitoring
- Track member count growth
- Monitor image storage usage
- Review error logs periodically

### Future Enhancements
- Add member search/filter
- Implement member grouping by department
- Add member detail pages
- Implement member status (active/inactive)
