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

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

if (!isset($_GET['id'])) {
    header('Location: investments.php');
    exit;
}

$investment_id = intval($_GET['id']);

// Get investment details
$sql = "SELECT i.*, u.username, u.email, u.full_name, u.phone, u.country, 
               p.name as plan_name, p.description as plan_description, 
               p.daily_return, p.duration_days, p.min_amount, p.max_amount,
               p.principal_return, p.status as plan_status
        FROM investments i 
        JOIN users u ON i.user_id = u.id 
        JOIN investment_plans p ON i.plan_id = p.id 
        WHERE i.id = ?";

$stmt = $db->prepare($sql);
$stmt->execute([$investment_id]);
$investment = $stmt->fetch();

if (!$investment) {
    echo "<script>alert('Investment not found'); window.location.href='investments.php';</script>";
    exit;
}

// Calculate statistics
$start_date = new DateTime($investment['start_date']);
$end_date = new DateTime($investment['end_date']);
$current_date = new DateTime();
$total_days = $investment['duration_days'];

if ($current_date > $end_date) {
    $days_elapsed = $total_days;
} else {
    $days_elapsed = $current_date->diff($start_date)->days;
}

$days_left = max(0, $total_days - $days_elapsed);
$progress = min(100, ($days_elapsed / $total_days) * 100);
$daily_profit = $investment['amount'] * ($investment['daily_return'] / 100);
$expected_total_profit = $daily_profit * $total_days;

// Get profit history
$profit_sql = "SELECT * FROM transactions 
               WHERE user_id = ? AND type = 'profit' AND description LIKE ? 
               ORDER BY created_at DESC 
               LIMIT 10";
$profit_stmt = $db->prepare($profit_sql);
$profit_stmt->execute([$investment['user_id'], '%investment #' . $investment_id . '%']);
$profit_history = $profit_stmt->fetchAll();

// Get all actions for this investment
$actions_sql = "SELECT al.*, au.username as admin_username 
                FROM activity_logs al 
                LEFT JOIN admin_users au ON al.admin_id = au.id 
                WHERE al.details LIKE ? 
                ORDER BY al.created_at DESC 
                LIMIT 20";
$actions_stmt = $db->prepare($actions_sql);
$actions_stmt->execute(['%"investment_id":' . $investment_id . '%']);
$investment_actions = $actions_stmt->fetchAll();
?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="mb-6">
        <div class="flex justify-between items-center">
            <div>
                <h1 class="text-2xl font-bold">Investment #<?php echo $investment['id']; ?></h1>
                <p class="text-gray-600">Detailed view of investment activity</p>
            </div>
            <div class="flex space-x-2">
                <a href="investments.php" class="bg-gray-200 text-gray-800 px-4 py-2 rounded-lg hover:bg-gray-300">
                    <i class="fas fa-arrow-left mr-2"></i>Back to List
                </a>
                <button onclick="printInvestment()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                    <i class="fas fa-print mr-2"></i>Print
                </button>
            </div>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Left Column: Investment Details -->
        <div class="lg:col-span-2 space-y-6">
            <!-- Investment Card -->
            <div class="bg-white rounded-xl shadow">
                <div class="p-6 border-b">
                    <div class="flex justify-between items-center">
                        <div>
                            <h2 class="text-xl font-bold">Investment Details</h2>
                            <p class="text-gray-600">Created on <?php echo date('F d, Y', strtotime($investment['created_at'])); ?></p>
                        </div>
                        <span class="px-4 py-2 rounded-full text-sm font-semibold <?php
                            echo $investment['status'] == 'running' ? 'bg-green-100 text-green-800' :
                                ($investment['status'] == 'completed' ? 'bg-blue-100 text-blue-800' :
                                ($investment['status'] == 'cancelled' ? 'bg-red-100 text-red-800' :
                                'bg-gray-100 text-gray-800'));
                        ?>">
                            <?php echo ucfirst($investment['status']); ?>
                        </span>
                    </div>
                </div>
                
                <div class="p-6">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <!-- Amount & Plan -->
                        <div class="space-y-4">
                            <div>
                                <p class="text-sm text-gray-600">Investment Amount</p>
                                <p class="text-3xl font-bold text-green-600">$<?php echo number_format($investment['amount'], 2); ?></p>
                            </div>
                            
                            <div>
                                <p class="text-sm text-gray-600">Plan</p>
                                <p class="text-lg font-semibold"><?php echo htmlspecialchars($investment['plan_name']); ?></p>
                                <p class="text-sm text-gray-600"><?php echo $investment['daily_return']; ?>% daily for <?php echo $total_days; ?> days</p>
                                <?php if ($investment['plan_description']): ?>
                                <p class="text-sm text-gray-500 mt-2"><?php echo htmlspecialchars($investment['plan_description']); ?></p>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <!-- Timeline -->
                        <div class="space-y-4">
                            <div>
                                <p class="text-sm text-gray-600 mb-2">Investment Period</p>
                                <div class="space-y-2">
                                    <div class="flex justify-between">
                                        <span class="text-sm">Start Date:</span>
                                        <span class="font-medium"><?php echo date('M d, Y', strtotime($investment['start_date'])); ?></span>
                                    </div>
                                    <div class="flex justify-between">
                                        <span class="text-sm">End Date:</span>
                                        <span class="font-medium"><?php echo date('M d, Y', strtotime($investment['end_date'])); ?></span>
                                    </div>
                                    <div class="flex justify-between">
                                        <span class="text-sm">Days Elapsed:</span>
                                        <span class="font-medium"><?php echo $days_elapsed; ?> / <?php echo $total_days; ?></span>
                                    </div>
                                    <div class="flex justify-between">
                                        <span class="text-sm">Days Remaining:</span>
                                        <span class="font-medium <?php echo $days_left > 0 ? 'text-green-600' : 'text-red-600'; ?>">
                                            <?php echo $days_left; ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            
                            <div>
                                <div class="flex justify-between text-sm mb-1">
                                    <span>Progress</span>
                                    <span><?php echo number_format($progress, 1); ?>%</span>
                                </div>
                                <div class="w-full bg-gray-200 rounded-full h-2">
                                    <div class="bg-green-600 h-2 rounded-full" style="width: <?php echo $progress; ?>%"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Profit Details -->
            <div class="bg-white rounded-xl shadow">
                <div class="p-6 border-b">
                    <h3 class="text-lg font-bold">Profit Details</h3>
                </div>
                <div class="p-6">
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div class="bg-green-50 p-4 rounded-lg">
                            <p class="text-sm text-gray-600">Daily Profit</p>
                            <p class="text-2xl font-bold text-green-600">$<?php echo number_format($daily_profit, 2); ?></p>
                        </div>
                        <div class="bg-blue-50 p-4 rounded-lg">
                            <p class="text-sm text-gray-600">Earned So Far</p>
                            <p class="text-2xl font-bold text-blue-600">$<?php echo number_format($investment['total_profit'], 2); ?></p>
                        </div>
                        <div class="bg-purple-50 p-4 rounded-lg">
                            <p class="text-sm text-gray-600">Expected Total</p>
                            <p class="text-2xl font-bold text-purple-600">$<?php echo number_format($expected_total_profit, 2); ?></p>
                        </div>
                    </div>
                    
                    <?php if ($investment['status'] == 'running'): ?>
                    <div class="mt-6">
                        <button onclick="addProfit()" class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700">
                            <i class="fas fa-plus mr-2"></i>Add Daily Profit
                        </button>
                        <button onclick="skipProfit()" class="bg-yellow-600 text-white px-4 py-2 rounded-lg hover:bg-yellow-700 ml-2">
                            <i class="fas fa-forward mr-2"></i>Skip Today's Profit
                        </button>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Profit History -->
            <?php if (!empty($profit_history)): ?>
            <div class="bg-white rounded-xl shadow">
                <div class="p-6 border-b">
                    <h3 class="text-lg font-bold">Recent Profit History</h3>
                </div>
                <div class="p-6">
                    <div class="overflow-x-auto">
                        <table class="w-full">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="p-3 text-left text-sm">Date</th>
                                    <th class="p-3 text-left text-sm">Amount</th>
                                    <th class="p-3 text-left text-sm">Type</th>
                                    <th class="p-3 text-left text-sm">Status</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-100">
                                <?php foreach ($profit_history as $profit): ?>
                                <tr>
                                    <td class="p-3"><?php echo date('M d, Y H:i', strtotime($profit['created_at'])); ?></td>
                                    <td class="p-3 font-medium text-green-600">$<?php echo number_format($profit['amount'], 2); ?></td>
                                    <td class="p-3">
                                        <span class="px-2 py-1 rounded-full text-xs <?php echo $profit['type'] == 'daily' ? 'bg-blue-100 text-blue-800' : 'bg-purple-100 text-purple-800'; ?>">
                                            <?php echo ucfirst($profit['type']); ?>
                                        </span>
                                    </td>
                                    <td class="p-3">
                                        <span class="px-2 py-1 rounded-full text-xs <?php echo $profit['status'] == 'paid' ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'; ?>">
                                            <?php echo ucfirst($profit['status']); ?>
                                        </span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php if (count($profit_history) >= 10): ?>
                    <div class="mt-4 text-center">
                        <a href="investment-profits.php?investment_id=<?php echo $investment_id; ?>" class="text-blue-600 hover:text-blue-800">
                            View All Profit Records →
                        </a>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- Activity Log -->
            <?php if (!empty($investment_actions)): ?>
            <div class="bg-white rounded-xl shadow">
                <div class="p-6 border-b">
                    <h3 class="text-lg font-bold">Activity Log</h3>
                </div>
                <div class="p-6">
                    <div class="space-y-4">
                        <?php foreach ($investment_actions as $log): 
                            $details = json_decode($log['details'] ?? '{}', true);
                        ?>
                        <div class="border-l-4 border-purple-500 pl-4 py-2">
                            <div class="flex justify-between">
                                <p class="font-medium"><?php echo ucfirst(str_replace('_', ' ', $log['action'])); ?></p>
                                <p class="text-sm text-gray-500"><?php echo date('M d, H:i', strtotime($log['created_at'])); ?></p>
                            </div>
                            <?php if ($log['admin_username']): ?>
                            <p class="text-sm text-gray-600">By: <?php echo htmlspecialchars($log['admin_username']); ?></p>
                            <?php endif; ?>
                            <?php if (!empty($details)): ?>
                            <p class="text-sm text-gray-500 mt-1">
                                <?php 
                                foreach ($details as $key => $value) {
                                    echo ucfirst($key) . ': ' . htmlspecialchars(json_encode($value)) . ' ';
                                }
                                ?>
                            </p>
                            <?php endif; ?>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <!-- Right Column: User Info & Actions -->
        <div class="space-y-6">
            <!-- User Information -->
            <div class="bg-white rounded-xl shadow">
                <div class="p-6 border-b">
                    <h3 class="text-lg font-bold">User Information</h3>
                </div>
                <div class="p-6">
                    <div class="space-y-4">
                        <div>
                            <p class="text-sm text-gray-600">Username</p>
                            <p class="font-medium"><?php echo htmlspecialchars($investment['username']); ?></p>
                        </div>
                        
                        <div>
                            <p class="text-sm text-gray-600">Email</p>
                            <p class="font-medium"><?php echo htmlspecialchars($investment['email']); ?></p>
                        </div>
                        
                        <?php if ($investment['full_name']): ?>
                        <div>
                            <p class="text-sm text-gray-600">Full Name</p>
                            <p class="font-medium"><?php echo htmlspecialchars($investment['full_name']); ?></p>
                        </div>
                        <?php endif; ?>
                        
                        <?php if ($investment['phone']): ?>
                        <div>
                            <p class="text-sm text-gray-600">Phone</p>
                            <p class="font-medium"><?php echo htmlspecialchars($investment['phone']); ?></p>
                        </div>
                        <?php endif; ?>
                        
                        <?php if ($investment['country']): ?>
                        <div>
                            <p class="text-sm text-gray-600">Country</p>
                            <p class="font-medium"><?php echo htmlspecialchars($investment['country']); ?></p>
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="mt-6">
                        <a href="user-edit.php?id=<?php echo $investment['user_id']; ?>" 
                           class="block text-center bg-gray-800 text-white py-2 rounded-lg hover:bg-gray-900">
                            <i class="fas fa-user-edit mr-2"></i>View User Profile
                        </a>
                    </div>
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="bg-white rounded-xl shadow">
                <div class="p-6 border-b">
                    <h3 class="text-lg font-bold">Quick Actions</h3>
                </div>
                <div class="p-6 space-y-3">
                    <?php if ($investment['status'] == 'running'): ?>
                    <button onclick="completeInvestment()" class="w-full bg-green-600 text-white py-2 rounded-lg hover:bg-green-700">
                        <i class="fas fa-check-circle mr-2"></i>Mark as Completed
                    </button>
                    
                    <button onclick="cancelInvestment()" class="w-full bg-red-600 text-white py-2 rounded-lg hover:bg-red-700">
                        <i class="fas fa-times-circle mr-2"></i>Cancel Investment
                    </button>
                    <?php endif; ?>
                    
                    <button onclick="extendInvestment()" class="w-full bg-blue-600 text-white py-2 rounded-lg hover:bg-blue-700">
                        <i class="fas fa-calendar-plus mr-2"></i>Extend Duration
                    </button>
                    
                    <button onclick="addBonus()" class="w-full bg-purple-600 text-white py-2 rounded-lg hover:bg-purple-700">
                        <i class="fas fa-gift mr-2"></i>Add Bonus
                    </button>
                    
                    <button onclick="deleteInvestment()" class="w-full bg-red-700 text-white py-2 rounded-lg hover:bg-red-800">
                        <i class="fas fa-trash-alt mr-2"></i>Delete Investment
                    </button>
                </div>
            </div>

            <!-- Investment Notes -->
            <div class="bg-white rounded-xl shadow">
                <div class="p-6 border-b">
                    <h3 class="text-lg font-bold">Investment Notes</h3>
                </div>
                <div class="p-6">
                    <div id="notesContainer">
                        <p class="text-gray-500 mb-4">No notes yet.</p>
                    </div>
                    
                    <div class="mt-4">
                        <textarea id="newNote" rows="3" 
                                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                                  placeholder="Add a note about this investment..."></textarea>
                        <button onclick="addNote()" class="mt-2 w-full bg-gray-800 text-white py-2 rounded-lg hover:bg-gray-900">
                            <i class="fas fa-plus mr-2"></i>Add Note
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modals will be added here -->
<div id="actionModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-md">
            <div class="p-6">
                <h3 id="modalTitle" class="text-xl font-bold mb-4"></h3>
                <div id="modalContent"></div>
                <div class="mt-6 flex justify-end space-x-2">
                    <button onclick="closeModal()" class="px-4 py-2 text-gray-600 hover:text-gray-800">Cancel</button>
                    <button id="modalConfirm" onclick="confirmAction()" class="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700">Confirm</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let currentAction = '';
let actionData = {};

function printInvestment() {
    window.print();
}

function completeInvestment() {
    if (confirm('Mark this investment as completed? Final profit will be calculated.')) {
        window.location.href = 'investments.php?action=complete&id=<?php echo $investment_id; ?>&from=view';
    }
}

function cancelInvestment() {
    if (confirm('Cancel this investment and return principal to user?')) {
        window.location.href = 'investments.php?action=cancel&id=<?php echo $investment_id; ?>&from=view';
    }
}

function deleteInvestment() {
    if (confirm('Delete this investment? Principal will be returned to user.')) {
        window.location.href = 'investments.php?action=delete&id=<?php echo $investment_id; ?>&from=view';
    }
}

function extendInvestment() {
    currentAction = 'extend';
    document.getElementById('modalTitle').textContent = 'Extend Investment Duration';
    document.getElementById('modalContent').innerHTML = `
        <div class="space-y-4">
            <div>
                <label class="block text-sm mb-1">Additional Days</label>
                <input type="number" id="extraDays" min="1" max="365" value="30" 
                       class="w-full px-3 py-2 border border-gray-300 rounded-lg">
            </div>
            <p class="text-sm text-gray-600">Current duration: <?php echo $total_days; ?> days</p>
        </div>
    `;
    document.getElementById('modalConfirm').textContent = 'Extend';
    document.getElementById('actionModal').classList.remove('hidden');
}

function addBonus() {
    currentAction = 'bonus';
    document.getElementById('modalTitle').textContent = 'Add Bonus to Investment';
    document.getElementById('modalContent').innerHTML = `
        <div class="space-y-4">
            <div>
                <label class="block text-sm mb-1">Bonus Amount ($)</label>
                <input type="number" id="bonusAmount" step="0.01" min="0.01" 
                       class="w-full px-3 py-2 border border-gray-300 rounded-lg">
            </div>
            <div>
                <label class="block text-sm mb-1">Reason (Optional)</label>
                <textarea id="bonusReason" rows="2" 
                          class="w-full px-3 py-2 border border-gray-300 rounded-lg"></textarea>
            </div>
        </div>
    `;
    document.getElementById('modalConfirm').textContent = 'Add Bonus';
    document.getElementById('actionModal').classList.remove('hidden');
}

function addProfit() {
    currentAction = 'add_profit';
    document.getElementById('modalTitle').textContent = 'Add Daily Profit';
    document.getElementById('modalContent').innerHTML = `
        <div class="space-y-4">
            <p>Add daily profit of $<?php echo number_format($daily_profit, 2); ?>?</p>
            <div>
                <label class="flex items-center">
                    <input type="checkbox" id="addToBalance" class="mr-2" checked>
                    <span class="text-sm">Add amount to user balance</span>
                </label>
            </div>
        </div>
    `;
    document.getElementById('modalConfirm').textContent = 'Add Profit';
    document.getElementById('actionModal').classList.remove('hidden');
}

function skipProfit() {
    if (confirm('Skip today\'s profit payout?')) {
        $.ajax({
            url: '../api/admin-actions.php',
            method: 'POST',
            data: {
                action: 'skip_profit',
                investment_id: <?php echo $investment_id; ?>
            },
            success: function(response) {
                const result = JSON.parse(response);
                showNotification(result.message, result.success ? 'success' : 'error');
                if (result.success) {
                    location.reload();
                }
            }
        });
    }
}

function confirmAction() {
    let url = '../api/admin-actions.php';
    let data = {
        action: currentAction,
        investment_id: <?php echo $investment_id; ?>
    };

    switch (currentAction) {
        case 'extend':
            const extraDays = document.getElementById('extraDays').value;
            if (!extraDays || extraDays < 1) {
                showNotification('Please enter valid number of days', 'error');
                return;
            }
            data.extra_days = extraDays;
            break;
            
        case 'bonus':
            const bonusAmount = document.getElementById('bonusAmount').value;
            const bonusReason = document.getElementById('bonusReason').value;
            if (!bonusAmount || bonusAmount <= 0) {
                showNotification('Please enter valid bonus amount', 'error');
                return;
            }
            data.bonus_amount = bonusAmount;
            data.reason = bonusReason;
            break;
            
        case 'add_profit':
            const addToBalance = document.getElementById('addToBalance').checked;
            data.add_to_balance = addToBalance;
            break;
    }

    $.ajax({
        url: url,
        method: 'POST',
        data: data,
        success: function(response) {
            const result = JSON.parse(response);
            showNotification(result.message, result.success ? 'success' : 'error');
            if (result.success) {
                closeModal();
                location.reload();
            }
        }
    });
}

function closeModal() {
    document.getElementById('actionModal').classList.add('hidden');
    currentAction = '';
}

function addNote() {
    const note = document.getElementById('newNote').value.trim();
    if (!note) {
        showNotification('Please enter a note', 'error');
        return;
    }

    $.ajax({
        url: '../api/admin-actions.php',
        method: 'POST',
        data: {
            action: 'add_investment_note',
            investment_id: <?php echo $investment_id; ?>,
            note: note
        },
        success: function(response) {
            const result = JSON.parse(response);
            showNotification(result.message, result.success ? 'success' : 'error');
            if (result.success) {
                document.getElementById('newNote').value = '';
                loadNotes();
            }
        }
    });
}

function loadNotes() {
    $.ajax({
        url: '../api/get-investment-notes.php',
        method: 'GET',
        data: { investment_id: <?php echo $investment_id; ?> },
        success: function(response) {
            document.getElementById('notesContainer').innerHTML = response;
        }
    });
}

// Load notes on page load
$(document).ready(function() {
    loadNotes();
});
</script>

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