<?php
/**
 * Team Members Management
 */

session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/security.php';
require_once __DIR__ . '/includes/auth.php';

checkAdminAuth();

$pdo = getDBConnection();
$message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'create';
    $id = intval($_POST['id'] ?? 0);
    
    $name = sanitizeInput($_POST['name'] ?? '');
    $position = sanitizeInput($_POST['position'] ?? '');
    $bio = sanitizeInput($_POST['bio'] ?? '');
    $email = sanitizeInput($_POST['email'] ?? '');
    $linkedinUrl = sanitizeInput($_POST['linkedin_url'] ?? '');
    $displayOrder = intval($_POST['display_order'] ?? 0);
    $status = sanitizeInput($_POST['status'] ?? 'active');
    
    // Handle photo upload
    $photo = null;
    if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
        $allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
        if (in_array($_FILES['photo']['type'], $allowedTypes)) {
            $uploadDir = __DIR__ . '/../uploads/team/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            $extension = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
            $filename = uniqid() . '_' . time() . '.' . $extension;
            if (move_uploaded_file($_FILES['photo']['tmp_name'], $uploadDir . $filename)) {
                $photo = $filename;
            }
        }
    }
    
    if (empty($name) || empty($position)) {
        $message = 'Name and position are required.';
    } else {
        if ($action === 'create') {
            $stmt = $pdo->prepare("
                INSERT INTO team_members (name, position, bio, email, linkedin_url, photo, display_order, status)
                VALUES (:name, :position, :bio, :email, :linkedin, :photo, :order, :status)
            ");
            $stmt->execute([
                ':name' => $name, ':position' => $position, ':bio' => $bio,
                ':email' => $email, ':linkedin' => $linkedinUrl, ':photo' => $photo,
                ':order' => $displayOrder, ':status' => $status
            ]);
            $message = 'Team member added successfully!';
        } elseif ($action === 'update' && $id > 0) {
            if ($photo) {
                // Delete old photo
                $old = $pdo->prepare("SELECT photo FROM team_members WHERE id = :id");
                $old->execute([':id' => $id]);
                $oldPhoto = $old->fetchColumn();
                if ($oldPhoto) {
                    $file = __DIR__ . '/../uploads/team/' . $oldPhoto;
                    if (file_exists($file)) unlink($file);
                }
                $stmt = $pdo->prepare("
                    UPDATE team_members SET name = :name, position = :position, bio = :bio,
                    email = :email, linkedin_url = :linkedin, photo = :photo,
                    display_order = :order, status = :status WHERE id = :id
                ");
                $stmt->execute([
                    ':name' => $name, ':position' => $position, ':bio' => $bio,
                    ':email' => $email, ':linkedin' => $linkedinUrl, ':photo' => $photo,
                    ':order' => $displayOrder, ':status' => $status, ':id' => $id
                ]);
            } else {
                $stmt = $pdo->prepare("
                    UPDATE team_members SET name = :name, position = :position, bio = :bio,
                    email = :email, linkedin_url = :linkedin, display_order = :order, status = :status WHERE id = :id
                ");
                $stmt->execute([
                    ':name' => $name, ':position' => $position, ':bio' => $bio,
                    ':email' => $email, ':linkedin' => $linkedinUrl,
                    ':order' => $displayOrder, ':status' => $status, ':id' => $id
                ]);
            }
            $message = 'Team member updated successfully!';
        }
    }
}

// Handle delete
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $stmt = $pdo->prepare("SELECT photo FROM team_members WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $photo = $stmt->fetchColumn();
    if ($photo) {
        $file = __DIR__ . '/../uploads/team/' . $photo;
        if (file_exists($file)) unlink($file);
    }
    $pdo->prepare("DELETE FROM team_members WHERE id = :id")->execute([':id' => $id]);
    $message = 'Team member deleted successfully!';
}

// Get edit item
$editItem = null;
if (isset($_GET['edit'])) {
    $id = intval($_GET['edit']);
    $stmt = $pdo->prepare("SELECT * FROM team_members WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $editItem = $stmt->fetch();
}

// Get all team members
$teamMembers = $pdo->query("
    SELECT * FROM team_members ORDER BY display_order ASC, created_at DESC
")->fetchAll();

$pageTitle = 'Team Members';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - Admin Panel</title>
    <link rel="stylesheet" href="assets/admin-modern.css">
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>
    
    <div class="admin-main">
        <?php include 'includes/header-new.php'; ?>
        
        <div class="admin-container">
            <?php if ($message): ?>
                <div class="message success"><?php echo htmlspecialchars($message); ?></div>
            <?php endif; ?>
            
            <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 1.5rem;">
                <!-- Form -->
                <div class="card slide-up">
                    <div class="card-header">
                        <h3 class="card-title"><?php echo $editItem ? 'Edit' : 'Add'; ?> Team Member</h3>
                    </div>
                    <form method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="<?php echo $editItem ? 'update' : 'create'; ?>">
                        <?php if ($editItem): ?>
                            <input type="hidden" name="id" value="<?php echo $editItem['id']; ?>">
                        <?php endif; ?>
                        
                        <div class="form-group">
                            <label class="form-label">Name *</label>
                            <input type="text" name="name" class="form-control" 
                                   value="<?php echo htmlspecialchars($editItem['name'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Position *</label>
                            <input type="text" name="position" class="form-control" 
                                   value="<?php echo htmlspecialchars($editItem['position'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Bio</label>
                            <textarea name="bio" class="form-control" rows="4"><?php echo htmlspecialchars($editItem['bio'] ?? ''); ?></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Email</label>
                            <input type="email" name="email" class="form-control" 
                                   value="<?php echo htmlspecialchars($editItem['email'] ?? ''); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">LinkedIn URL</label>
                            <input type="url" name="linkedin_url" class="form-control" 
                                   value="<?php echo htmlspecialchars($editItem['linkedin_url'] ?? ''); ?>"
                                   placeholder="https://linkedin.com/in/...">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Photo</label>
                            <input type="file" name="photo" accept="image/*" class="form-control">
                            <?php if ($editItem && $editItem['photo']): ?>
                                <div style="margin-top: 0.5rem;">
                                    <img src="../uploads/team/<?php echo htmlspecialchars($editItem['photo']); ?>" 
                                         style="width: 100px; height: 100px; object-fit: cover; border-radius: 50%;">
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Display Order</label>
                            <input type="number" name="display_order" class="form-control" 
                                   value="<?php echo $editItem['display_order'] ?? 0; ?>" min="0">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-control">
                                <option value="active" <?php echo ($editItem['status'] ?? 'active') === 'active' ? 'selected' : ''; ?>>Active</option>
                                <option value="inactive" <?php echo ($editItem['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                            </select>
                        </div>
                        
                        <div style="display: flex; gap: 0.75rem;">
                            <button type="submit" class="btn btn-primary"><?php echo $editItem ? 'Update' : 'Create'; ?></button>
                            <?php if ($editItem): ?>
                                <a href="team.php" class="btn btn-secondary">Cancel</a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
                
                <!-- List -->
                <div class="card slide-up" style="animation-delay: 0.2s">
                    <div class="card-header">
                        <h3 class="card-title">Team Members</h3>
                    </div>
                    <div style="max-height: 600px; overflow-y: auto;">
                        <?php if (empty($teamMembers)): ?>
                            <p style="text-align: center; padding: 2rem; color: var(--text-secondary);">No team members yet</p>
                        <?php else: ?>
                            <?php foreach ($teamMembers as $member): ?>
                            <div style="padding: 1rem; border-bottom: 1px solid var(--border-color);">
                                <div style="display: flex; gap: 1rem; align-items: start;">
                                    <?php if ($member['photo']): ?>
                                        <img src="../uploads/team/<?php echo htmlspecialchars($member['photo']); ?>" 
                                             style="width: 80px; height: 80px; border-radius: 50%; object-fit: cover;">
                                    <?php else: ?>
                                        <div style="width: 80px; height: 80px; border-radius: 50%; background: linear-gradient(135deg, var(--primary-color), var(--secondary-color)); display: flex; align-items: center; justify-content: center; font-weight: 700; color: white; font-size: 1.5rem;">
                                            <?php echo strtoupper(substr($member['name'], 0, 1)); ?>
                                        </div>
                                    <?php endif; ?>
                                    <div style="flex: 1;">
                                        <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 0.5rem;">
                                            <div>
                                                <div style="font-weight: 600; color: var(--text-primary); font-size: 1.125rem;">
                                                    <?php echo htmlspecialchars($member['name']); ?>
                                                </div>
                                                <div style="font-size: 0.875rem; color: var(--text-secondary); margin-top: 0.25rem;">
                                                    <?php echo htmlspecialchars($member['position']); ?>
                                                </div>
                                            </div>
                                            <span class="badge badge-<?php echo $member['status'] === 'active' ? 'success' : 'danger'; ?>">
                                                <?php echo ucfirst($member['status']); ?>
                                            </span>
                                        </div>
                                        <?php if ($member['bio']): ?>
                                            <div style="font-size: 0.875rem; color: var(--text-secondary); margin-bottom: 0.5rem;">
                                                <?php echo htmlspecialchars(substr($member['bio'], 0, 150)); ?><?php echo strlen($member['bio']) > 150 ? '...' : ''; ?>
                                            </div>
                                        <?php endif; ?>
                                        <div style="display: flex; gap: 0.5rem; margin-top: 0.75rem;">
                                            <a href="?edit=<?php echo $member['id']; ?>" class="btn btn-sm btn-secondary">Edit</a>
                                            <a href="?delete=<?php echo $member['id']; ?>" 
                                               class="btn btn-sm btn-danger"
                                               onclick="return confirm('Delete this team member?')">Delete</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="assets/admin.js"></script>
</body>
</html>

