<?php
session_start();
include('../includes/config.php');

$date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
$bot_plan = isset($_GET['bot_plan']) ? intval($_GET['bot_plan']) : 0;
$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;

// Get daily summary
$summary_sql = "SELECT 
    SUM(CASE WHEN type = 'profit' THEN amount ELSE 0 END) as total_profit,
    SUM(CASE WHEN type = 'loss' THEN amount ELSE 0 END) as total_loss,
    COUNT(*) as total_trades
    FROM transactions 
    WHERE type IN ('profit', 'loss')
    AND status = 'completed'
    AND DATE(date) = '$date'";

if ($bot_plan > 0) {
    $summary_sql .= " AND related_id IN (SELECT id FROM user_bot_subscriptions WHERE bot_plan_id = $bot_plan)";
}
if ($user_id > 0) {
    $summary_sql .= " AND user_id = $user_id";
}

$summary_result = mysqli_query($conn, $summary_sql);
$summary = mysqli_fetch_assoc($summary_result);

// Get top trades for the day
$top_trades_sql = "SELECT 
    t.*,
    u.username,
    p.plan_name
    FROM transactions t
    LEFT JOIN users u ON t.user_id = u.id
    LEFT JOIN user_bot_subscriptions s ON t.related_id = s.id AND t.related_type = 'subscription'
    LEFT JOIN trading_bot_plans p ON s.bot_plan_id = p.id
    WHERE t.type IN ('profit', 'loss')
    AND t.status = 'completed'
    AND DATE(t.date) = '$date'";

if ($bot_plan > 0) {
    $top_trades_sql .= " AND s.bot_plan_id = $bot_plan";
}
if ($user_id > 0) {
    $top_trades_sql .= " AND t.user_id = $user_id";
}

$top_trades_sql .= " ORDER BY t.amount DESC LIMIT 10";
$top_trades_result = mysqli_query($conn, $top_trades_sql);

$net_pl = ($summary['total_profit'] ?: 0) - ($summary['total_loss'] ?: 0);
$win_rate = ($summary['total_trades'] ?: 0) > 0 ? ($summary['total_profit'] / ($summary['total_profit'] + $summary['total_loss']) * 100) : 0;
?>

<div class="container-fluid">
    <h4 class="mb-4">Trading Details for <?php echo date('F d, Y', strtotime($date)); ?></h4>
    
    <!-- Summary Stats -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card bg-light">
                <div class="card-body text-center">
                    <h5 class="card-title text-success">$<?php echo number_format($summary['total_profit'] ?: 0, 2); ?></h5>
                    <p class="card-text">Total Profit</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-light">
                <div class="card-body text-center">
                    <h5 class="card-title text-danger">$<?php echo number_format($summary['total_loss'] ?: 0, 2); ?></h5>
                    <p class="card-text">Total Loss</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-light">
                <div class="card-body text-center">
                    <h5 class="card-title <?php echo $net_pl >= 0 ? 'text-success' : 'text-danger'; ?>">
                        $<?php echo number_format($net_pl, 2); ?>
                    </h5>
                    <p class="card-text">Net P/L</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-light">
                <div class="card-body text-center">
                    <h5 class="card-title text-info"><?php echo number_format($win_rate, 1); ?>%</h5>
                    <p class="card-text">Win Rate</p>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Top Trades Table -->
    <div class="row">
        <div class="col-md-12">
            <h5>Top Trades of the Day</h5>
            <div class="table-responsive">
                <table class="table table-sm table-hover">
                    <thead>
                        <tr>
                            <th>Time</th>
                            <th>User</th>
                            <th>Type</th>
                            <th>Amount</th>
                            <th>Bot Plan</th>
                            <th>Description</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (mysqli_num_rows($top_trades_result) > 0): ?>
                            <?php while ($trade = mysqli_fetch_assoc($top_trades_result)): ?>
                                <tr>
                                    <td><?php echo date('H:i:s', strtotime($trade['created_at'])); ?></td>
                                    <td><?php echo htmlspecialchars($trade['username']); ?></td>
                                    <td>
                                        <span class="badge bg-<?php echo $trade['type'] == 'profit' ? 'success' : 'danger'; ?>">
                                            <?php echo ucfirst($trade['type']); ?>
                                        </span>
                                    </td>
                                    <td class="fw-500 <?php echo $trade['type'] == 'profit' ? 'text-success' : 'text-danger'; ?>">
                                        $<?php echo number_format($trade['amount'], 2); ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($trade['plan_name'] ?: 'N/A'); ?></td>
                                    <td><?php echo htmlspecialchars($trade['description']); ?></td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="6" class="text-center">No trades found for this day</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <!-- Bot Performance -->
    <div class="row mt-4">
        <div class="col-md-12">
            <h5>Bot Performance Breakdown</h5>
            <?php
            $bot_performance_sql = "SELECT 
                p.plan_name,
                COUNT(t.id) as trade_count,
                SUM(CASE WHEN t.type = 'profit' THEN t.amount ELSE 0 END) as profit,
                SUM(CASE WHEN t.type = 'loss' THEN t.amount ELSE 0 END) as loss
                FROM transactions t
                LEFT JOIN user_bot_subscriptions s ON t.related_id = s.id AND t.related_type = 'subscription'
                LEFT JOIN trading_bot_plans p ON s.bot_plan_id = p.id
                WHERE t.type IN ('profit', 'loss')
                AND t.status = 'completed'
                AND DATE(t.date) = '$date'
                GROUP BY p.id
                ORDER BY profit DESC";
            
            $bot_performance_result = mysqli_query($conn, $bot_performance_sql);
            ?>
            
            <div class="table-responsive">
                <table class="table table-sm">
                    <thead>
                        <tr>
                            <th>Bot Plan</th>
                            <th>Trades</th>
                            <th>Profit</th>
                            <th>Loss</th>
                            <th>Net P/L</th>
                            <th>Performance</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (mysqli_num_rows($bot_performance_result) > 0): ?>
                            <?php while ($bot = mysqli_fetch_assoc($bot_performance_result)): 
                                $bot_net = $bot['profit'] - $bot['loss'];
                                ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($bot['plan_name']); ?></td>
                                    <td><?php echo $bot['trade_count']; ?></td>
                                    <td class="text-success">$<?php echo number_format($bot['profit'], 2); ?></td>
                                    <td class="text-danger">$<?php echo number_format($bot['loss'], 2); ?></td>
                                    <td class="fw-500 <?php echo $bot_net >= 0 ? 'text-success' : 'text-danger'; ?>">
                                        $<?php echo number_format($bot_net, 2); ?>
                                    </td>
                                    <td>
                                        <div class="progress" style="height: 8px;">
                                            <div class="progress-bar <?php echo $bot_net >= 0 ? 'bg-success' : 'bg-danger'; ?>" 
                                                 style="width: <?php echo min(abs($bot_net) / max($bot['profit'], 1) * 100, 100); ?>%"></div>
                                        </div>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="6" class="text-center">No bot performance data</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>