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

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

// Handle actions
if (isset($_GET['action']) && isset($_GET['id'])) {
    $action = $_GET['action'];
    $plan_id = $_GET['id'];
    
    try {
        if ($action == 'delete') {
            // Check if plan has active investments
            $check_stmt = $db->prepare("SELECT COUNT(*) as count FROM investments WHERE plan_id = ? AND status = 'running'");
            $check_stmt->execute([$plan_id]);
            $result = $check_stmt->fetch();
            
            if ($result['count'] > 0) {
                throw new Exception("Cannot delete plan with active investments");
            }
            
            // Delete plan
            $delete_stmt = $db->prepare("DELETE FROM investment_plans WHERE id = ?");
            $delete_stmt->execute([$plan_id]);
            
            $message = "Plan deleted successfully!";
            $success = true;
            
        } elseif ($action == 'toggle_status') {
            // Toggle plan status
            $status_stmt = $db->prepare("SELECT status FROM investment_plans WHERE id = ?");
            $status_stmt->execute([$plan_id]);
            $plan = $status_stmt->fetch();
            
            $new_status = $plan['status'] == 'active' ? 'inactive' : 'active';
            
            $update_stmt = $db->prepare("UPDATE investment_plans SET status = ? WHERE id = ?");
            $update_stmt->execute([$new_status, $plan_id]);
            
            $message = "Plan status updated to " . $new_status . "!";
            $success = true;
        }
        
        if ($success) {
            echo "<script>alert('$message'); window.location.href='plans.php';</script>";
            exit();
        }
        
    } catch (Exception $e) {
        $error = "Action failed: " . $e->getMessage();
    }
}

// Get all plans
$stmt = $db->query("SELECT * FROM investment_plans ORDER BY min_amount ASC");
$plans = $stmt->fetchAll();

// Get plan statistics
$stats_sql = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active,
    SUM(CASE WHEN status = 'inactive' THEN 1 ELSE 0 END) as inactive,
    (SELECT COUNT(*) FROM investments WHERE status = 'running') as active_investments
    FROM investment_plans";

$stats_stmt = $db->query($stats_sql);
$stats = $stats_stmt->fetch();
?>

<div class="container-fluid">
    <!-- Header -->
    <div class="bg-white rounded-xl shadow p-6 mb-6">
        <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
            <div>
                <h1 class="text-2xl font-bold">Investment Plans</h1>
                <p class="text-gray-600">Manage investment plans and their configurations</p>
            </div>
            <div>
                <a href="plan-create.php" class="bg-gradient-to-r from-purple-600 to-blue-600 text-white px-6 py-3 rounded-lg font-semibold hover:opacity-90">
                    <i class="fas fa-plus-circle mr-2"></i>Create New Plan
                </a>
            </div>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Plans</p>
                    <h3 class="text-2xl font-bold"><?php echo number_format($stats['total']); ?></h3>
                </div>
                <i class="fas fa-list-alt text-purple-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Active Plans</p>
                    <h3 class="text-2xl font-bold text-green-600"><?php echo number_format($stats['active']); ?></h3>
                </div>
                <i class="fas fa-check-circle text-green-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Inactive Plans</p>
                    <h3 class="text-2xl font-bold text-red-600"><?php echo number_format($stats['inactive']); ?></h3>
                </div>
                <i class="fas fa-times-circle text-red-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Active Investments</p>
                    <h3 class="text-2xl font-bold"><?php echo number_format($stats['active_investments']); ?></h3>
                </div>
                <i class="fas fa-chart-pie text-blue-500 text-2xl"></i>
            </div>
        </div>
    </div>

    <!-- Plans Grid -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <?php foreach ($plans as $plan): 
            // Get plan statistics
            $plan_stats_stmt = $db->prepare("SELECT 
                COUNT(*) as total_investments,
                SUM(amount) as total_invested,
                SUM(total_profit) as total_profits
                FROM investments 
                WHERE plan_id = ?");
            $plan_stats_stmt->execute([$plan['id']]);
            $plan_stats = $plan_stats_stmt->fetch();
            
            $total_return = $plan['daily_return'] * $plan['duration_days'];
        ?>
        <div class="bg-white rounded-xl shadow-lg overflow-hidden border <?php echo $plan['status'] == 'active' ? 'border-green-200' : 'border-red-200'; ?>">
            <!-- Plan Header -->
            <div class="bg-gradient-to-r <?php echo $plan['status'] == 'active' ? 'from-green-500 to-green-600' : 'from-red-500 to-red-600'; ?> text-white p-6">
                <div class="flex justify-between items-start">
                    <div>
                        <h3 class="text-xl font-bold"><?php echo htmlspecialchars($plan['name']); ?></h3>
                        <p class="opacity-90"><?php echo $plan['duration_days']; ?> Days</p>
                    </div>
                    <span class="px-3 py-1 bg-white <?php echo $plan['status'] == 'active' ? 'text-green-600' : 'text-red-600'; ?> rounded-full text-sm font-semibold">
                        <?php echo ucfirst($plan['status']); ?>
                    </span>
                </div>
            </div>
            
            <!-- Plan Body -->
            <div class="p-6">
                <!-- Return Rate -->
                <div class="text-center mb-6">
                    <div class="text-4xl font-bold text-green-600"><?php echo $plan['daily_return']; ?>%</div>
                    <p class="text-gray-600">Daily Return</p>
                    <p class="text-sm text-gray-500">Total: <?php echo $total_return; ?>% Return</p>
                </div>
                
                <!-- Investment Range -->
                <div class="mb-6">
                    <h4 class="font-semibold mb-2">Investment Range</h4>
                    <div class="flex justify-between items-center">
                        <div class="text-center">
                            <p class="text-2xl font-bold">$<?php echo number_format($plan['min_amount'], 2); ?></p>
                            <p class="text-sm text-gray-500">Minimum</p>
                        </div>
                        <div class="text-gray-400">
                            <i class="fas fa-arrows-alt-h"></i>
                        </div>
                        <div class="text-center">
                            <p class="text-2xl font-bold">$<?php echo number_format($plan['max_amount'], 2); ?></p>
                            <p class="text-sm text-gray-500">Maximum</p>
                        </div>
                    </div>
                </div>
                
                <!-- Features -->
                <div class="mb-6">
                    <h4 class="font-semibold mb-2">Features</h4>
                    <ul class="space-y-2">
                        <li class="flex items-center">
                            <i class="fas fa-check text-green-500 mr-2"></i>
                            <span><?php echo $plan['duration_days']; ?> Days Duration</span>
                        </li>
                        <li class="flex items-center">
                            <i class="fas fa-check text-green-500 mr-2"></i>
                            <span>Daily Profits</span>
                        </li>
                        <li class="flex items-center">
                            <i class="fas <?php echo $plan['principal_return'] ? 'fa-check text-green-500' : 'fa-times text-red-500'; ?> mr-2"></i>
                            <span>Principal <?php echo $plan['principal_return'] ? 'Returned' : 'Not Returned'; ?></span>
                        </li>
                        <li class="flex items-center">
                            <i class="fas <?php echo $plan['compound_interest'] ? 'fa-check text-green-500' : 'fa-times text-red-500'; ?> mr-2"></i>
                            <span>Compound Interest</span>
                        </li>
                    </ul>
                </div>
                
                <!-- Plan Statistics -->
                <div class="border-t pt-4">
                    <h4 class="font-semibold mb-2">Statistics</h4>
                    <div class="grid grid-cols-2 gap-2">
                        <div class="text-center">
                            <p class="font-bold"><?php echo number_format($plan_stats['total_investments'] ?? 0); ?></p>
                            <p class="text-xs text-gray-500">Investments</p>
                        </div>
                        <div class="text-center">
                            <p class="font-bold">$<?php echo number_format($plan_stats['total_invested'] ?? 0, 2); ?></p>
                            <p class="text-xs text-gray-500">Invested</p>
                        </div>
                    </div>
                </div>
                
                <!-- Actions -->
                <div class="border-t pt-4 mt-4">
                    <div class="flex justify-between">
                        <a href="plan-edit.php?id=<?php echo $plan['id']; ?>" 
                           class="text-blue-600 hover:text-blue-800 font-medium">
                            <i class="fas fa-edit mr-1"></i> Edit
                        </a>
                        
                        <a href="?action=toggle_status&id=<?php echo $plan['id']; ?>" 
                           onclick="return confirm('<?php echo $plan['status'] == 'active' ? 'Deactivate' : 'Activate'; ?> this plan?')"
                           class="text-yellow-600 hover:text-yellow-800 font-medium">
                            <i class="fas fa-power-off mr-1"></i> <?php echo $plan['status'] == 'active' ? 'Deactivate' : 'Activate'; ?>
                        </a>
                        
                        <a href="?action=delete&id=<?php echo $plan['id']; ?>" 
                           onclick="return confirm('Delete this plan? This action cannot be undone.')"
                           class="text-red-600 hover:text-red-800 font-medium">
                            <i class="fas fa-trash mr-1"></i> Delete
                        </a>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
        
        <!-- Create New Plan Card -->
        <div class="bg-white rounded-xl shadow-lg border-2 border-dashed border-gray-300 hover:border-purple-500 transition-colors">
            <div class="h-full flex flex-col items-center justify-center p-12 text-center">
                <div class="w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mb-4">
                    <i class="fas fa-plus-circle text-purple-600 text-2xl"></i>
                </div>
                <h3 class="text-lg font-semibold text-gray-800 mb-2">Create New Plan</h3>
                <p class="text-gray-600 mb-6">Add a new investment plan to attract more investors</p>
                <a href="plan-create.php" class="bg-gradient-to-r from-purple-600 to-blue-600 text-white px-6 py-3 rounded-lg font-semibold hover:opacity-90">
                    Create Plan
                </a>
            </div>
        </div>
    </div>
</div>

<script>
// Quick status toggle
function togglePlanStatus(planId, currentStatus) {
    const newStatus = currentStatus === 'active' ? 'inactive' : 'active';
    const actionText = currentStatus === 'active' ? 'Deactivate' : 'Activate';
    
    if (confirm(${actionText} this plan?)) {
        $.ajax({
            url: '../api/admin-actions.php',
            method: 'POST',
            data: {
                action: 'toggle_plan_status',
                plan_id: planId,
                status: newStatus
            },
            success: function(response) {
                const result = JSON.parse(response);
                showNotification(result.message, result.success ? 'success' : 'error');
                if (result.success) location.reload();
            }
        });
    }
}

// Export plans
function exportPlans() {
    window.open('../api/export-plans.php', '_blank');
}
</script>

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