<?php
session_start();
require_once '../connection.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: ../admin-login.php');
    exit();
}

// Fetch admin data from admin_table
$admin_id = $_SESSION['admin_id'];
$query = "SELECT * FROM admin_table WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    session_destroy();
    header('Location: ../admin-login.php');
    exit();
}

$admin = $result->fetch_assoc();
$stmt->close();

// Handle form submission for adding/editing plan
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        // Add new plan
        if ($_POST['action'] === 'add') {
            $plan_name = mysqli_real_escape_string($conn, $_POST['plan_name']);
            $min_investment = floatval($_POST['min_investment']);
            $max_investment = floatval($_POST['max_investment']);
            $profit_percentage = floatval($_POST['profit_percentage']);
            $duration_days = intval($_POST['duration_days']);
            $description = mysqli_real_escape_string($conn, $_POST['description']);
            $features = isset($_POST['features']) ? json_encode(array_filter($_POST['features'])) : '[]';
            $status = $_POST['status'];
            
            // Handle image upload
            $image_url = '';
            if (isset($_FILES['plan_image']) && $_FILES['plan_image']['error'] === 0) {
                $allowed_types = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif'];
                $file_type = $_FILES['plan_image']['type'];
                
                if (in_array($file_type, $allowed_types)) {
                    $upload_dir = '../uploads/plans/';
                    if (!file_exists($upload_dir)) {
                        mkdir($upload_dir, 0777, true);
                    }
                    
                    $file_extension = pathinfo($_FILES['plan_image']['name'], PATHINFO_EXTENSION);
                    $file_name = uniqid() . '.' . $file_extension;
                    $target_path = $upload_dir . $file_name;
                    
                    if (move_uploaded_file($_FILES['plan_image']['tmp_name'], $target_path)) {
                        $image_url = 'uploads/plans/' . $file_name;
                    }
                }
            }
            
            $query = "INSERT INTO copy_trade_plans (plan_name, min_investment, max_investment, profit_percentage, duration_days, description, features, image_url, status) 
                      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($query);
            $stmt->bind_param("sddiissss", $plan_name, $min_investment, $max_investment, $profit_percentage, $duration_days, $description, $features, $image_url, $status);
            
            if ($stmt->execute()) {
                $message = "Copy trade plan added successfully!";
            } else {
                $error = "Error adding plan: " . $conn->error;
            }
            $stmt->close();
        }
        
        // Edit plan
        elseif ($_POST['action'] === 'edit' && isset($_POST['plan_id'])) {
            $plan_id = intval($_POST['plan_id']);
            $plan_name = mysqli_real_escape_string($conn, $_POST['plan_name']);
            $min_investment = floatval($_POST['min_investment']);
            $max_investment = floatval($_POST['max_investment']);
            $profit_percentage = floatval($_POST['profit_percentage']);
            $duration_days = intval($_POST['duration_days']);
            $description = mysqli_real_escape_string($conn, $_POST['description']);
            $features = isset($_POST['features']) ? json_encode(array_filter($_POST['features'])) : '[]';
            $status = $_POST['status'];
            
            // Handle image upload
            $image_url = $_POST['existing_image'] ?? '';
            if (isset($_FILES['plan_image']) && $_FILES['plan_image']['error'] === 0) {
                $allowed_types = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif'];
                $file_type = $_FILES['plan_image']['type'];
                
                if (in_array($file_type, $allowed_types)) {
                    $upload_dir = '../uploads/plans/';
                    if (!file_exists($upload_dir)) {
                        mkdir($upload_dir, 0777, true);
                    }
                    
                    // Delete old image if exists
                    if (!empty($image_url) && file_exists('../' . $image_url)) {
                        unlink('../' . $image_url);
                    }
                    
                    $file_extension = pathinfo($_FILES['plan_image']['name'], PATHINFO_EXTENSION);
                    $file_name = uniqid() . '.' . $file_extension;
                    $target_path = $upload_dir . $file_name;
                    
                    if (move_uploaded_file($_FILES['plan_image']['tmp_name'], $target_path)) {
                        $image_url = 'uploads/plans/' . $file_name;
                    }
                }
            }
            
            $query = "UPDATE copy_trade_plans SET 
                      plan_name = ?, 
                      min_investment = ?, 
                      max_investment = ?, 
                      profit_percentage = ?, 
                      duration_days = ?, 
                      description = ?, 
                      features = ?, 
                      image_url = ?, 
                      status = ? 
                      WHERE id = ?";
            
            $stmt = $conn->prepare($query);
            $stmt->bind_param("sddiissssi", $plan_name, $min_investment, $max_investment, $profit_percentage, $duration_days, $description, $features, $image_url, $status, $plan_id);
            
            if ($stmt->execute()) {
                $message = "Copy trade plan updated successfully!";
            } else {
                $error = "Error updating plan: " . $conn->error;
            }
            $stmt->close();
        }
    }
}

// Handle delete request
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $plan_id = intval($_GET['delete']);
    
    // Get image URL to delete file
    $query = "SELECT image_url FROM copy_trade_plans WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $plan_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($row = $result->fetch_assoc()) {
        if (!empty($row['image_url']) && file_exists('../' . $row['image_url'])) {
            unlink('../' . $row['image_url']);
        }
    }
    $stmt->close();
    
    // Delete plan
    $query = "DELETE FROM copy_trade_plans WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $plan_id);
    
    if ($stmt->execute()) {
        $message = "Copy trade plan deleted successfully!";
    } else {
        $error = "Error deleting plan: " . $conn->error;
    }
    $stmt->close();
}

// Fetch all copy trade plans
$plans_query = "SELECT * FROM copy_trade_plans ORDER BY id DESC";
$plans_result = $conn->query($plans_query);
$plans = [];
if ($plans_result) {
    while ($row = $plans_result->fetch_assoc()) {
        $row['features'] = json_decode($row['features'], true);
        $plans[] = $row;
    }
}

// Get plan for editing if requested
$edit_plan = null;
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $edit_id = intval($_GET['edit']);
    $query = "SELECT * FROM copy_trade_plans WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $edit_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $edit_plan = $result->fetch_assoc();
    if ($edit_plan) {
        $edit_plan['features'] = json_decode($edit_plan['features'], true);
    }
    $stmt->close();
}

// Get statistics for copy trade
$stats = [];

// Total plans
$stats['total_plans'] = count($plans);

// Active plans
$stats['active_plans'] = 0;
foreach ($plans as $plan) {
    if ($plan['status'] === 'active') {
        $stats['active_plans']++;
    }
}

// Total investments (if you have an investments table)
$query = "SELECT COUNT(*) as total_investments, SUM(amount) as total_amount FROM copy_trade_investments";
$result = $conn->query($query);
if ($result) {
    $investment_stats = $result->fetch_assoc();
    $stats['total_investments'] = $investment_stats['total_investments'] ?? 0;
    $stats['total_invested'] = $investment_stats['total_amount'] ?? 0;
} else {
    $stats['total_investments'] = 0;
    $stats['total_invested'] = 0;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Copy Trade Plans - Unify Grant Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: {
                            50: '#eff6ff',
                            100: '#dbeafe',
                            200: '#bfdbfe',
                            300: '#93c5fd',
                            400: '#60a5fa',
                            500: '#3b82f6',
                            600: '#2563eb',
                            700: '#1d4ed8',
                            800: '#1e40af',
                            900: '#1e3a8a',
                        }
                    },
                    fontFamily: {
                        'inter': ['Inter', 'system-ui', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }
        
        .sidebar {
            transition: all 0.3s ease;
        }
        
        .sidebar.collapsed {
            width: 70px;
        }
        
        .sidebar.collapsed .sidebar-text {
            display: none;
        }
        
        .sidebar.collapsed .logo-text {
            display: none;
        }
        
        .main-content {
            transition: all 0.3s ease;
        }
        
        .feature-tag {
            transition: all 0.2s ease;
        }
        
        .feature-tag:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }
        
        /* Mobile Responsive Styles */
        @media (max-width: 1024px) {
            .sidebar {
                transform: translateX(-100%);
                width: 280px;
                box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
            }

            .sidebar.active {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0 !important;
                width: 100%;
            }

            .main-content::before {
                content: '';
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                height: 70px;
                background: white;
                z-index: 40;
                box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
                display: block;
            }

            header.bg-white {
                position: relative;
                z-index: 45;
                padding-top: 20px;
                padding-bottom: 20px;
                margin-top: 70px;
                border-bottom: 1px solid #e5e7eb;
            }

            .hamburger-menu {
                position: fixed;
                top: 18px;
                left: 20px;
                z-index: 100;
                background: white;
                border: none;
                width: 40px;
                height: 40px;
                border-radius: 8px;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                gap: 4px;
                cursor: pointer;
                box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
                transition: all 0.3s ease;
            }

            .hamburger-menu span {
                display: block;
                width: 20px;
                height: 2px;
                background: #4b5563;
                transition: all 0.3s ease;
            }

            .hamburger-menu.active span:nth-child(1) {
                transform: rotate(45deg) translate(5px, 5px);
            }

            .hamburger-menu.active span:nth-child(2) {
                opacity: 0;
            }

            .hamburger-menu.active span:nth-child(3) {
                transform: rotate(-45deg) translate(7px, -6px);
            }

            .sidebar-overlay {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0, 0, 0, 0.5);
                z-index: 45;
                opacity: 0;
                visibility: hidden;
                transition: all 0.3s ease;
            }

            .sidebar-overlay.active {
                opacity: 1;
                visibility: visible;
            }
        }

        @media (min-width: 1025px) {
            .hamburger-menu,
            .sidebar-overlay {
                display: none !important;
            }
            
            .sidebar {
                transform: translateX(0) !important;
            }
        }

        .sidebar.collapsed .sidebar-text,
        .sidebar.collapsed .logo-text {
            display: none !important;
        }

        .sidebar,
        .main-content,
        .hamburger-menu,
        .sidebar-overlay {
            transition: all 0.3s ease;
        }
    </style>
</head>
<body class="bg-gray-50 font-inter">

<?php include("nav.php"); ?>

<div class="sidebar-overlay"></div>

<!-- Main Content -->
<div class="main-content ml-64">
    <button class="hamburger-menu">
        <span></span>
        <span></span>
        <span></span>
    </button>
    
    <!-- Header -->
    <header class="bg-white shadow-sm border-b border-gray-200 px-8 py-4">
        <div class="flex items-center justify-between">
            <div>
                <h2 class="text-2xl font-bold text-gray-800">Copy Trade Plans</h2>
                <p class="text-gray-600">Manage your copy trading investment plans</p>
            </div>
            
            <div class="flex items-center space-x-4">
                <!-- Add New Plan Button -->
                <button onclick="toggleAddModal()" class="flex items-center space-x-2 px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition">
                    <i class="fas fa-plus"></i>
                    <span>Add New Plan</span>
                </button>
                
                <!-- Export Button -->
                <button onclick="exportPlans()" class="flex items-center space-x-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition">
                    <i class="fas fa-download"></i>
                    <span>Export</span>
                </button>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <main class="p-8">
        <!-- Alert Messages -->
        <?php if ($message): ?>
        <div class="mb-6 bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-lg flex items-center justify-between">
            <div class="flex items-center">
                <i class="fas fa-check-circle mr-2"></i>
                <span><?php echo $message; ?></span>
            </div>
            <button onclick="this.parentElement.remove()" class="text-green-700">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <?php endif; ?>

        <?php if ($error): ?>
        <div class="mb-6 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-lg flex items-center justify-between">
            <div class="flex items-center">
                <i class="fas fa-exclamation-circle mr-2"></i>
                <span><?php echo $error; ?></span>
            </div>
            <button onclick="this.parentElement.remove()" class="text-red-700">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <?php endif; ?>

        <!-- Stats Grid -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <!-- Total Plans Card -->
            <div class="stat-card bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-lg transition">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Total Plans</p>
                        <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo $stats['total_plans']; ?></p>
                    </div>
                    <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-layer-group text-blue-600 text-xl"></i>
                    </div>
                </div>
                <div class="mt-4">
                    <a href="#" class="text-sm text-primary-600 hover:text-primary-800 font-medium">
                        View all plans →
                    </a>
                </div>
            </div>

            <!-- Active Plans Card -->
            <div class="stat-card bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-lg transition">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Active Plans</p>
                        <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo $stats['active_plans']; ?></p>
                    </div>
                    <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-check-circle text-green-600 text-xl"></i>
                    </div>
                </div>
                <div class="mt-4">
                    <span class="text-sm text-gray-500">
                        <?php echo $stats['total_plans'] > 0 ? round(($stats['active_plans'] / $stats['total_plans']) * 100, 1) : 0; ?>% active
                    </span>
                </div>
            </div>

            <!-- Total Investments Card -->
            <div class="stat-card bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-lg transition">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Total Investments</p>
                        <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo number_format($stats['total_investments']); ?></p>
                    </div>
                    <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-chart-line text-purple-600 text-xl"></i>
                    </div>
                </div>
                <div class="mt-4">
                    <a href="investments.php" class="text-sm text-primary-600 hover:text-primary-800 font-medium">
                        View investments →
                    </a>
                </div>
            </div>

            <!-- Total Invested Card -->
            <div class="stat-card bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-lg transition">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Total Invested</p>
                        <p class="text-3xl font-bold text-gray-800 mt-2">$<?php echo number_format($stats['total_invested'], 2); ?></p>
                    </div>
                    <div class="w-12 h-12 bg-yellow-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-dollar-sign text-yellow-600 text-xl"></i>
                    </div>
                </div>
                <div class="mt-4">
                    <span class="text-sm text-gray-500">Across all plans</span>
                </div>
            </div>
        </div>

        <!-- Plans List -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-lg font-semibold text-gray-800">Available Copy Trade Plans</h3>
                <div class="flex space-x-2">
                    <select id="filterStatus" onchange="filterPlans()" class="text-sm border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary-500">
                        <option value="all">All Plans</option>
                        <option value="active">Active</option>
                        <option value="inactive">Inactive</option>
                    </select>
                </div>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <?php if (empty($plans)): ?>
                <div class="lg:col-span-2 text-center py-12">
                    <div class="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fas fa-layer-group text-gray-400 text-3xl"></i>
                    </div>
                    <h4 class="text-lg font-medium text-gray-700 mb-2">No Copy Trade Plans Yet</h4>
                    <p class="text-gray-500 mb-4">Get started by creating your first copy trade plan</p>
                    <button onclick="toggleAddModal()" class="inline-flex items-center px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition">
                        <i class="fas fa-plus mr-2"></i>
                        Add Your First Plan
                    </button>
                </div>
                <?php else: ?>
                    <?php foreach ($plans as $plan): ?>
                    <div class="plan-card bg-white border border-gray-200 rounded-xl overflow-hidden hover:shadow-lg transition" data-status="<?php echo $plan['status']; ?>">
                        <?php if (!empty($plan['image_url'])): ?>
                        <div class="h-48 overflow-hidden">
                            <img src="../<?php echo htmlspecialchars($plan['image_url']); ?>" alt="<?php echo htmlspecialchars($plan['plan_name']); ?>" class="w-full h-full object-cover">
                        </div>
                        <?php endif; ?>
                        
                        <div class="p-6">
                            <div class="flex items-start justify-between mb-4">
                                <div>
                                    <h4 class="text-xl font-bold text-gray-800 mb-1"><?php echo htmlspecialchars($plan['plan_name']); ?></h4>
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium <?php echo $plan['status'] === 'active' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'; ?>">
                                        <i class="fas fa-circle text-[8px] mr-1"></i>
                                        <?php echo ucfirst($plan['status']); ?>
                                    </span>
                                </div>
                                <div class="flex space-x-2">
                                    <a href="?edit=<?php echo $plan['id']; ?>" class="text-blue-600 hover:text-blue-800" title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="?delete=<?php echo $plan['id']; ?>" class="text-red-600 hover:text-red-800" title="Delete" onclick="return confirm('Are you sure you want to delete this plan? This action cannot be undone.')">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </div>
                            </div>
                            
                            <p class="text-gray-600 text-sm mb-4"><?php echo nl2br(htmlspecialchars($plan['description'])); ?></p>
                            
                            <div class="grid grid-cols-2 gap-4 mb-4">
                                <div>
                                    <p class="text-sm text-gray-500">Min Investment</p>
                                    <p class="text-lg font-bold text-gray-800">$<?php echo number_format($plan['min_investment'], 2); ?></p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-500">Max Investment</p>
                                    <p class="text-lg font-bold text-gray-800">$<?php echo number_format($plan['max_investment'], 2); ?></p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-500">Profit Percentage</p>
                                    <p class="text-lg font-bold text-green-600"><?php echo $plan['profit_percentage']; ?>%</p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-500">Duration</p>
                                    <p class="text-lg font-bold text-gray-800"><?php echo $plan['duration_days']; ?> days</p>
                                </div>
                            </div>
                            
                            <?php if (!empty($plan['features'])): ?>
                            <div class="border-t border-gray-200 pt-4">
                                <p class="text-sm font-medium text-gray-700 mb-2">Features:</p>
                                <div class="flex flex-wrap gap-2">
                                    <?php foreach ($plan['features'] as $feature): ?>
                                    <?php if (!empty($feature)): ?>
                                    <span class="feature-tag inline-flex items-center px-2 py-1 bg-primary-50 text-primary-700 text-xs rounded-md">
                                        <i class="fas fa-check-circle mr-1 text-primary-500"></i>
                                        <?php echo htmlspecialchars($feature); ?>
                                    </span>
                                    <?php endif; ?>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php endif; ?>
                           
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </main>
</div>

<!-- Add/Edit Plan Modal -->
<div id="planModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 <?php echo isset($edit_plan) ? '' : 'hidden'; ?>">
    <div class="relative top-20 mx-auto p-5 border w-full max-w-4xl shadow-lg rounded-lg bg-white">
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-xl font-bold text-gray-800">
                <i class="fas fa-copy mr-2 text-primary-600"></i>
                <?php echo isset($edit_plan) ? 'Edit' : 'Add New'; ?> Copy Trade Plan
            </h3>
            <button onclick="toggleAddModal()" class="text-gray-400 hover:text-gray-600">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>

        <form method="POST" enctype="multipart/form-data" class="space-y-4">
            <input type="hidden" name="action" value="<?php echo isset($edit_plan) ? 'edit' : 'add'; ?>">
            <?php if (isset($edit_plan)): ?>
            <input type="hidden" name="plan_id" value="<?php echo $edit_plan['id']; ?>">
            <input type="hidden" name="existing_image" value="<?php echo htmlspecialchars($edit_plan['image_url'] ?? ''); ?>">
            <?php endif; ?>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Expert's Name *</label>
                    <input type="text" name="plan_name" required 
                           value="<?php echo isset($edit_plan) ? htmlspecialchars($edit_plan['plan_name']) : ''; ?>"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                    <select name="status" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500">
                        <option value="active" <?php echo (isset($edit_plan) && $edit_plan['status'] == 'active') ? 'selected' : ''; ?>>Active</option>
                        <option value="inactive" <?php echo (isset($edit_plan) && $edit_plan['status'] == 'inactive') ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Minimum Investment ($) *</label>
                    <input type="number" name="min_investment" required step="0.01" min="0"
                           value="<?php echo isset($edit_plan) ? $edit_plan['min_investment'] : ''; ?>"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Maximum Investment ($) *</label>
                    <input type="number" name="max_investment" required step="0.01" min="0"
                           value="<?php echo isset($edit_plan) ? $edit_plan['max_investment'] : ''; ?>"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Profit Percentage (%) *</label>
                    <input type="number" name="profit_percentage" required step="0.01" min="0" max="100"
                           value="<?php echo isset($edit_plan) ? $edit_plan['profit_percentage'] : ''; ?>"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Duration (Days) *</label>
                    <input type="number" name="duration_days" required min="1"
                           value="<?php echo isset($edit_plan) ? $edit_plan['duration_days'] : ''; ?>"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500">
                </div>
                
                <div class="md:col-span-2">
                    <label class="block text-sm font-medium text-gray-700 mb-1">Plan Image</label>
                    <?php if (isset($edit_plan) && !empty($edit_plan['image_url'])): ?>
                    <div class="mb-2">
                        <img src="../<?php echo htmlspecialchars($edit_plan['image_url']); ?>" alt="Current plan image" class="h-20 w-20 object-cover rounded-lg">
                    </div>
                    <?php endif; ?>
                    <input type="file" name="plan_image" accept="image/*"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500">
                    <p class="text-xs text-gray-500 mt-1">Recommended size: 800x400px. Max file size: 2MB</p>
                </div>
                
                <div class="md:col-span-2">
                    <label class="block text-sm font-medium text-gray-700 mb-1">Description *</label>
                    <textarea name="description" required rows="3"
                              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"><?php echo isset($edit_plan) ? htmlspecialchars($edit_plan['description']) : ''; ?></textarea>
                </div>
                
                <div class="md:col-span-2">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Features (Click + to add features)</label>
                    <div id="features-container" class="space-y-2">
                        <?php
                        $features = isset($edit_plan) && !empty($edit_plan['features']) ? $edit_plan['features'] : [''];
                        foreach ($features as $index => $feature):
                        ?>
                        <div class="flex items-center space-x-2 feature-row">
                            <input type="text" name="features[]" value="<?php echo htmlspecialchars($feature ?? ''); ?>" 
                                   placeholder="e.g., 24/7 Support" 
                                   class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500">
                            <button type="button" onclick="addFeature(this)" class="text-green-600 hover:text-green-800">
                                <i class="fas fa-plus-circle text-xl"></i>
                            </button>
                            <button type="button" onclick="removeFeature(this)" class="text-red-600 hover:text-red-800 <?php echo $index === 0 ? 'hidden' : ''; ?>">
                                <i class="fas fa-minus-circle text-xl"></i>
                            </button>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            
            <div class="flex justify-end space-x-3 pt-4 border-t border-gray-200">
                <button type="button" onclick="toggleAddModal()" 
                        class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition">
                    Cancel
                </button>
                <button type="submit" 
                        class="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition">
                    <?php echo isset($edit_plan) ? 'Update Plan' : 'Add Plan'; ?>
                </button>
            </div>
        </form>
    </div>
</div>

<!-- JavaScript -->
<script>
    // Toggle sidebar
    function toggleSidebar() {
        const sidebar = document.querySelector('.sidebar');
        const mainContent = document.querySelector('.main-content');
        sidebar.classList.toggle('collapsed');
        mainContent.classList.toggle('ml-64');
        mainContent.classList.toggle('ml-20');
    }

    // Toggle add/edit modal
    function toggleAddModal() {
        const modal = document.getElementById('planModal');
        modal.classList.toggle('hidden');
        
        // Remove edit parameter from URL if modal is closed
        if (modal.classList.contains('hidden') && window.location.search.includes('edit=')) {
            window.location.href = 'copytrade-plans.php';
        }
    }

    // Add feature input field
    function addFeature(button) {
        const container = document.getElementById('features-container');
        const newRow = document.createElement('div');
        newRow.className = 'flex items-center space-x-2 feature-row';
        newRow.innerHTML = `
            <input type="text" name="features[]" placeholder="e.g., 24/7 Support" 
                   class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500">
            <button type="button" onclick="addFeature(this)" class="text-green-600 hover:text-green-800">
                <i class="fas fa-plus-circle text-xl"></i>
            </button>
            <button type="button" onclick="removeFeature(this)" class="text-red-600 hover:text-red-800">
                <i class="fas fa-minus-circle text-xl"></i>
            </button>
        `;
        container.appendChild(newRow);
    }

    // Remove feature input field
    function removeFeature(button) {
        const row = button.closest('.feature-row');
        if (document.querySelectorAll('.feature-row').length > 1) {
            row.remove();
        }
    }

    // Filter plans by status
    function filterPlans() {
        const status = document.getElementById('filterStatus').value;
        const plans = document.querySelectorAll('.plan-card');
        
        plans.forEach(plan => {
            if (status === 'all' || plan.dataset.status === status) {
                plan.style.display = 'block';
            } else {
                plan.style.display = 'none';
            }
        });
    }

    // Export plans data
    function exportPlans() {
        const plans = <?php echo json_encode($plans); ?>;
        const dataStr = JSON.stringify(plans, null, 2);
        const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
        
        const exportFileDefaultName = 'copy-trade-plans-' + new Date().toISOString().slice(0,10) + '.json';
        
        const linkElement = document.createElement('a');
        linkElement.setAttribute('href', dataUri);
        linkElement.setAttribute('download', exportFileDefaultName);
        linkElement.click();
    }

    // View plan details (placeholder for performance view)
    function viewPlanDetails(planId) {
        alert('Viewing performance for plan ID: ' + planId + ' (Feature coming soon)');
        // Redirect to plan performance page
        // window.location.href = 'plan-performance.php?id=' + planId;
    }

    // Duplicate plan
    function duplicatePlan(planId) {
        if (confirm('Create a copy of this plan?')) {
            // Implement duplication logic
            alert('Duplication feature coming soon!');
        }
    }

    // Mobile menu handling
    const hamburgerMenu = document.querySelector('.hamburger-menu');
    const sidebar = document.querySelector('.sidebar');
    const overlay = document.querySelector('.sidebar-overlay');

    if (hamburgerMenu) {
        hamburgerMenu.addEventListener('click', function() {
            sidebar.classList.toggle('active');
            this.classList.toggle('active');
            overlay.classList.toggle('active');
        });
    }

    if (overlay) {
        overlay.addEventListener('click', function() {
            sidebar.classList.remove('active');
            hamburgerMenu.classList.remove('active');
            this.classList.remove('active');
        });
    }

    // Close sidebar when clicking on links (for mobile)
    const sidebarLinks = document.querySelectorAll('.sidebar a');
    sidebarLinks.forEach(link => {
        link.addEventListener('click', function() {
            if (window.innerWidth <= 1024) {
                sidebar.classList.remove('active');
                hamburgerMenu.classList.remove('active');
                overlay.classList.remove('active');
            }
        });
    });

    // Show modal if edit parameter is present
    window.addEventListener('load', function() {
        if (window.location.search.includes('edit=')) {
            document.getElementById('planModal').classList.remove('hidden');
        }
    });
</script>

</body>
</html>