<?php
require_once __DIR__ . '/../api/lib.php';
hw_require_auth(['superadmin']);
$authUser = hw_get_auth_user();

$db = hw_db();
$message = '';
$error = '';

// Handle form submissions
if ($_POST) {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add_coach') {
        $email = trim($_POST['email'] ?? '');
        $first_name = trim($_POST['first_name'] ?? '');
        $last_name = trim($_POST['last_name'] ?? '');
        $display_name = trim($_POST['display_name'] ?? '');
        $bio = trim($_POST['bio'] ?? '');
        $expertise = $_POST['expertise'] ?? [];
        $hourly_rate = floatval($_POST['hourly_rate'] ?? 0);
        $years_experience = intval($_POST['years_experience'] ?? 0);
        
        // Handle image upload
        $profile_image_url = null;
        if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = __DIR__ . '/../uploads/coaches/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            $file_extension = strtolower(pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION));
            $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];
            
            if (in_array($file_extension, $allowed_extensions)) {
                $filename = uniqid() . '.' . $file_extension;
                $filepath = $upload_dir . $filename;
                
                if (move_uploaded_file($_FILES['profile_image']['tmp_name'], $filepath)) {
                    $profile_image_url = '/files/atasteofafricanmarketplace/uploads/coaches/' . $filename;
                }
            }
        }
        
        if ($email && $first_name && $last_name && $display_name) {
            try {
                $db->beginTransaction();
                
                // Create user account
                $password = 'TempPass123!';
                $stmt = $db->prepare("INSERT INTO users (email, password_hash, first_name, last_name, status) VALUES (?, ?, ?, ?, 'active')");
                $stmt->execute([$email, hw_hash_password($password), $first_name, $last_name]);
                $user_id = $db->lastInsertId();
                
                // Add coach role
                $stmt = $db->prepare("INSERT INTO user_roles (user_id, role_id) SELECT ?, id FROM roles WHERE name = 'coach'");
                $stmt->execute([$user_id]);
                
                // Create coach profile
                $stmt = $db->prepare("INSERT INTO coaches (user_id, display_name, bio, expertise, hourly_rate, years_experience, profile_image_url) VALUES (?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$user_id, $display_name, $bio, json_encode($expertise), $hourly_rate, $years_experience, $profile_image_url]);
                
                $db->commit();
                $message = "Coach added successfully! Temporary password: $password";
            } catch (Exception $e) {
                $db->rollback();
                $error = "Error adding coach: " . $e->getMessage();
            }
        } else {
            $error = "All required fields must be filled";
        }
    }
    
    elseif ($action === 'update_coach') {
        $coach_id = intval($_POST['coach_id'] ?? 0);
        $email = trim($_POST['email'] ?? '');
        $first_name = trim($_POST['first_name'] ?? '');
        $last_name = trim($_POST['last_name'] ?? '');
        $display_name = trim($_POST['display_name'] ?? '');
        $bio = trim($_POST['bio'] ?? '');
        $expertise = $_POST['expertise'] ?? [];
        $hourly_rate = floatval($_POST['hourly_rate'] ?? 0);
        $years_experience = intval($_POST['years_experience'] ?? 0);
        
        // Handle image upload
        $profile_image_url = null;
        if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = __DIR__ . '/../uploads/coaches/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            $file_extension = strtolower(pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION));
            $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];
            
            if (in_array($file_extension, $allowed_extensions)) {
                $filename = uniqid() . '.' . $file_extension;
                $filepath = $upload_dir . $filename;
                
                if (move_uploaded_file($_FILES['profile_image']['tmp_name'], $filepath)) {
                    $profile_image_url = '/files/atasteofafricanmarketplace/uploads/coaches/' . $filename;
                }
            }
        }
        
        if ($coach_id && $email && $first_name && $last_name && $display_name) {
            try {
                $db->beginTransaction();
                
                // Update user info
                $stmt = $db->prepare("UPDATE users u JOIN coaches c ON u.id = c.user_id SET u.email = ?, u.first_name = ?, u.last_name = ? WHERE c.id = ?");
                $stmt->execute([$email, $first_name, $last_name, $coach_id]);
                
                // Update coach profile
                if ($profile_image_url) {
                    $stmt = $db->prepare("UPDATE coaches SET display_name = ?, bio = ?, expertise = ?, hourly_rate = ?, years_experience = ?, profile_image_url = ? WHERE id = ?");
                    $stmt->execute([$display_name, $bio, json_encode($expertise), $hourly_rate, $years_experience, $profile_image_url, $coach_id]);
                } else {
                    $stmt = $db->prepare("UPDATE coaches SET display_name = ?, bio = ?, expertise = ?, hourly_rate = ?, years_experience = ? WHERE id = ?");
                    $stmt->execute([$display_name, $bio, json_encode($expertise), $hourly_rate, $years_experience, $coach_id]);
                }
                
                $db->commit();
                $message = "Coach updated successfully!";
            } catch (Exception $e) {
                $db->rollback();
                $error = "Error updating coach: " . $e->getMessage();
            }
        } else {
            $error = "All required fields must be filled";
        }
    }
    
    elseif ($action === 'reset_password') {
        $coach_id = intval($_POST['coach_id'] ?? 0);
        $new_password = trim($_POST['new_password'] ?? '');
        
        if ($coach_id && $new_password && strlen($new_password) >= 8) {
            try {
                // Get the user_id for this coach
                $stmt = $db->prepare("SELECT user_id FROM coaches WHERE id = ?");
                $stmt->execute([$coach_id]);
                $coach = $stmt->fetch();
                
                if ($coach) {
                    // Update the password
                    $stmt = $db->prepare("UPDATE users SET password_hash = ? WHERE id = ?");
                    $stmt->execute([hw_hash_password($new_password), $coach['user_id']]);
                    $message = "Password reset successfully! New password: " . htmlspecialchars($new_password);
                } else {
                    $error = "Coach not found";
                }
            } catch (Exception $e) {
                $error = "Error resetting password: " . $e->getMessage();
            }
        } else {
            $error = "Password must be at least 8 characters";
        }
    }
    
    elseif ($action === 'delete_coach') {
        $coach_id = intval($_POST['coach_id'] ?? 0);
        if ($coach_id) {
            try {
                $stmt = $db->prepare("DELETE FROM coaches WHERE id = ?");
                $stmt->execute([$coach_id]);
                $message = "Coach deleted successfully!";
            } catch (Exception $e) {
                $error = "Error deleting coach: " . $e->getMessage();
            }
        }
    }
}

// Get coach for editing
$edit_coach = null;
if (isset($_GET['edit'])) {
    $coach_id = intval($_GET['edit']);
    $stmt = $db->prepare("
        SELECT c.*, u.email, u.first_name, u.last_name 
        FROM coaches c 
        JOIN users u ON c.user_id = u.id 
        WHERE c.id = ?
    ");
    $stmt->execute([$coach_id]);
    $edit_coach = $stmt->fetch();
    if ($edit_coach) {
        $edit_coach['expertise'] = json_decode($edit_coach['expertise'] ?? '[]', true);
    }
}

// Get all coaches
$stmt = $db->query("
    SELECT c.*, u.email, u.first_name, u.last_name,
           COUNT(DISTINCT a.id) as total_appointments
    FROM coaches c 
    JOIN users u ON c.user_id = u.id 
    LEFT JOIN appointments a ON c.id = a.coach_id
    GROUP BY c.id
    ORDER BY c.created_at DESC
");
$coaches = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Format coach data
foreach ($coaches as &$coach) {
    $coach['expertise'] = json_decode($coach['expertise'] ?? '[]', true);
}

$expertise_options = ['Herbal Medicine', 'Nutrition', 'Wellness Coaching', 'Stress Management', 'Holistic Health', 'Aromatherapy', 'Mindfulness', 'Yoga', 'Meditation'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Coaches | Superadmin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body class="bg-gray-100">
    <div class="min-h-screen flex">
        <!-- Sidebar -->
        <div class="bg-emerald-800 text-white w-64 flex-shrink-0">
            <div class="p-6">
                <h1 class="text-xl font-bold">Superadmin Panel</h1>
                <p class="text-emerald-200 text-sm mt-1">Website Management</p>
            </div>
            
            <nav class="mt-6">
                <a href="/files/atasteofafricanmarketplace/superadmin/dashboard.php" class="flex items-center px-6 py-3 hover:bg-emerald-700 text-emerald-100">
                    <i class="fas fa-tachometer-alt mr-3"></i>
                    Dashboard
                </a>
                <a href="/files/atasteofafricanmarketplace/superadmin/coaches.php" class="flex items-center px-6 py-3 bg-emerald-700 text-white">
                    <i class="fas fa-users mr-3"></i>
                    Manage Coaches
                </a>
                <a href="/files/atasteofafricanmarketplace/superadmin/coach-applications.php" class="flex items-center px-6 py-3 hover:bg-emerald-700 text-emerald-100">
                    <i class="fas fa-user-plus mr-3"></i>
                    Coach Applications
                </a>
                <a href="/files/atasteofafricanmarketplace/superadmin/appointments.php" class="flex items-center px-6 py-3 hover:bg-emerald-700 text-emerald-100">
                    <i class="fas fa-calendar mr-3"></i>
                    Appointments
                </a>
                <a href="/files/atasteofafricanmarketplace/dashboard/admin/toa-wheel-management.php" class="flex items-center px-6 py-3 hover:bg-emerald-700 text-emerald-100">
                    <i class="fas fa-cog mr-3"></i>
                    TOA Wheel
                </a>
                <a href="/files/atasteofafricanmarketplace/superadmin/content.php" class="flex items-center px-6 py-3 hover:bg-emerald-700 text-emerald-100">
                    <i class="fas fa-edit mr-3"></i>
                    Website Content
                </a>
                
                <div class="border-t border-emerald-700 mt-6 pt-6">
                    <a href="/files/atasteofafricanmarketplace/api/auth/logout.php" class="flex items-center px-6 py-3 hover:bg-red-600 text-emerald-100">
                        <i class="fas fa-sign-out-alt mr-3"></i>
                        Logout
                    </a>
                </div>
            </nav>
        </div>
        
        <!-- Main Content -->
        <div class="flex-1 p-8">
            <div class="mb-8">
                <h2 class="text-3xl font-bold text-gray-900">Manage Coaches</h2>
                <p class="text-gray-600 mt-2">Add, edit, view, and manage coach profiles and emails</p>
            </div>
            
            <?php if ($message): ?>
                <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-6">
                    <?= htmlspecialchars($message) ?>
                </div>
            <?php endif; ?>
            
            <?php if ($error): ?>
                <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6">
                    <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>
            
            <!-- Coach Form -->
            <?php if ($edit_coach): ?>
                <div class="bg-white p-6 rounded-lg shadow mb-6">
                    <h3 class="text-lg font-semibold text-gray-900 mb-4">Edit Coach Profile</h3>
                    
                    <form method="POST" enctype="multipart/form-data" class="space-y-4">
                        <input type="hidden" name="action" value="update_coach">
                        <input type="hidden" name="coach_id" value="<?= $edit_coach['id'] ?>">
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Profile Picture</label>
                            <div class="flex items-center space-x-4">
                                <img src="<?= $edit_coach['profile_image_url'] ?: 'https://i.pravatar.cc/100?u=' . urlencode($edit_coach['display_name']) ?>" 
                                     alt="Current photo" class="w-16 h-16 rounded-full object-cover">
                                <input type="file" name="profile_image" accept="image/*" 
                                       class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-emerald-50 file:text-emerald-700 hover:file:bg-emerald-100">
                            </div>
                        </div>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Email</label>
                                <input type="email" name="email" value="<?= htmlspecialchars($edit_coach['email']) ?>" 
                                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500" required>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Display Name</label>
                                <input type="text" name="display_name" value="<?= htmlspecialchars($edit_coach['display_name']) ?>" 
                                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500" required>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">First Name</label>
                                <input type="text" name="first_name" value="<?= htmlspecialchars($edit_coach['first_name']) ?>" 
                                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500" required>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Last Name</label>
                                <input type="text" name="last_name" value="<?= htmlspecialchars($edit_coach['last_name']) ?>" 
                                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500" required>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Hourly Rate ($)</label>
                                <input type="number" name="hourly_rate" value="<?= $edit_coach['hourly_rate'] ?>" step="0.01" 
                                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500">
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Years Experience</label>
                                <input type="number" name="years_experience" value="<?= $edit_coach['years_experience'] ?>" 
                                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500">
                            </div>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Bio</label>
                            <textarea name="bio" rows="4" 
                                      class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500"><?= htmlspecialchars($edit_coach['bio']) ?></textarea>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Expertise (select multiple)</label>
                            <div class="grid grid-cols-2 md:grid-cols-3 gap-2">
                                <?php foreach ($expertise_options as $option): ?>
                                    <label class="flex items-center">
                                        <input type="checkbox" name="expertise[]" value="<?= htmlspecialchars($option) ?>" 
                                               <?= in_array($option, $edit_coach['expertise']) ? 'checked' : '' ?>
                                               class="mr-2 text-emerald-600">
                                        <span class="text-sm"><?= htmlspecialchars($option) ?></span>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        
                        <div class="flex gap-3">
                            <button type="submit" class="bg-emerald-600 text-white px-4 py-2 rounded hover:bg-emerald-700">
                                Update Coach
                            </button>
                            <a href="/files/atasteofafricanmarketplace/superadmin/coaches.php" class="bg-gray-500 text-white px-4 py-2 rounded hover:bg-gray-600">
                                Cancel
                            </a>
                        </div>
                    </form>
                    
                    <!-- Password Reset Section -->
                    <div class="mt-6 pt-6 border-t border-gray-200">
                        <h4 class="text-md font-semibold text-gray-900 mb-4 flex items-center">
                            <i class="fas fa-key text-red-600 mr-2"></i>
                            Reset Password
                        </h4>
                        <form method="POST" class="space-y-3" onsubmit="return confirmPasswordReset()">
                            <input type="hidden" name="action" value="reset_password">
                            <input type="hidden" name="coach_id" value="<?= $edit_coach['id'] ?>">
                            
                            <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                                <div class="flex">
                                    <div class="flex-shrink-0">
                                        <i class="fas fa-exclamation-triangle text-yellow-600"></i>
                                    </div>
                                    <div class="ml-3">
                                        <h5 class="text-sm font-medium text-yellow-800">Warning</h5>
                                        <p class="mt-1 text-sm text-yellow-700">
                                            This will reset the coach's password. Make sure to share the new password securely with them.
                                        </p>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="max-w-md">
                                <label class="block text-sm font-medium text-gray-700 mb-2">New Password</label>
                                <input type="text" name="new_password" id="new_password" 
                                       placeholder="Enter new password (min 8 characters)" 
                                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-red-500" 
                                       required minlength="8">
                                <p class="mt-1 text-xs text-gray-500">Password must be at least 8 characters long</p>
                            </div>
                            
                            <div class="flex gap-2">
                                <button type="submit" class="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700 flex items-center">
                                    <i class="fas fa-sync-alt mr-2"></i>
                                    Reset Password
                                </button>
                                <button type="button" onclick="generatePassword()" class="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 flex items-center">
                                    <i class="fas fa-random mr-2"></i>
                                    Generate Strong Password
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            <?php else: ?>
                <div class="bg-white p-6 rounded-lg shadow mb-6">
                    <h3 class="text-lg font-semibold text-gray-900 mb-4">Add New Coach</h3>
                    
                    <form method="POST" enctype="multipart/form-data" class="space-y-4">
                        <input type="hidden" name="action" value="add_coach">
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Profile Picture</label>
                            <input type="file" name="profile_image" accept="image/*" 
                                   class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-emerald-50 file:text-emerald-700 hover:file:bg-emerald-100">
                        </div>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Email</label>
                                <input type="email" name="email" 
                                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500" required>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Display Name</label>
                                <input type="text" name="display_name" 
                                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500" required>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">First Name</label>
                                <input type="text" name="first_name" 
                                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500" required>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Last Name</label>
                                <input type="text" name="last_name" 
                                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500" required>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Hourly Rate ($)</label>
                                <input type="number" name="hourly_rate" step="0.01" 
                                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500">
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Years Experience</label>
                                <input type="number" name="years_experience" 
                                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500">
                            </div>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Bio</label>
                            <textarea name="bio" rows="4" 
                                      class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500"></textarea>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Expertise (select multiple)</label>
                            <div class="grid grid-cols-2 md:grid-cols-3 gap-2">
                                <?php foreach ($expertise_options as $option): ?>
                                    <label class="flex items-center">
                                        <input type="checkbox" name="expertise[]" value="<?= htmlspecialchars($option) ?>" 
                                               class="mr-2 text-emerald-600">
                                        <span class="text-sm"><?= htmlspecialchars($option) ?></span>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        
                        <button type="submit" class="bg-emerald-600 text-white px-4 py-2 rounded hover:bg-emerald-700">
                            Add Coach
                        </button>
                    </form>
                </div>
            <?php endif; ?>
            
            <!-- Coaches List -->
            <div class="bg-white rounded-lg shadow overflow-hidden">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h3 class="text-lg font-semibold text-gray-900">All Coaches</h3>
                </div>
                
                <div class="overflow-x-auto">
                    <table class="min-w-full">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Coach</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Email</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Expertise</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Rate</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Appointments</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            <?php foreach ($coaches as $coach): ?>
                                <tr>
                                    <td class="px-6 py-4">
                                        <div class="flex items-center">
                                            <img src="<?= $coach['profile_image_url'] ?: 'https://i.pravatar.cc/100?u=' . urlencode($coach['display_name']) ?>" 
                                                 alt="<?= htmlspecialchars($coach['display_name']) ?>" 
                                                 class="w-10 h-10 rounded-full mr-3">
                                            <div>
                                                <div class="text-sm font-medium text-gray-900"><?= htmlspecialchars($coach['display_name']) ?></div>
                                                <div class="text-sm text-gray-500"><?= htmlspecialchars($coach['first_name'] . ' ' . $coach['last_name']) ?></div>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-900"><?= htmlspecialchars($coach['email']) ?></td>
                                    <td class="px-6 py-4">
                                        <div class="flex flex-wrap gap-1">
                                            <?php foreach (array_slice($coach['expertise'], 0, 2) as $skill): ?>
                                                <span class="inline-block bg-emerald-100 text-emerald-800 text-xs px-2 py-1 rounded">
                                                    <?= htmlspecialchars($skill) ?>
                                                </span>
                                            <?php endforeach; ?>
                                            <?php if (count($coach['expertise']) > 2): ?>
                                                <span class="text-xs text-gray-500">+<?= count($coach['expertise']) - 2 ?> more</span>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-900">$<?= number_format($coach['hourly_rate'], 2) ?></td>
                                    <td class="px-6 py-4 text-sm text-gray-900"><?= $coach['total_appointments'] ?></td>
                                    <td class="px-6 py-4 text-sm font-medium">
                                        <div class="flex gap-2">
                                            <button onclick="viewCoach(<?= $coach['id'] ?>)" 
                                                    class="text-blue-600 hover:text-blue-900">View</button>
                                            <a href="?edit=<?= $coach['id'] ?>" class="text-emerald-600 hover:text-emerald-900">Edit</a>
                                            <button onclick="openResetPasswordModal(<?= $coach['id'] ?>, '<?= htmlspecialchars($coach['display_name'], ENT_QUOTES) ?>')" 
                                                    class="text-orange-600 hover:text-orange-900">
                                                <i class="fas fa-key"></i>
                                            </button>
                                            <form method="POST" class="inline" onsubmit="return confirm('Delete this coach?')">
                                                <input type="hidden" name="action" value="delete_coach">
                                                <input type="hidden" name="coach_id" value="<?= $coach['id'] ?>">
                                                <button type="submit" class="text-red-600 hover:text-red-900">Delete</button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <!-- View Coach Modal -->
    <div id="viewModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden items-center justify-center z-50">
        <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full mx-4 max-h-screen overflow-y-auto">
            <div class="p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold text-gray-900">Coach Profile</h3>
                    <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600">
                        <span class="sr-only">Close</span>
                        <svg class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>
                <div id="modalContent"></div>
            </div>
        </div>
    </div>
    
    <!-- Reset Password Modal -->
    <div id="resetPasswordModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden items-center justify-center z-50">
        <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
            <div class="p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold text-gray-900">
                        <i class="fas fa-key text-orange-600 mr-2"></i>
                        Reset Password
                    </h3>
                    <button onclick="closeResetPasswordModal()" class="text-gray-400 hover:text-gray-600">
                        <span class="sr-only">Close</span>
                        <svg class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>
                
                <div class="bg-yellow-50 border-l-4 border-yellow-400 p-4 mb-4">
                    <div class="flex">
                        <i class="fas fa-exclamation-triangle text-yellow-400 mr-3 mt-1"></i>
                        <div>
                            <p class="text-sm text-yellow-700">
                                You are about to reset the password for <strong id="resetCoachName"></strong>.
                                Make sure to share the new password securely with them.
                            </p>
                        </div>
                    </div>
                </div>
                
                <form method="POST" id="resetPasswordForm">
                    <input type="hidden" name="action" value="reset_password">
                    <input type="hidden" name="coach_id" id="resetCoachId">
                    
                    <div class="mb-4">
                        <label for="new_password_modal" class="block text-sm font-medium text-gray-700 mb-2">
                            New Password
                        </label>
                        <input type="text" 
                               name="new_password" 
                               id="new_password_modal" 
                               minlength="8" 
                               required
                               placeholder="Enter new password (min 8 characters)"
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-orange-500">
                        <p class="text-xs text-gray-500 mt-1">Password must be at least 8 characters long</p>
                    </div>
                    
                    <div class="flex gap-2 mb-4">
                        <button type="button" 
                                onclick="generatePasswordForModal()" 
                                class="flex-1 bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 transition">
                            <i class="fas fa-random mr-2"></i>
                            Generate Strong Password
                        </button>
                    </div>
                    
                    <div class="flex gap-2">
                        <button type="button" 
                                onclick="closeResetPasswordModal()" 
                                class="flex-1 bg-gray-300 text-gray-700 px-4 py-2 rounded hover:bg-gray-400 transition">
                            Cancel
                        </button>
                        <button type="submit" 
                                class="flex-1 bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700 transition">
                            <i class="fas fa-sync-alt mr-2"></i>
                            Reset Password
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <script>
        const coaches = <?= json_encode($coaches) ?>;
        
        function generatePassword() {
            const length = 12;
            const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*";
            let password = "";
            
            // Ensure at least one of each type
            password += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[Math.floor(Math.random() * 26)];
            password += "abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random() * 26)];
            password += "0123456789"[Math.floor(Math.random() * 10)];
            password += "!@#$%^&*"[Math.floor(Math.random() * 8)];
            
            // Fill the rest
            for (let i = password.length; i < length; i++) {
                password += charset[Math.floor(Math.random() * charset.length)];
            }
            
            // Shuffle the password
            password = password.split('').sort(() => Math.random() - 0.5).join('');
            
            document.getElementById('new_password').value = password;
            
            // Copy to clipboard
            navigator.clipboard.writeText(password).then(() => {
                alert('Password generated and copied to clipboard!\\n\\nPassword: ' + password);
            }).catch(() => {
                alert('Password generated!\\n\\nPassword: ' + password);
            });
        }
        
        function confirmPasswordReset() {
            const password = document.getElementById('new_password').value;
            return confirm('Are you sure you want to reset this coach\\'s password?\\n\\nNew password: ' + password + '\\n\\nMake sure to share this password securely with the coach.');
        }
                function openResetPasswordModal(coachId, coachName) {
            document.getElementById('resetCoachId').value = coachId;
            document.getElementById('resetCoachName').textContent = coachName;
            document.getElementById('new_password_modal').value = '';
            document.getElementById('resetPasswordModal').classList.remove('hidden');
            document.getElementById('resetPasswordModal').classList.add('flex');
        }
        
        function closeResetPasswordModal() {
            document.getElementById('resetPasswordModal').classList.add('hidden');
            document.getElementById('resetPasswordModal').classList.remove('flex');
            document.getElementById('resetPasswordForm').reset();
        }
        
        function generatePasswordForModal() {
            const length = 12;
            const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*";
            let password = "";
            
            // Ensure at least one of each type
            password += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[Math.floor(Math.random() * 26)];
            password += "abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random() * 26)];
            password += "0123456789"[Math.floor(Math.random() * 10)];
            password += "!@#$%^&*"[Math.floor(Math.random() * 8)];
            
            // Fill the rest
            for (let i = password.length; i < length; i++) {
                password += charset[Math.floor(Math.random() * charset.length)];
            }
            
            // Shuffle the password
            password = password.split('').sort(() => Math.random() - 0.5).join('');
            
            document.getElementById('new_password_modal').value = password;
            
            // Copy to clipboard
            navigator.clipboard.writeText(password).then(() => {
                alert('Password generated and copied to clipboard!\\n\\nPassword: ' + password);
            }).catch(() => {
                alert('Password generated!\\n\\nPassword: ' + password);
            });
        }
        
        // Add form submit confirmation
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('resetPasswordForm');
            if (form) {
                form.addEventListener('submit', function(e) {
                    const password = document.getElementById('new_password_modal').value;
                    const coachName = document.getElementById('resetCoachName').textContent;
                    if (!confirm(`Reset password for ${coachName}?\\n\\nNew password: ${password}\\n\\nMake sure to share this securely with the coach.`)) {
                        e.preventDefault();
                    }
                });
            }
        });
                function viewCoach(coachId) {
            const coach = coaches.find(c => c.id == coachId);
            if (!coach) return;
            
            const content = `
                <div class="space-y-4">
                    <div class="flex items-center space-x-4">
                        <img src="${coach.profile_image_url || 'https://i.pravatar.cc/100?u=' + encodeURIComponent(coach.display_name)}" 
                             alt="${coach.display_name}" class="w-20 h-20 rounded-full">
                        <div>
                            <h4 class="text-xl font-semibold">${coach.display_name}</h4>
                            <p class="text-gray-600">${coach.first_name} ${coach.last_name}</p>
                            <p class="text-sm text-gray-500">${coach.email}</p>
                        </div>
                    </div>
                    
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Hourly Rate</label>
                            <p class="text-lg font-semibold text-emerald-600">$${parseFloat(coach.hourly_rate).toFixed(2)}</p>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Experience</label>
                            <p class="text-lg">${coach.years_experience} years</p>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Total Appointments</label>
                            <p class="text-lg">${coach.total_appointments}</p>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700">Member Since</label>
                            <p class="text-sm">${new Date(coach.created_at).toLocaleDateString()}</p>
                        </div>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Bio</label>
                        <p class="text-gray-600">${coach.bio || 'No bio provided'}</p>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Expertise</label>
                        <div class="flex flex-wrap gap-2">
                            ${coach.expertise.map(skill => `<span class="bg-emerald-100 text-emerald-800 text-sm px-3 py-1 rounded-full">${skill}</span>`).join('')}
                        </div>
                    </div>
                </div>
            `;
            
            document.getElementById('modalContent').innerHTML = content;
            document.getElementById('viewModal').classList.remove('hidden');
            document.getElementById('viewModal').classList.add('flex');
        }
        
        function closeModal() {
            document.getElementById('viewModal').classList.add('hidden');
            document.getElementById('viewModal').classList.remove('flex');
        }
    </script>
</body>
</html>