<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: admin_login.php");
    exit();
}
require_once 'db.php';

// Handle plan updates
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] == 'update_plan') {
        $plan_id = intval($_POST['plan_id']);
        $name = mysqli_real_escape_string($conn, $_POST['name']);
        $min_amount = floatval($_POST['min_amount']);
        $max_amount = floatval($_POST['max_amount']);
        $roi = floatval($_POST['roi']);
        $duration_days = intval($_POST['duration_days']);
        $return_type = mysqli_real_escape_string($conn, $_POST['return_type']);
        $status = mysqli_real_escape_string($conn, $_POST['status']);
        
        $update_query = "UPDATE investment_plans SET 
            name = '$name',
            min_amount = $min_amount,
            max_amount = $max_amount,
            roi_percentage = $roi,
            duration_days = $duration_days,
            return_type = '$return_type',
            status = '$status',
            updated_at = NOW()
            WHERE id = $plan_id";
        
        if (mysqli_query($conn, $update_query)) {
            $success = "Plan updated successfully!";
        } else {
            $error = "Failed to update plan: " . mysqli_error($conn);
        }
    } elseif ($_POST['action'] == 'add_plan') {
        $name = mysqli_real_escape_string($conn, $_POST['name']);
        $min_amount = floatval($_POST['min_amount']);
        $max_amount = floatval($_POST['max_amount']);
        $roi = floatval($_POST['roi']);
        $duration_days = intval($_POST['duration_days']);
        $return_type = mysqli_real_escape_string($conn, $_POST['return_type']);
        
        $insert_query = "INSERT INTO investment_plans 
            (name, min_amount, max_amount, roi_percentage, duration_days, return_type, status) 
            VALUES ('$name', $min_amount, $max_amount, $roi, $duration_days, '$return_type', 'active')";
        
        if (mysqli_query($conn, $insert_query)) {
            $success = "New plan added successfully!";
        } else {
            $error = "Failed to add plan: " . mysqli_error($conn);
        }
    } elseif ($_POST['action'] == 'delete_plan') {
        $plan_id = intval($_POST['plan_id']);
        
        // Check if plan has active investments
        $check_query = "SELECT COUNT(*) as count FROM investments WHERE plan_id = $plan_id AND status = 'active'";
        $check_result = mysqli_query($conn, $check_query);
        $check_data = mysqli_fetch_assoc($check_result);
        
        if ($check_data['count'] > 0) {
            $error = "Cannot delete plan with active investments!";
        } else {
            $delete_query = "DELETE FROM investment_plans WHERE id = $plan_id";
            if (mysqli_query($conn, $delete_query)) {
                $success = "Plan deleted successfully!";
            } else {
                $error = "Failed to delete plan: " . mysqli_error($conn);
            }
        }
    }
}

// Get all plans
$plans_query = "SELECT * FROM investment_plans ORDER BY min_amount ASC";
$plans_result = mysqli_query($conn, $plans_query);

// Get statistics
$stats_query = "SELECT 
    (SELECT COUNT(*) FROM investment_plans WHERE status = 'active') as active_plans,
    (SELECT COUNT(*) FROM investment_plans WHERE status = 'inactive') as inactive_plans,
    (SELECT COUNT(*) FROM investments WHERE status = 'active') as active_investments,
    (SELECT SUM(amount) FROM investments WHERE status = 'active') as total_invested";
$stats_result = mysqli_query($conn, $stats_query);
$stats = mysqli_fetch_assoc($stats_result);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Plans - Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            background-color: #000;
            color: #fff;
            font-family: Arial, sans-serif;
            font-size: 13px;
        }
        .header {
            background: #111;
            padding: 12px 15px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.5);
            position: sticky;
            top: 0;
            z-index: 100;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .header-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .header h1 {
            color: #fff;
            font-size: 18px;
        }
        .back-btn {
            color: #FFD700;
            text-decoration: none;
            font-size: 20px;
        }
        .logout-btn {
            background: #f87171;
            color: #fff;
            padding: 8px 15px;
            border-radius: 5px;
            text-decoration: none;
            font-size: 12px;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        .container {
            padding: 12px;
            max-width: 1200px;
            margin: 0 auto;
        }
        .alert {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 12px;
            font-size: 12px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .alert-success {
            background: #1a4d1a;
            border: 1px solid #2d7a2d;
            color: #4ade80;
        }
        .alert-error {
            background: #4d1a1a;
            border: 1px solid #7a2d2d;
            color: #f87171;
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 10px;
            margin-bottom: 15px;
        }
        .stat-card {
            background: #111;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
            border: 1px solid #333;
        }
        .stat-number {
            font-size: 24px;
            font-weight: bold;
            color: #FFD700;
            margin-bottom: 5px;
        }
        .stat-label {
            color: #888;
            font-size: 11px;
        }
        .add-plan-btn {
            background: #FFD700;
            color: #000;
            padding: 12px 20px;
            border-radius: 8px;
            border: none;
            font-weight: bold;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            width: 100%;
            margin-bottom: 15px;
            font-size: 13px;
        }
        .add-plan-btn:hover {
            background: #FFA500;
        }
        .plans-list {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        .plan-card {
            background: #111;
            border-radius: 10px;
            padding: 15px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
            border: 2px solid #333;
        }
        .plan-card.inactive {
            opacity: 0.6;
            border-color: #666;
        }
        .plan-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
        }
        .plan-name {
            font-size: 16px;
            font-weight: bold;
            color: #FFD700;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .plan-status {
            padding: 5px 10px;
            border-radius: 5px;
            font-size: 10px;
            font-weight: bold;
            text-transform: uppercase;
        }
        .status-active {
            background: #4ade80;
            color: #000;
        }
        .status-inactive {
            background: #666;
            color: #fff;
        }
        .plan-details {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 8px;
            margin-bottom: 12px;
        }
        .detail-item {
            background: #000;
            padding: 8px;
            border-radius: 5px;
            font-size: 11px;
        }
        .detail-label {
            color: #888;
            display: block;
            margin-bottom: 3px;
        }
        .detail-value {
            color: #fff;
            font-weight: bold;
            font-size: 13px;
        }
        .return-badge {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 3px;
            font-size: 10px;
            font-weight: bold;
        }
        .return-fixed {
            background: #3b82f6;
            color: #fff;
        }
        .return-flexible {
            background: #10b981;
            color: #fff;
        }
        .plan-actions {
            display: flex;
            gap: 8px;
            margin-top: 12px;
        }
        .btn {
            flex: 1;
            padding: 10px;
            border: none;
            border-radius: 5px;
            font-weight: bold;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 5px;
            font-size: 11px;
        }
        .btn-edit {
            background: #3b82f6;
            color: #fff;
        }
        .btn-delete {
            background: #f87171;
            color: #fff;
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.9);
            overflow-y: auto;
        }
        .modal-content {
            background: #111;
            margin: 20px auto;
            padding: 20px;
            border-radius: 10px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 4px 20px rgba(255, 215, 0, 0.3);
            border: 1px solid #FFD700;
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .modal-title {
            color: #FFD700;
            font-size: 18px;
        }
        .close {
            color: #fff;
            font-size: 28px;
            cursor: pointer;
            line-height: 20px;
        }
        .close:hover {
            color: #FFD700;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-label {
            display: block;
            color: #888;
            font-size: 11px;
            margin-bottom: 5px;
        }
        input, select {
            width: 100%;
            padding: 10px;
            background: #000;
            border: 1px solid #333;
            border-radius: 5px;
            color: #fff;
            font-size: 13px;
        }
        input:focus, select:focus {
            outline: none;
            border-color: #FFD700;
        }
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
        }
        .submit-btn {
            width: 100%;
            padding: 12px;
            background: #FFD700;
            color: #000;
            border: none;
            border-radius: 5px;
            font-weight: bold;
            cursor: pointer;
            font-size: 13px;
            margin-top: 10px;
        }
        .submit-btn:hover {
            background: #FFA500;
        }
        .info-box {
            background: #000;
            border: 1px solid #333;
            border-radius: 5px;
            padding: 10px;
            margin-top: 10px;
            font-size: 11px;
            color: #888;
        }
        .info-box i {
            color: #FFD700;
            margin-right: 5px;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-left">
            <a href="admin_dashboard.php" class="back-btn"><i class="fas fa-arrow-left"></i></a>
            <h1><i class="fas fa-chart-line"></i> Manage Plans</h1>
        </div>
        <a href="admin_logout.php" class="logout-btn">
            <i class="fas fa-sign-out-alt"></i> Logout
        </a>
    </div>

    <div class="container">
        <?php if (isset($success)): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i>
                <span><?php echo $success; ?></span>
            </div>
        <?php endif; ?>
        
        <?php if (isset($error)): ?>
            <div class="alert alert-error">
                <i class="fas fa-exclamation-circle"></i>
                <span><?php echo $error; ?></span>
            </div>
        <?php endif; ?>

        <!-- Statistics -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['active_plans'] ?? 0; ?></div>
                <div class="stat-label">Active Plans</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['inactive_plans'] ?? 0; ?></div>
                <div class="stat-label">Inactive Plans</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['active_investments'] ?? 0; ?></div>
                <div class="stat-label">Active Investments</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">$<?php echo number_format($stats['total_invested'] ?? 0, 2); ?></div>
                <div class="stat-label">Total Invested</div>
            </div>
        </div>

        <button class="add-plan-btn" onclick="openAddModal()">
            <i class="fas fa-plus-circle"></i> Add New Plan
        </button>

        <!-- Plans List -->
        <div class="plans-list">
            <?php if ($plans_result && mysqli_num_rows($plans_result) > 0): ?>
                <?php while ($plan = mysqli_fetch_assoc($plans_result)): ?>
                <div class="plan-card <?php echo $plan['status'] == 'inactive' ? 'inactive' : ''; ?>">
                    <div class="plan-header">
                        <div class="plan-name">
                            <i class="fas fa-gem"></i>
                            <?php echo htmlspecialchars($plan['name']); ?>
                        </div>
                        <span class="plan-status status-<?php echo htmlspecialchars($plan['status']); ?>">
                            <?php echo htmlspecialchars($plan['status']); ?>
                        </span>
                    </div>
                    
                    <div class="plan-details">
                        <div class="detail-item">
                            <span class="detail-label">Minimum</span>
                            <span class="detail-value">$<?php echo number_format($plan['min_amount'], 2); ?></span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label">Maximum</span>
                            <span class="detail-value">$<?php echo number_format($plan['max_amount'], 2); ?></span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label">ROI</span>
                            <span class="detail-value"><?php echo $plan['roi_percentage']; ?>%</span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label">Duration</span>
                            <span class="detail-value"><?php echo $plan['duration_days']; ?> days</span>
                        </div>
                    </div>

                    <div style="margin: 10px 0;">
                        <span class="detail-label">Return Type:</span>
                        <span class="return-badge return-<?php echo htmlspecialchars($plan['return_type']); ?>">
                            <?php echo $plan['return_type'] == 'fixed' ? 'PROFIT ONLY' : 'PROFIT + CAPITAL'; ?>
                        </span>
                    </div>

                    <div class="plan-actions">
                        <button class="btn btn-edit" onclick="openEditModal(<?php echo htmlspecialchars(json_encode($plan)); ?>)">
                            <i class="fas fa-edit"></i> Edit
                        </button>
                        <form method="POST" style="flex: 1;" onsubmit="return confirm('Are you sure you want to delete this plan?');">
                            <input type="hidden" name="action" value="delete_plan">
                            <input type="hidden" name="plan_id" value="<?php echo $plan['id']; ?>">
                            <button type="submit" class="btn btn-delete">
                                <i class="fas fa-trash"></i> Delete
                            </button>
                        </form>
                    </div>
                </div>
                <?php endwhile; ?>
            <?php else: ?>
                <div style="text-align: center; padding: 40px; color: #666;">
                    <i class="fas fa-inbox" style="font-size: 50px; margin-bottom: 15px; opacity: 0.3;"></i>
                    <p>No plans found</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Add/Edit Plan Modal -->
    <div id="planModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title" id="modalTitle">Add New Plan</h2>
                <span class="close" onclick="closeModal()">&times;</span>
            </div>
            <form method="POST" id="planForm">
                <input type="hidden" name="action" id="formAction" value="add_plan">
                <input type="hidden" name="plan_id" id="planId">
                
                <div class="form-group">
                    <label class="form-label">Plan Name</label>
                    <input type="text" name="name" id="planName" required placeholder="e.g. Starter Plan">
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Minimum Amount ($)</label>
                        <input type="number" name="min_amount" id="minAmount" required step="0.01" min="0">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Maximum Amount ($)</label>
                        <input type="number" name="max_amount" id="maxAmount" required step="0.01" min="0">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">ROI Percentage (%)</label>
                        <input type="number" name="roi" id="roi" required step="0.01" min="0">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Duration (Days)</label>
                        <input type="number" name="duration_days" id="duration" required min="1">
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Return Type</label>
                    <select name="return_type" id="returnType" required>
                        <option value="fixed">Fixed (Profit Only)</option>
                        <option value="flexible">Flexible (Profit + Capital)</option>
                    </select>
                    <div class="info-box">
                        <i class="fas fa-info-circle"></i>
                        <strong>Fixed:</strong> Users receive only the profit at maturity<br>
                        <strong>Flexible:</strong> Users receive profit + their initial capital back
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Status</label>
                    <select name="status" id="status" required>
                        <option value="active">Active</option>
                        <option value="inactive">Inactive</option>
                    </select>
                </div>

                <button type="submit" class="submit-btn">
                    <i class="fas fa-save"></i> Save Plan
                </button>
            </form>
        </div>
    </div>

    <script>
        function openAddModal() {
            document.getElementById('modalTitle').innerText = 'Add New Plan';
            document.getElementById('formAction').value = 'add_plan';
            document.getElementById('planForm').reset();
            document.getElementById('planId').value = '';
            document.getElementById('status').value = 'active';
            document.getElementById('planModal').style.display = 'block';
        }

        function openEditModal(plan) {
            document.getElementById('modalTitle').innerText = 'Edit Plan';
            document.getElementById('formAction').value = 'update_plan';
            document.getElementById('planId').value = plan.id;
            document.getElementById('planName').value = plan.name;
            document.getElementById('minAmount').value = plan.min_amount;
            document.getElementById('maxAmount').value = plan.max_amount;
            document.getElementById('roi').value = plan.roi_percentage;
            document.getElementById('duration').value = plan.duration_days;
            document.getElementById('returnType').value = plan.return_type;
            document.getElementById('status').value = plan.status;
            document.getElementById('planModal').style.display = 'block';
        }

        function closeModal() {
            document.getElementById('planModal').style.display = 'none';
        }

        // Close modal when clicking outside
        window.onclick = function(event) {
            const modal = document.getElementById('planModal');
            if (event.target == modal) {
                closeModal();
            }
        }

        // Auto-hide alerts
        setTimeout(function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(function(alert) {
                alert.style.transition = 'opacity 0.5s';
                alert.style.opacity = '0';
                setTimeout(function() {
                    alert.remove();
                }, 500);
            });
        }, 5000);
    </script>
</body>
</html>
<?php
mysqli_close($conn);
?>