<?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 investment actions
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $investment_id = intval($_POST['investment_id']);
    $action = $_POST['action'];
    
    if ($action == 'delete') {
        // Delete investment and related data
        mysqli_begin_transaction($conn);
        try {
            // Delete related referral commissions
            mysqli_query($conn, "DELETE FROM referral_commissions WHERE investment_id = $investment_id");
            
            // Delete the investment
            $delete_query = "DELETE FROM investments WHERE id = ?";
            $stmt = mysqli_prepare($conn, $delete_query);
            mysqli_stmt_bind_param($stmt, "i", $investment_id);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);
            
            mysqli_commit($conn);
            $success = "Investment deleted successfully!";
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $error = "Failed to delete investment: " . $e->getMessage();
        }
        
    } elseif ($action == 'pause') {
        // Check if paused column exists, if not add it
        $check_column = mysqli_query($conn, "SHOW COLUMNS FROM investments LIKE 'paused'");
        if (mysqli_num_rows($check_column) == 0) {
            mysqli_query($conn, "ALTER TABLE investments ADD COLUMN paused TINYINT(1) DEFAULT 0");
        }
        
        // Pause the investment
        $sql = "UPDATE investments SET paused = 1 WHERE id = ?";
        $stmt = mysqli_prepare($conn, $sql);
        mysqli_stmt_bind_param($stmt, "i", $investment_id);
        if (mysqli_stmt_execute($stmt)) {
            $success = "Investment paused successfully!";
        } else {
            $error = "Failed to pause investment!";
        }
        mysqli_stmt_close($stmt);
        
    } elseif ($action == 'unpause') {
        // Unpause the investment
        $sql = "UPDATE investments SET paused = 0 WHERE id = ?";
        $stmt = mysqli_prepare($conn, $sql);
        mysqli_stmt_bind_param($stmt, "i", $investment_id);
        if (mysqli_stmt_execute($stmt)) {
            $success = "Investment resumed successfully!";
        } else {
            $error = "Failed to resume investment!";
        }
        mysqli_stmt_close($stmt);
        
    } elseif ($action == 'mature') {
        // Manually mature an investment
        $investment_query = "SELECT i.*, u.phone_number 
                            FROM investments i 
                            JOIN users u ON i.user_id = u.id 
                            WHERE i.id = ?";
        $stmt = mysqli_prepare($conn, $investment_query);
        mysqli_stmt_bind_param($stmt, "i", $investment_id);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        $investment = mysqli_fetch_assoc($result);
        mysqli_stmt_close($stmt);
        
        if ($investment && $investment['status'] == 'running') {
            // Update investment status to matured
            $update_query = "UPDATE investments SET status = 'matured' WHERE id = ?";
            $stmt = mysqli_prepare($conn, $update_query);
            mysqli_stmt_bind_param($stmt, "i", $investment_id);
            
            if (mysqli_stmt_execute($stmt)) {
                // Add profit to user's account
                $profit_query = "INSERT INTO profits (user_id, amount, source, created_at) 
                                VALUES (?, ?, 'Investment Matured', NOW())";
                $stmt2 = mysqli_prepare($conn, $profit_query);
                mysqli_stmt_bind_param($stmt2, "id", $investment['user_id'], $investment['profit']);
                mysqli_stmt_execute($stmt2);
                mysqli_stmt_close($stmt2);
                
                $success = "Investment matured successfully! Profit added to user account.";
            } else {
                $error = "Failed to mature investment!";
            }
            mysqli_stmt_close($stmt);
        }
        
    } elseif ($action == 'adjust_profit') {
        $new_profit = floatval($_POST['new_profit']);
        
        $sql = "UPDATE investments SET profit = ? WHERE id = ?";
        $stmt = mysqli_prepare($conn, $sql);
        mysqli_stmt_bind_param($stmt, "di", $new_profit, $investment_id);
        if (mysqli_stmt_execute($stmt)) {
            $success = "Investment profit adjusted to $" . number_format($new_profit, 2) . " successfully!";
        } else {
            $error = "Failed to adjust profit!";
        }
        mysqli_stmt_close($stmt);
    }
}

// Get filter status
$filter = isset($_GET['filter']) ? $_GET['filter'] : 'all';

// Build query based on filter
$where_clause = "";
if ($filter == 'running') {
    $where_clause = "WHERE i.status = 'running'";
} elseif ($filter == 'matured') {
    $where_clause = "WHERE i.status = 'matured'";
} elseif ($filter == 'paused') {
    $where_clause = "WHERE i.paused = 1";
}

// Check if paused column exists
$check_column = mysqli_query($conn, "SHOW COLUMNS FROM investments LIKE 'paused'");
if (mysqli_num_rows($check_column) == 0) {
    mysqli_query($conn, "ALTER TABLE investments ADD COLUMN paused TINYINT(1) DEFAULT 0");
}

// Get all investments with user information
$query = "SELECT i.*, u.phone_number, u.email,
          COALESCE(i.paused, 0) as paused
          FROM investments i 
          JOIN users u ON i.user_id = u.id 
          $where_clause
          ORDER BY i.start_date DESC";
$investments_result = mysqli_query($conn, $query);

// Get counts for each status
$count_query = "SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN status = 'running' THEN 1 ELSE 0 END) as running,
                SUM(CASE WHEN status = 'matured' THEN 1 ELSE 0 END) as matured,
                COALESCE(SUM(CASE WHEN paused = 1 THEN 1 ELSE 0 END), 0) as paused,
                SUM(amount) as total_invested,
                SUM(CASE WHEN status = 'running' THEN amount ELSE 0 END) as active_invested
                FROM investments";
$count_result = mysqli_query($conn, $count_query);
$counts = mysqli_fetch_assoc($count_result);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Investments - 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(140px, 1fr));
            gap: 10px;
            margin-bottom: 15px;
        }
        .stat-card {
            background: #111;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            border: 2px solid transparent;
        }
        .stat-card:hover {
            transform: translateY(-2px);
        }
        .stat-card.active {
            border-color: #FFD700;
        }
        .stat-number {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 5px;
        }
        .stat-label {
            color: #888;
            font-size: 10px;
        }
        .stat-card.all .stat-number { color: #FFD700; }
        .stat-card.running .stat-number { color: #4ade80; }
        .stat-card.matured .stat-number { color: #3b82f6; }
        .stat-card.paused .stat-number { color: #FFA500; }
        
        .investments-list {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        .investment-card {
            background: #111;
            border-radius: 10px;
            padding: 15px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
            border-left: 4px solid #333;
        }
        .investment-card.running {
            border-left-color: #4ade80;
        }
        .investment-card.matured {
            border-left-color: #3b82f6;
        }
        .investment-card.paused {
            border-left-color: #FFA500;
            opacity: 0.8;
        }
        .investment-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 12px;
        }
        .investment-amount {
            font-size: 20px;
            font-weight: bold;
            color: #FFD700;
        }
        .investment-status {
            display: flex;
            flex-direction: column;
            gap: 5px;
            align-items: flex-end;
        }
        .status-badge {
            padding: 5px 10px;
            border-radius: 5px;
            font-size: 10px;
            font-weight: bold;
            text-transform: uppercase;
        }
        .status-running {
            background: #4ade80;
            color: #000;
        }
        .status-matured {
            background: #3b82f6;
            color: #fff;
        }
        .status-paused {
            background: #FFA500;
            color: #000;
        }
        .investment-info {
            display: grid;
            gap: 8px;
            margin-bottom: 12px;
        }
        .info-row {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 12px;
        }
        .info-label {
            color: #888;
            min-width: 100px;
        }
        .info-value {
            color: #fff;
        }
        .info-value.profit {
            color: #4ade80;
            font-weight: bold;
        }
        .progress-bar {
            width: 100%;
            height: 6px;
            background: #333;
            border-radius: 3px;
            margin: 10px 0 5px 0;
            overflow: hidden;
        }
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #FFD700, #FFA500);
            border-radius: 3px;
            transition: width 0.3s;
        }
        .progress-text {
            text-align: center;
            font-size: 10px;
            color: #888;
        }
        .action-buttons {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 8px;
            margin-top: 12px;
        }
        .btn {
            padding: 8px;
            border: none;
            border-radius: 5px;
            font-weight: bold;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 5px;
            font-size: 11px;
            transition: all 0.3s;
        }
        .btn-pause {
            background: #FFA500;
            color: #000;
        }
        .btn-pause:hover {
            background: #ff8800;
        }
        .btn-unpause {
            background: #4ade80;
            color: #000;
        }
        .btn-unpause:hover {
            background: #22c55e;
        }
        .btn-mature {
            background: #3b82f6;
            color: #fff;
        }
        .btn-mature:hover {
            background: #2563eb;
        }
        .btn-adjust {
            background: #8b5cf6;
            color: #fff;
        }
        .btn-adjust:hover {
            background: #7c3aed;
        }
        .btn-delete {
            background: #f87171;
            color: #fff;
        }
        .btn-delete:hover {
            background: #ef4444;
        }
        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        .no-investments {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        .no-investments i {
            font-size: 50px;
            margin-bottom: 15px;
            opacity: 0.3;
        }

        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.8);
            overflow-y: auto;
        }
        .modal-content {
            background-color: #111;
            margin: 50px auto;
            padding: 20px;
            border: 1px solid #333;
            width: 90%;
            max-width: 500px;
            border-radius: 10px;
            position: relative;
        }
        .close {
            color: #888;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            line-height: 20px;
        }
        .close:hover {
            color: #fff;
        }
        .modal h2 {
            color: #FFD700;
            margin-bottom: 20px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #fff;
            font-size: 12px;
        }
        .form-group input {
            width: 100%;
            padding: 10px;
            background: #000;
            border: 1px solid #333;
            border-radius: 5px;
            color: #fff;
            font-size: 14px;
        }
        .form-group input:focus {
            outline: none;
            border-color: #FFD700;
        }
        .btn-submit {
            width: 100%;
            padding: 12px;
            background: #FFD700;
            color: #000;
            border: none;
            border-radius: 5px;
            font-weight: bold;
            cursor: pointer;
            font-size: 14px;
            margin-top: 10px;
        }
        .btn-submit:hover {
            background: #FFA500;
        }

        @media (max-width: 768px) {
            .investment-header {
                flex-direction: column;
                gap: 10px;
            }
            .investment-status {
                align-items: flex-start;
            }
        }
    </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 Investments</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">
            <a href="?filter=all" style="text-decoration: none;">
                <div class="stat-card all <?php echo $filter == 'all' ? 'active' : ''; ?>">
                    <div class="stat-number"><?php echo $counts['total']; ?></div>
                    <div class="stat-label">Total Investments</div>
                </div>
            </a>
            <a href="?filter=running" style="text-decoration: none;">
                <div class="stat-card running <?php echo $filter == 'running' ? 'active' : ''; ?>">
                    <div class="stat-number"><?php echo $counts['running']; ?></div>
                    <div class="stat-label">Active</div>
                </div>
            </a>
            <a href="?filter=matured" style="text-decoration: none;">
                <div class="stat-card matured <?php echo $filter == 'matured' ? 'active' : ''; ?>">
                    <div class="stat-number"><?php echo $counts['matured']; ?></div>
                    <div class="stat-label">Completed</div>
                </div>
            </a>
            <a href="?filter=paused" style="text-decoration: none;">
                <div class="stat-card paused <?php echo $filter == 'paused' ? 'active' : ''; ?>">
                    <div class="stat-number"><?php echo $counts['paused']; ?></div>
                    <div class="stat-label">Paused</div>
                </div>
            </a>
            <div class="stat-card">
                <div class="stat-number" style="color: #4ade80;">$<?php echo number_format($counts['total_invested'], 0); ?></div>
                <div class="stat-label">Total Invested</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" style="color: #3b82f6;">$<?php echo number_format($counts['active_invested'], 0); ?></div>
                <div class="stat-label">Active Capital</div>
            </div>
        </div>

        <!-- Investments List -->
        <div class="investments-list">
            <?php if ($investments_result && mysqli_num_rows($investments_result) > 0): ?>
                <?php while ($investment = mysqli_fetch_assoc($investments_result)): 
                    $start = strtotime($investment['start_date']);
                    $maturity = strtotime($investment['maturity_date']);
                    $now = time();
                    $total_duration = $maturity - $start;
                    $elapsed = $now - $start;
                    $progress = min(100, max(0, ($elapsed / $total_duration) * 100));
                    $is_paused = $investment['paused'] == 1;
                    $status_class = $is_paused ? 'paused' : $investment['status'];
                ?>
                <div class="investment-card <?php echo $status_class; ?>">
                    <div class="investment-header">
                        <div class="investment-amount">
                            <i class="fas fa-dollar-sign"></i> <?php echo number_format($investment['amount'], 2); ?>
                        </div>
                        <div class="investment-status">
                            <span class="status-badge status-<?php echo htmlspecialchars($investment['status']); ?>">
                                <?php echo htmlspecialchars($investment['status']); ?>
                            </span>
                            <?php if ($is_paused): ?>
                            <span class="status-badge status-paused">
                                <i class="fas fa-pause"></i> PAUSED
                            </span>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="investment-info">
                        <div class="info-row">
                            <span class="info-label"><i class="fas fa-user"></i> User:</span>
                            <span class="info-value"><?php echo htmlspecialchars($investment['phone_number']); ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label"><i class="fas fa-envelope"></i> Email:</span>
                            <span class="info-value"><?php echo htmlspecialchars($investment['email']); ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label"><i class="fas fa-calendar-plus"></i> Start Date:</span>
                            <span class="info-value"><?php echo date('M d, Y - h:i A', $start); ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label"><i class="fas fa-calendar-check"></i> Maturity:</span>
                            <span class="info-value"><?php echo date('M d, Y - h:i A', $maturity); ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label"><i class="fas fa-coins"></i> Expected Profit:</span>
                            <span class="info-value profit">$<?php echo number_format($investment['profit'], 2); ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label"><i class="fas fa-chart-line"></i> Total Return:</span>
                            <span class="info-value">$<?php echo number_format($investment['amount'] + $investment['profit'], 2); ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label"><i class="fas fa-hashtag"></i> ID:</span>
                            <span class="info-value">#<?php echo $investment['id']; ?></span>
                        </div>
                    </div>

                    <?php if ($investment['status'] == 'running' && !$is_paused): ?>
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: <?php echo $progress; ?>%"></div>
                    </div>
                    <div class="progress-text">Progress: <?php echo round($progress); ?>%</div>
                    <?php endif; ?>

                    <div class="action-buttons">
                        <?php if ($investment['status'] == 'running'): ?>
                            <?php if ($is_paused): ?>
                            <form method="POST" style="margin: 0;">
                                <input type="hidden" name="investment_id" value="<?php echo $investment['id']; ?>">
                                <input type="hidden" name="action" value="unpause">
                                <button type="submit" class="btn btn-unpause">
                                    <i class="fas fa-play"></i> Resume
                                </button>
                            </form>
                            <?php else: ?>
                            <form method="POST" style="margin: 0;" onsubmit="return confirm('Are you sure you want to PAUSE this investment?');">
                                <input type="hidden" name="investment_id" value="<?php echo $investment['id']; ?>">
                                <input type="hidden" name="action" value="pause">
                                <button type="submit" class="btn btn-pause">
                                    <i class="fas fa-pause"></i> Pause
                                </button>
                            </form>
                            <?php endif; ?>
                            
                            <form method="POST" style="margin: 0;" onsubmit="return confirm('Are you sure you want to MATURE this investment? Profit will be added to user account.');">
                                <input type="hidden" name="investment_id" value="<?php echo $investment['id']; ?>">
                                <input type="hidden" name="action" value="mature">
                                <button type="submit" class="btn btn-mature">
                                    <i class="fas fa-check-circle"></i> Complete
                                </button>
                            </form>
                        <?php endif; ?>
                        
                        <button type="button" class="btn btn-adjust" onclick="openAdjustModal(<?php echo $investment['id']; ?>, <?php echo $investment['profit']; ?>, '<?php echo htmlspecialchars($investment['phone_number']); ?>')">
                            <i class="fas fa-edit"></i> Adjust Profit
                        </button>
                        
                        <form method="POST" style="margin: 0;" onsubmit="return confirm('Are you sure you want to DELETE this investment? This action cannot be undone!');">
                            <input type="hidden" name="investment_id" value="<?php echo $investment['id']; ?>">
                            <input type="hidden" name="action" value="delete">
                            <button type="submit" class="btn btn-delete">
                                <i class="fas fa-trash"></i> Delete
                            </button>
                        </form>
                    </div>
                </div>
                <?php endwhile; ?>
            <?php else: ?>
                <div class="no-investments">
                    <i class="fas fa-chart-line"></i>
                    <p>No investments found</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Adjust Profit Modal -->
    <div id="adjustModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeAdjustModal()">&times;</span>
            <h2><i class="fas fa-edit"></i> Adjust Investment Profit</h2>
            <p style="color: #888; margin-bottom: 20px; font-size: 12px;">
                User: <span id="modalUserPhone"></span><br>
                Current Profit: $<span id="modalCurrentProfit"></span>
            </p>
            
            <form method="POST">
                <input type="hidden" name="investment_id" id="modalInvestmentId">
                <input type="hidden" name="action" value="adjust_profit">
                
                <div class="form-group">
                    <label>New Profit Amount ($)</label>
                    <input type="number" name="new_profit" step="0.01" min="0" placeholder="Enter new profit amount" required>
                </div>
                
                <button type="submit" class="btn-submit">
                    <i class="fas fa-check"></i> Update Profit
                </button>
            </form>
        </div>
    </div>

    <script>
        // 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);

        // Modal functions
        function openAdjustModal(investmentId, currentProfit, userPhone) {
            document.getElementById('modalInvestmentId').value = investmentId;
            document.getElementById('modalCurrentProfit').textContent = currentProfit;
            document.getElementById('modalUserPhone').textContent = userPhone;
            document.getElementById('adjustModal').style.display = 'block';
        }

        function closeAdjustModal() {
            document.getElementById('adjustModal').style.display = 'none';
        }

        // Close modal when clicking outside
        window.onclick = function(event) {
            const modal = document.getElementById('adjustModal');
            if (event.target == modal) {
                closeAdjustModal();
            }
        }
    </script>
</body>
</html>
<?php
mysqli_close($conn);
?>