<?php
session_start();
require_once __DIR__ . '/../api/lib.php';
require_once __DIR__ . '/../partials/admin-sidebar.php';

// Simple admin check
if (!isset($_SESSION['user_id'])) {
    header('Location: /files/atasteofafricanmarketplace/superadmin-login.php');
    exit;
}

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

// Handle form submissions
if ($_POST) {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add_member') {
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $service_id = intval($_POST['service_id'] ?? 0);
        $membership_type = $_POST['membership_type'] ?? 'basic';
        
        if ($name && $email && $service_id) {
            try {
                $stmt = $db->prepare("INSERT INTO toa_members (name, email, phone, service_id, membership_type, status) VALUES (?, ?, ?, ?, ?, 'active')");
                $stmt->execute([$name, $email, $phone, $service_id, $membership_type]);
                $message = "Member added successfully!";
            } catch (Exception $e) {
                $error = "Error adding member: " . $e->getMessage();
            }
        } else {
            $error = "Name, email, and service are required.";
        }
    }
    
    elseif ($action === 'update_status') {
        $member_id = intval($_POST['member_id'] ?? 0);
        $status = $_POST['status'] ?? '';
        
        if ($member_id && $status) {
            try {
                $stmt = $db->prepare("UPDATE toa_members SET status = ? WHERE id = ?");
                $stmt->execute([$status, $member_id]);
                $message = "Member status updated!";
            } catch (Exception $e) {
                $error = "Error updating status: " . $e->getMessage();
            }
        }
    }
}

// Get services for dropdown
$services = $db->query("SELECT * FROM toa_wheel_services ORDER BY display_order")->fetchAll(PDO::FETCH_ASSOC);

// Get members
$members = $db->query("
    SELECT m.*, s.service_name 
    FROM toa_members m 
    JOIN toa_wheel_services s ON m.service_id = s.id 
    ORDER BY m.created_at DESC
")->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TOA Wellness Wheel Members | Admin</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 -->
        <?php renderAdminSidebar('toa-members'); ?>
        
        <!-- Main Content -->
        <div class="flex-1 p-8">
            <div class="mb-8">
                <h2 class="text-3xl font-bold text-gray-900">TOA Wellness Wheel Members</h2>
                <p class="text-gray-600 mt-2">Manage business & financial empowerment members</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; ?>
            
            <!-- Add Member Form -->
            <div class="bg-white p-6 rounded-lg shadow mb-6">
                <h3 class="text-lg font-semibold mb-4">Add New Member</h3>
                <form method="POST" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4 items-end">
                    <input type="hidden" name="action" value="add_member">
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Name</label>
                        <input type="text" name="name" required class="w-full px-3 py-2 border border-gray-300 rounded-md">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Email</label>
                        <input type="email" name="email" required class="w-full px-3 py-2 border border-gray-300 rounded-md">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Phone</label>
                        <input type="tel" name="phone" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Service</label>
                        <select name="service_id" required class="w-full px-3 py-2 border border-gray-300 rounded-md">
                            <option value="">Select Service</option>
                            <?php foreach ($services as $service): ?>
                                <option value="<?= $service['id'] ?>"><?= htmlspecialchars($service['service_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Membership</label>
                        <select name="membership_type" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                            <option value="basic">Basic</option>
                            <option value="premium">Premium</option>
                            <option value="enterprise">Enterprise</option>
                        </select>
                    </div>
                    
                    <button type="submit" class="bg-emerald-600 text-white px-4 py-2 rounded hover:bg-emerald-700">
                        Add Member
                    </button>
                </form>
            </div>
            
            <!-- Members 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 Members (<?= count($members) ?>)</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">Member</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Service</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Membership</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Joined</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 ($members as $member): ?>
                                <tr>
                                    <td class="px-6 py-4">
                                        <div>
                                            <div class="text-sm font-medium text-gray-900"><?= htmlspecialchars($member['name']) ?></div>
                                            <div class="text-sm text-gray-500"><?= htmlspecialchars($member['email']) ?></div>
                                            <?php if ($member['phone']): ?>
                                                <div class="text-xs text-gray-400"><?= htmlspecialchars($member['phone']) ?></div>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-900"><?= htmlspecialchars($member['service_name']) ?></td>
                                    <td class="px-6 py-4">
                                        <span class="px-2 py-1 text-xs font-semibold rounded-full
                                            <?= $member['membership_type'] === 'enterprise' ? 'bg-purple-100 text-purple-800' : 
                                                ($member['membership_type'] === 'premium' ? 'bg-blue-100 text-blue-800' : 'bg-gray-100 text-gray-800') ?>">
                                            <?= ucfirst($member['membership_type']) ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4">
                                        <span class="px-2 py-1 text-xs font-semibold rounded-full
                                            <?= $member['status'] === 'active' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800' ?>">
                                            <?= ucfirst($member['status']) ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-500"><?= date('M j, Y', strtotime($member['created_at'])) ?></td>
                                    <td class="px-6 py-4 text-sm font-medium">
                                        <form method="POST" class="inline-block">
                                            <input type="hidden" name="action" value="update_status">
                                            <input type="hidden" name="member_id" value="<?= $member['id'] ?>">
                                            <select name="status" onchange="this.form.submit()" class="text-sm border rounded px-2 py-1">
                                                <option value="active" <?= $member['status'] === 'active' ? 'selected' : '' ?>>Active</option>
                                                <option value="inactive" <?= $member['status'] === 'inactive' ? 'selected' : '' ?>>Inactive</option>
                                                <option value="suspended" <?= $member['status'] === 'suspended' ? 'selected' : '' ?>>Suspended</option>
                                            </select>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <?php if (empty($members)): ?>
                <div class="text-center py-12">
                    <i class="fas fa-users text-gray-400 text-6xl mb-4"></i>
                    <h3 class="text-lg font-medium text-gray-900 mb-2">No Members Yet</h3>
                    <p class="text-gray-500">TOA Wellness Wheel members will appear here.</p>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</body>
</html>