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

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

// Handle actions
if ($_POST) {
    $action = $_POST['action'] ?? '';
    $application_id = intval($_POST['application_id'] ?? 0);
    
    if ($action === 'approve' && $application_id) {
        try {
            $db->beginTransaction();
            
            // Get application data
            $stmt = $db->prepare("SELECT * FROM coach_applications WHERE id = ? AND status = 'pending'");
            $stmt->execute([$application_id]);
            $app = $stmt->fetch();
            
            if ($app) {
                // Create user account
                $password = 'TempPass123!';
                $stmt = $db->prepare("INSERT INTO users (email, password_hash, first_name, last_name, status) VALUES (?, ?, ?, ?, 'active')");
                $stmt->execute([$app['email'], hw_hash_password($password), $app['first_name'], $app['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, $app['display_name'], $app['bio'], $app['expertise'], $app['hourly_rate'], $app['years_experience'], $app['profile_image_url']]);
                
                // Update application status
                $stmt = $db->prepare("UPDATE coach_applications SET status = 'approved', processed_at = NOW() WHERE id = ?");
                $stmt->execute([$application_id]);
                
                $db->commit();
                $message = "Application approved! Coach account created with temporary password: $password";
            }
        } catch (Exception $e) {
            $db->rollback();
            $error = "Error approving application: " . $e->getMessage();
        }
    }
    
    elseif ($action === 'reject' && $application_id) {
        try {
            $stmt = $db->prepare("UPDATE coach_applications SET status = 'rejected', processed_at = NOW() WHERE id = ?");
            $stmt->execute([$application_id]);
            $message = "Application rejected.";
        } catch (Exception $e) {
            $error = "Error rejecting application: " . $e->getMessage();
        }
    }
}

// Get applications
$stmt = $db->query("SELECT * FROM coach_applications ORDER BY created_at DESC");
$applications = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($applications as &$app) {
    $app['expertise'] = json_decode($app['expertise'] ?? '[]', true);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Coach Applications | 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>
            </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 hover:bg-emerald-700 text-emerald-100">
                    <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 bg-emerald-700 text-white">
                    <i class="fas fa-user-plus mr-3"></i>Coach Applications
                </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>
            </nav>
        </div>
        
        <!-- Main Content -->
        <div class="flex-1 p-8">
            <div class="mb-8">
                <h2 class="text-3xl font-bold text-gray-900">Coach Applications</h2>
                <p class="text-gray-600 mt-2">Review and approve new coach applications</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; ?>
            
            <!-- Applications List -->
            <div class="space-y-6">
                <?php foreach ($applications as $app): ?>
                <div class="bg-white rounded-lg shadow-lg overflow-hidden">
                    <div class="p-6">
                        <div class="flex items-start justify-between">
                            <div class="flex items-center space-x-4">
                                <img src="<?= $app['profile_image_url'] ?: 'https://i.pravatar.cc/100?u=' . urlencode($app['display_name']) ?>" 
                                     alt="<?= htmlspecialchars($app['display_name']) ?>" 
                                     class="w-16 h-16 rounded-full object-cover">
                                <div>
                                    <h3 class="text-xl font-semibold text-gray-900"><?= htmlspecialchars($app['display_name']) ?></h3>
                                    <p class="text-gray-600"><?= htmlspecialchars($app['first_name'] . ' ' . $app['last_name']) ?></p>
                                    <p class="text-sm text-gray-500"><?= htmlspecialchars($app['email']) ?></p>
                                </div>
                            </div>
                            
                            <div class="flex items-center space-x-2">
                                <span class="px-3 py-1 rounded-full text-sm font-medium
                                    <?= $app['status'] === 'pending' ? 'bg-yellow-100 text-yellow-800' : 
                                        ($app['status'] === 'approved' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800') ?>">
                                    <?= ucfirst($app['status']) ?>
                                </span>
                                <span class="text-sm text-gray-500"><?= date('M j, Y', strtotime($app['created_at'])) ?></span>
                            </div>
                        </div>
                        
                        <div class="mt-4 grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700">Experience</label>
                                <p class="text-sm text-gray-900"><?= $app['years_experience'] ?> years</p>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700">Hourly Rate</label>
                                <p class="text-sm text-gray-900">$<?= number_format($app['hourly_rate'], 2) ?></p>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700">Phone</label>
                                <p class="text-sm text-gray-900"><?= htmlspecialchars($app['phone'] ?: 'Not provided') ?></p>
                            </div>
                        </div>
                        
                        <div class="mt-4">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Expertise</label>
                            <div class="flex flex-wrap gap-2">
                                <?php foreach ($app['expertise'] as $skill): ?>
                                    <span class="bg-emerald-100 text-emerald-800 text-xs px-2 py-1 rounded"><?= htmlspecialchars($skill) ?></span>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        
                        <?php if ($app['certifications']): ?>
                        <div class="mt-4">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Certifications</label>
                            <p class="text-sm text-gray-600"><?= nl2br(htmlspecialchars($app['certifications'])) ?></p>
                        </div>
                        <?php endif; ?>
                        
                        <div class="mt-4">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Bio</label>
                            <p class="text-sm text-gray-600"><?= nl2br(htmlspecialchars($app['bio'])) ?></p>
                        </div>
                        
                        <?php if ($app['status'] === 'pending'): ?>
                        <div class="mt-6 flex space-x-3">
                            <form method="POST" class="inline">
                                <input type="hidden" name="action" value="approve">
                                <input type="hidden" name="application_id" value="<?= $app['id'] ?>">
                                <button type="submit" onclick="return confirm('Approve this application?')"
                                        class="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700">
                                    <i class="fas fa-check mr-2"></i>Approve
                                </button>
                            </form>
                            
                            <form method="POST" class="inline">
                                <input type="hidden" name="action" value="reject">
                                <input type="hidden" name="application_id" value="<?= $app['id'] ?>">
                                <button type="submit" onclick="return confirm('Reject this application?')"
                                        class="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700">
                                    <i class="fas fa-times mr-2"></i>Reject
                                </button>
                            </form>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
                
                <?php if (empty($applications)): ?>
                <div class="text-center py-12">
                    <i class="fas fa-inbox text-gray-400 text-6xl mb-4"></i>
                    <h3 class="text-lg font-medium text-gray-900 mb-2">No Applications Yet</h3>
                    <p class="text-gray-500">Coach applications will appear here when submitted.</p>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</body>
</html>