<?php
$page_title = "Create Investment Plan";
require_once 'header.php';

$db = Database::getInstance()->connect();
$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);
    $description = trim($_POST['description']);
    $min_amount = floatval($_POST['min_amount']);
    $max_amount = floatval($_POST['max_amount']);
    $daily_return = floatval($_POST['daily_return']);
    $duration_days = intval($_POST['duration_days']);
    $total_return = floatval($_POST['total_return']);
    $principal_return = isset($_POST['principal_return']) ? 1 : 0;
    $compound_interest = isset($_POST['compound_interest']) ? 1 : 0;
    $status = $_POST['status'];
    $features = $_POST['features'] ?? [];
    
    // Validation
    if (empty($name) || $min_amount <= 0 || $max_amount <= 0 || $daily_return <= 0 || $duration_days <= 0) {
        $error = "Please fill all required fields with valid values";
    } elseif ($min_amount >= $max_amount) {
        $error = "Maximum amount must be greater than minimum amount";
    } elseif ($daily_return > 100) {
        $error = "Daily return cannot exceed 100%";
    } else {
        try {
            // Calculate total return if not provided
            if ($total_return <= 0) {
                $total_return = $daily_return * $duration_days;
            }
            
            // Insert plan
            $stmt = $db->prepare("
                INSERT INTO investment_plans (name, description, min_amount, max_amount, daily_return, 
                                            duration_days, total_return, principal_return, compound_interest, 
                                            status, features)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $stmt->execute([
                $name, $description, $min_amount, $max_amount, $daily_return, $duration_days,
                $total_return, $principal_return, $compound_interest, $status,
                json_encode($features)
            ]);
            
            $plan_id = $db->lastInsertId();
            
            // Log action
            $log_stmt = $db->prepare("INSERT INTO activity_logs (admin_id, action, details) VALUES (?, 'plan_create', ?)");
            $log_stmt->execute([
                $_SESSION['admin_id'],
                json_encode([
                    'plan_id' => $plan_id,
                    'name' => $name,
                    'daily_return' => $daily_return,
                    'created_by' => $_SESSION['admin_username']
                ])
            ]);
            
            $success = "Investment plan created successfully!";
            
            // Clear form
            $_POST = [];
            
        } catch (Exception $e) {
            $error = "Failed to create plan: " . $e->getMessage();
        }
    }
}
?>

<div class="container-fluid">
    <div class="max-w-4xl mx-auto">
        <!-- Header -->
        <div class="bg-white rounded-xl shadow p-6 mb-6">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-2xl font-bold">Create Investment Plan</h1>
                    <p class="text-gray-600">Design a new investment plan for your users</p>
                </div>
                <a href="plans.php" class="text-gray-600 hover:text-gray-800">
                    <i class="fas fa-arrow-left mr-2"></i>Back to Plans
                </a>
            </div>
        </div>

        <?php if ($error): ?>
        <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
            <?php echo $error; ?>
        </div>
        <?php endif; ?>
        
        <?php if ($success): ?>
        <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
            <?php echo $success; ?>
        </div>
        <?php endif; ?>

        <!-- Plan Form -->
        <div class="bg-white rounded-xl shadow p-6">
            <form method="POST" action="" class="space-y-8">
                <!-- Basic Information -->
                <div>
                    <h3 class="text-lg font-bold mb-4">Basic Information</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Plan Name *</label>
                            <input type="text" name="name" value="<?php echo htmlspecialchars($_POST['name'] ?? ''); ?>" required
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                                   placeholder="e.g., Starter Plan">
                        </div>
                        
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Status *</label>
                            <select name="status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                                <option value="active" selected>Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="mt-4">
                        <label class="block text-gray-700 font-medium mb-2">Description</label>
                        <textarea name="description" rows="3"
                                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                                  placeholder="Describe this investment plan..."><?php echo htmlspecialchars($_POST['description'] ?? ''); ?></textarea>
                    </div>
                </div>

                <!-- Financial Settings -->
                <div>
                    <h3 class="text-lg font-bold mb-4">Financial Settings</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Minimum Amount ($) *</label>
                            <input type="number" step="0.01" name="min_amount" value="<?php echo $_POST['min_amount'] ?? '50.00'; ?>" required
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                            <p class="text-xs text-gray-500 mt-1">Minimum investment amount</p>
                        </div>
                        
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Maximum Amount ($) *</label>
                            <input type="number" step="0.01" name="max_amount" value="<?php echo $_POST['max_amount'] ?? '1000.00'; ?>" required
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                            <p class="text-xs text-gray-500 mt-1">Maximum investment amount</p>
                        </div>
                        
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Daily Return (%) *</label>
                            <input type="number" step="0.01" name="daily_return" value="<?php echo $_POST['daily_return'] ?? '5.00'; ?>" required
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                            <p class="text-xs text-gray-500 mt-1">Daily profit percentage</p>
                        </div>
                        
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Duration (Days) *</label>
                            <input type="number" name="duration_days" value="<?php echo $_POST['duration_days'] ?? '30'; ?>" required
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                            <p class="text-xs text-gray-500 mt-1">Investment duration in days</p>
                        </div>
                        
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Total Return (%)</label>
                            <input type="number" step="0.01" name="total_return" value="<?php echo $_POST['total_return'] ?? ''; ?>"
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                                   placeholder="Auto-calculated">
                            <p class="text-xs text-gray-500 mt-1">Leave empty for auto-calculation</p>
                        </div>
                    </div>
                </div>

                <!-- Plan Features -->
                <div>
                    <h3 class="text-lg font-bold mb-4">Plan Features</h3>
                    <div class="space-y-4">
                        <div class="flex items-center">
                            <input type="checkbox" id="principal_return" name="principal_return" value="1" checked
                                   class="h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded">
                            <label for="principal_return" class="ml-2 text-gray-700">
                                Principal Return (Return initial investment at the end)
                            </label>
                        </div>
                        
                        <div class="flex items-center">
                            <input type="checkbox" id="compound_interest" name="compound_interest" value="1"
                                   class="h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded">
                            <label for="compound_interest" class="ml-2 text-gray-700">
                                Compound Interest (Reinvest daily profits)
                            </label>
                        </div>
                        
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Additional Features</label>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-2">
                                <div class="flex items-center">
                                    <input type="checkbox" id="feature_24_7" name="features[]" value="24/7 Support"
                                           class="h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded">
                                    <label for="feature_24_7" class="ml-2 text-gray-700">24/7 Support</label>
                                </div>
                                <div class="flex items-center">
                                    <input type="checkbox" id="feature_daily" name="features[]" value="Daily Payouts"
                                           class="h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded">
                                    <label for="feature_daily" class="ml-2 text-gray-700">Daily Payouts</label>
                                </div>
                                <div class="flex items-center">
                                    <input type="checkbox" id="feature_instant" name="features[]" value="Instant Withdrawal"
                                           class="h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded">
                                    <label for="feature_instant" class="ml-2 text-gray-700">Instant Withdrawal</label>
                                </div>
                                <div class="flex items-center">
                                    <input type="checkbox" id="feature_compound" name="features[]" value="Compound Option"
                                           class="h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded">
                                    <label for="feature_compound" class="ml-2 text-gray-700">Compound Option</label>
                                </div>
                                <div class="flex items-center">
                                    <input type="checkbox" id="feature_bonus" name="features[]" value="Welcome Bonus"
                                           class="h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded">
                                    <label for="feature_bonus" class="ml-2 text-gray-700">Welcome Bonus</label>
                                </div>
                                <div class="flex items-center">
                                    <input type="checkbox" id="feature_referral" name="features[]" value="Referral Bonus"
                                           class="h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded">
                                    <label for="feature_referral" class="ml-2 text-gray-700">Referral Bonus</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Plan Preview -->
                <div class="border-t pt-6">
                    <h3 class="text-lg font-bold mb-4">Plan Preview</h3>
                    <div class="bg-gray-50 rounded-lg p-6">
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-center">
                            <div>
                                <p class="text-gray-600">Investment Range</p>
                                <p class="text-xl font-bold">
                                    $<span id="preview_min"><?php echo $_POST['min_amount'] ?? '50.00'; ?></span> - 
                                    $<span id="preview_max"><?php echo $_POST['max_amount'] ?? '1000.00'; ?></span>
                                </p>
                            </div>
                            <div>
                                <p class="text-gray-600">Daily Return</p>
                                <p class="text-2xl font-bold text-green-600">
                                    <span id="preview_daily"><?php echo $_POST['daily_return'] ?? '5.00'; ?></span>%
                                </p>
                            </div>
                            <div>
                                <p class="text-gray-600">Duration</p>
                                <p class="text-xl font-bold">
                                    <span id="preview_duration"><?php echo $_POST['duration_days'] ?? '30'; ?></span> Days
                                </p>
                            </div>
                        </div>
                        <div class="mt-4 text-center">
                            <p class="text-gray-600">Total Return</p>
                            <p class="text-xl font-bold text-blue-600">
                                <span id="preview_total"><?php echo ($_POST['daily_return'] ?? 5) * ($_POST['duration_days'] ?? 30); ?></span>%
                            </p>
                        </div>
                    </div>
                </div>

                <!-- Submit Buttons -->
                <div class="border-t pt-6">
                    <div class="flex justify-end space-x-4">
                        <a href="plans.php" class="px-6 py-3 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">
                            Cancel
                        </a>
                        <button type="submit" 
                                class="bg-gradient-to-r from-purple-600 to-blue-600 text-white font-bold px-6 py-3 rounded-lg hover:opacity-90">
                            <i class="fas fa-save mr-2"></i>Create Plan
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Live preview updates
document.querySelectorAll('input[name="min_amount"], input[name="max_amount"], input[name="daily_return"], input[name="duration_days"]').forEach(input => {
    input.addEventListener('input', updatePreview);
});

function updatePreview() {
    const min = document.querySelector('input[name="min_amount"]').value || '50.00';
    const max = document.querySelector('input[name="max_amount"]').value || '1000.00';
    const daily = document.querySelector('input[name="daily_return"]').value || '5.00';
    const duration = document.querySelector('input[name="duration_days"]').value || '30';
    
    document.getElementById('preview_min').textContent = parseFloat(min).toFixed(2);
    document.getElementById('preview_max').textContent = parseFloat(max).toFixed(2);
    document.getElementById('preview_daily').textContent = parseFloat(daily).toFixed(2);
    document.getElementById('preview_duration').textContent = duration;
    
    // Calculate total return
    const total = parseFloat(daily) * parseInt(duration);
    document.getElementById('preview_total').textContent = total.toFixed(2);
    
    // Update total return field if empty
    const totalReturnField = document.querySelector('input[name="total_return"]');
    if (!totalReturnField.value) {
        totalReturnField.value = total.toFixed(2);
    }
}

// Initialize preview
updatePreview();

// Validate amounts
document.querySelector('input[name="max_amount"]').addEventListener('blur', function() {
    const min = parseFloat(document.querySelector('input[name="min_amount"]').value);
    const max = parseFloat(this.value);
    
    if (max <= min) {
        showNotification('Maximum amount must be greater than minimum amount', 'error');
        this.value = min + 10;
        updatePreview();
    }
});

// Validate daily return
document.querySelector('input[name="daily_return"]').addEventListener('blur', function() {
    const value = parseFloat(this.value);
    if (value > 100) {
        showNotification('Daily return cannot exceed 100%', 'error');
        this.value = 100;
        updatePreview();
    }
});
</script>

<?php require_once 'footer.php'; ?>