<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();

if (!isset($_SESSION['admin_id'])) {
    header("Location: index.php");
    exit();
}

require_once "../account/include/db.php";

// --- ACTION LOGIC ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    // 1. UPDATE MARKET SETTINGS
    if ($action === 'update_settings') {
        foreach ($_POST['settings'] as $id => $value) {
            $upd_s = "UPDATE `trading_settings` SET `setting_value` = ? WHERE `id` = ?";
            if ($stmt = mysqli_prepare($conn, $upd_s)) {
                mysqli_stmt_bind_param($stmt, "si", $value, $id);
                mysqli_stmt_execute($stmt);
                mysqli_stmt_close($stmt);
            }
        }
        $_SESSION['swal_success'] = "Global trading settings updated.";
    }

    // 2. DELETE TRADE
    elseif ($action === 'delete_trade' && isset($_POST['trade_id'])) {
        $t_id = (int)$_POST['trade_id'];
        $del_q = "DELETE FROM `trades` WHERE `id` = ?";
        if ($stmt = mysqli_prepare($conn, $del_q)) {
            mysqli_stmt_bind_param($stmt, "i", $t_id);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);
            $_SESSION['swal_success'] = "Trade record deleted.";
        }
    }

    // 3. CREATE / EDIT TRADE (Manual Control)
    elseif (($action === 'add_trade' || $action === 'edit_trade')) {
        $user_id    = (int)$_POST['user_id'];
        $asset      = mysqli_real_escape_string($conn, $_POST['asset']);
        $type       = mysqli_real_escape_string($conn, $_POST['trade_type']);
        $amount     = (float)$_POST['amount'];
        $entry      = (float)$_POST['entry_price'];
        $exit       = (float)$_POST['exit_price'];
        $status     = mysqli_real_escape_string($conn, $_POST['status']);
        $market     = mysqli_real_escape_string($conn, $_POST['market']);
        
        // Logic: Calculate PnL if forcing Win/Loss
        // Win = ~90% profit, Loss = -100% loss
        $pnl = ($status === 'WIN') ? $amount * 0.9 : -$amount; 
        if ($status === 'PENDING') $pnl = 0;

        if ($action === 'add_trade') {
            $q = "INSERT INTO `trades` (user_id, asset, trade_type, amount, entry_price, exit_price, pnl, status, market, created_at) 
                  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
            $stmt = mysqli_prepare($conn, $q);
            mysqli_stmt_bind_param($stmt, "issddddss", $user_id, $asset, $type, $amount, $entry, $exit, $pnl, $status, $market);
        } else {
            $t_id = (int)$_POST['trade_id'];
            $q = "UPDATE `trades` SET user_id=?, asset=?, trade_type=?, amount=?, entry_price=?, exit_price=?, pnl=?, status=?, market=? WHERE id=?";
            $stmt = mysqli_prepare($conn, $q);
            mysqli_stmt_bind_param($stmt, "issddddssi", $user_id, $asset, $type, $amount, $entry, $exit, $pnl, $status, $market, $t_id);
        }

        if (mysqli_stmt_execute($stmt)) {
            $_SESSION['swal_success'] = "Trade data synchronized successfully.";
            $_SESSION['swal_title'] = "Success";
        }
        mysqli_stmt_close($stmt);
    }

    header("Location: market_controls.php?page=" . ($_GET['page'] ?? 1));
    exit();
}

// --- PAGINATION ---
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

$total_res = mysqli_query($conn, "SELECT COUNT(*) as total FROM `trades` ");
$total_data = mysqli_fetch_assoc($total_res);
$total_records = $total_data['total'] ?? 0;
$total_pages = ceil($total_records / $limit);

// Fetch Trades
$t_query = "SELECT t.*, u.full_name, u.username 
            FROM `trades` t 
            JOIN `users` u ON t.user_id = u.id 
            ORDER BY t.created_at DESC LIMIT $limit OFFSET $offset";
$trades = mysqli_query($conn, $t_query);

// Fetch Settings
$settings = mysqli_query($conn, "SELECT * FROM `trading_settings` ");

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
    body { font-family: 'Inter', sans-serif !important; }
    .status-badge { padding: 2px 8px; border-radius: 4px; font-size: 10px; font-weight: 800; text-transform: uppercase; }
    .btn-action { transition: all 0.2s; }
    .btn-action:hover { transform: translateY(-1px); }
</style>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<main class="md:ml-64 p-4 md:p-6 min-h-[calc(100vh-65px)] bg-slate-950 relative z-10">
    
    <div class="mb-8 flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
            <div class="text-[10px] font-bold text-blue-500 tracking-widest uppercase mb-1">Premiumtrustglobal Admin</div>
            <h1 class="text-3xl font-bold text-white tracking-tight">Market Controls</h1>
        </div>
        <button onclick="tradeModal('add')" class="bg-blue-600 hover:bg-blue-500 text-white px-5 py-2.5 rounded-lg text-sm font-bold shadow-lg shadow-blue-900/20 flex items-center gap-2 transition-all">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
            Manual Trade Entry
        </button>
    </div>

    <div class="bg-slate-900 border border-slate-800 rounded-xl p-6 mb-8 shadow-xl">
        <h3 class="text-white font-bold text-sm mb-4 flex items-center gap-2">
            <svg class="w-4 h-4 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path></svg>
            Global Trading Engine Settings
        </h3>
        <form method="POST" class="grid grid-cols-1 md:grid-cols-4 gap-6 items-end">
            <input type="hidden" name="action" value="update_settings">
            <?php while($s = mysqli_fetch_assoc($settings)): ?>
                <div>
                    <label class="text-[10px] uppercase font-bold text-slate-500 block mb-2"><?php echo str_replace('_', ' ', $s['setting_name'] ?? ''); ?></label>
                    <input type="text" name="settings[<?php echo $s['id']; ?>]" value="<?php echo htmlspecialchars($s['setting_value'] ?? ''); ?>" class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white text-sm focus:border-blue-500 outline-none">
                </div>
            <?php endwhile; ?>
            <div>
                <button type="submit" class="w-full bg-slate-800 hover:bg-slate-700 text-white py-2.5 rounded font-bold text-xs uppercase tracking-widest transition-all">Save Configuration</button>
            </div>
        </form>
    </div>

    <div class="bg-slate-900 border border-slate-800 rounded-xl overflow-hidden shadow-2xl flex flex-col">
        <div class="overflow-x-auto">
            <table class="w-full text-left border-collapse min-w-[1000px]">
                <thead>
                    <tr class="border-b border-slate-800 bg-slate-950 text-xs text-slate-400 uppercase tracking-widest">
                        <th class="p-4">User / Market</th>
                        <th class="p-4">Asset / Type</th>
                        <th class="p-4">Amount / PnL</th>
                        <th class="p-4">Entry / Exit</th>
                        <th class="p-4">Status</th>
                        <th class="p-4 text-right">Control</th>
                    </tr>
                </thead>
                <tbody class="text-sm text-slate-300 divide-y divide-slate-800/50">
                    <?php if(mysqli_num_rows($trades) > 0): ?>
                        <?php while ($row = mysqli_fetch_assoc($trades)): 
                            $is_win = ($row['status'] === 'WIN');
                            $is_pending = ($row['status'] === 'PENDING');
                        ?>
                        <tr class="hover:bg-slate-800/30 transition-colors">
                            <td class="p-4">
                                <div class="font-bold text-slate-100"><?php echo htmlspecialchars($row['full_name'] ?? ''); ?></div>
                                <div class="text-[10px] text-slate-500 uppercase font-bold tracking-tighter"><?php echo htmlspecialchars($row['market'] ?? ''); ?></div>
                            </td>
                            <td class="p-4">
                                <div class="font-bold text-blue-400"><?php echo htmlspecialchars($row['asset'] ?? ''); ?></div>
                                <div class="text-[10px] <?php echo ($row['trade_type'] ?? '') == 'BUY' ? 'text-emerald-500' : 'text-red-500'; ?> font-black"><?php echo htmlspecialchars($row['trade_type'] ?? ''); ?></div>
                            </td>
                            <td class="p-4">
                                <div class="font-mono text-slate-300">$<?php echo number_format($row['amount'] ?? 0, 2); ?></div>
                                <div class="font-mono text-xs <?php echo ($row['pnl'] ?? 0) >= 0 ? 'text-emerald-400' : 'text-red-400'; ?>">
                                    <?php echo ($row['pnl'] ?? 0) >= 0 ? '+' : ''; ?><?php echo number_format($row['pnl'] ?? 0, 2); ?>
                                </div>
                            </td>
                            <td class="p-4 font-mono text-xs">
                                <div class="text-slate-400">In: <?php echo number_format($row['entry_price'] ?? 0, 4); ?></div>
                                <div class="text-slate-500">Out: <?php echo number_format($row['exit_price'] ?? 0, 4); ?></div>
                            </td>
                            <td class="p-4">
                                <?php if($is_pending): ?>
                                    <span class="status-badge bg-amber-500/10 text-amber-500 border border-amber-500/20">Active</span>
                                <?php elseif($is_win): ?>
                                    <span class="status-badge bg-emerald-500/10 text-emerald-500 border border-emerald-500/20">Profit</span>
                                <?php else: ?>
                                    <span class="status-badge bg-red-500/10 text-red-500 border border-red-500/20">Loss</span>
                                <?php endif; ?>
                            </td>
                            <td class="p-4 text-right">
                                <div class="flex justify-end gap-3">
                                    <button onclick='tradeModal("edit", <?php echo json_encode($row); ?>)' class="text-blue-500 text-[10px] font-bold uppercase hover:underline">Edit</button>
                                    <form method="POST" class="inline" onsubmit="return confirm('Remove trade from history?');">
                                        <input type="hidden" name="trade_id" value="<?php echo $row['id']; ?>">
                                        <input type="hidden" name="action" value="delete_trade">
                                        <button type="submit" class="text-red-500 text-[10px] font-bold uppercase hover:underline">Delete</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if($total_pages > 1): ?>
        <div class="p-4 border-t border-slate-800 bg-slate-900/50 flex items-center justify-between">
            <div class="text-xs text-slate-500">Page <?php echo $page; ?> of <?php echo $total_pages; ?></div>
            <div class="flex gap-1">
                <?php if($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>" class="px-3 py-1.5 rounded border border-slate-800 text-xs text-slate-400 hover:bg-slate-800 transition-all">Prev</a>
                <?php endif; ?>
                <?php if($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>" class="px-3 py-1.5 rounded border border-slate-800 text-xs text-slate-400 hover:bg-slate-800 transition-all">Next</a>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</main>

<script>
function tradeModal(mode, data = null) {
    Swal.fire({
        title: mode === 'add' ? 'New Trade Entry' : 'Edit Trade Outcome',
        background: '#0f172a',
        color: '#f1f5f9',
        width: '600px',
        html: `
            <form id="tradeForm" method="POST" class="text-left grid grid-cols-2 gap-4 mt-4">
                <input type="hidden" name="action" value="${mode === 'add' ? 'add_trade' : 'edit_trade'}">
                ${mode === 'edit' ? `<input type="hidden" name="trade_id" value="${data.id}">` : ''}
                
                <div class="col-span-2">
                    <label class="text-[10px] uppercase font-bold text-slate-500">User ID</label>
                    <input type="number" name="user_id" value="${data ? data.user_id : ''}" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                </div>

                <div>
                    <label class="text-[10px] uppercase font-bold text-slate-500">Asset (e.g. BTC/USD)</label>
                    <input type="text" name="asset" value="${data ? data.asset : ''}" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                </div>

                <div>
                    <label class="text-[10px] uppercase font-bold text-slate-500">Market Type</label>
                    <select name="market" class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                        <option value="crypto" ${data && data.market === 'crypto' ? 'selected' : ''}>Crypto</option>
                        <option value="forex" ${data && data.market === 'forex' ? 'selected' : ''}>Forex</option>
                        <option value="stocks" ${data && data.market === 'stocks' ? 'selected' : ''}>Stocks</option>
                    </select>
                </div>

                <div>
                    <label class="text-[10px] uppercase font-bold text-slate-500">Trade Type</label>
                    <select name="trade_type" class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                        <option value="BUY" ${data && data.trade_type === 'BUY' ? 'selected' : ''}>BUY / CALL</option>
                        <option value="SELL" ${data && data.trade_type === 'SELL' ? 'selected' : ''}>SELL / PUT</option>
                    </select>
                </div>

                <div>
                    <label class="text-[10px] uppercase font-bold text-slate-500">Trade Status (Outcome)</label>
                    <select name="status" class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                        <option value="PENDING" ${data && data.status === 'PENDING' ? 'selected' : ''}>Active / Pending</option>
                        <option value="WIN" ${data && data.status === 'WIN' ? 'selected' : ''}>Force WIN</option>
                        <option value="LOSS" ${data && data.status === 'LOSS' ? 'selected' : ''}>Force LOSS</option>
                    </select>
                </div>

                <div>
                    <label class="text-[10px] uppercase font-bold text-slate-500">Trade Amount ($)</label>
                    <input type="number" step="0.01" name="amount" value="${data ? data.amount : ''}" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                </div>

                <div>
                    <label class="text-[10px] uppercase font-bold text-slate-500">Entry Price</label>
                    <input type="number" step="0.000001" name="entry_price" value="${data ? data.entry_price : ''}" class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                </div>

                <div class="col-span-2">
                    <label class="text-[10px] uppercase font-bold text-slate-500">Exit Price (Closing Price)</label>
                    <input type="number" step="0.000001" name="exit_price" value="${data ? data.exit_price : ''}" class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                </div>
            </form>
        `,
        showCancelButton: true,
        confirmButtonText: mode === 'add' ? 'Place Trade' : 'Update Outcome',
        confirmButtonColor: '#3b82f6',
        preConfirm: () => { document.getElementById('tradeForm').submit(); }
    });
}

<?php if (isset($_SESSION['swal_success'])): ?>
    Swal.fire({ title: 'Success', text: '<?php echo $_SESSION['swal_success']; ?>', icon: 'success', background: '#0f172a', color: '#f1f5f9', confirmButtonColor: '#3b82f6' });
    <?php unset($_SESSION['swal_success']); ?>
<?php endif; ?>
</script>

<?php include 'includes/footer.php'; ?>