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

// Redirect to login if the admin is not authenticated
if (!isset($_SESSION['admin_id'])) {
    header("Location: index.php");
    exit();
}

// Include Database Connection
require_once "../account/include/db.php";

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

    // 1. DELETE ACTION
    if ($action === 'delete' && isset($_POST['bot_id'])) {
        $bot_id = (int)$_POST['bot_id'];
        $del_q = "DELETE FROM `ai_trading_bots` WHERE `id` = ?";
        if ($stmt = mysqli_prepare($conn, $del_q)) {
            mysqli_stmt_bind_param($stmt, "i", $bot_id);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "AI Bot has been permanently decommissioned.";
                $_SESSION['swal_title'] = "Bot Deleted";
            }
            mysqli_stmt_close($stmt);
        }
    }

    // 2. ADD ACTION
    elseif ($action === 'add') {
        $name        = mysqli_real_escape_string($conn, $_POST['name']);
        $desc        = mysqli_real_escape_string($conn, $_POST['description']);
        $price       = (float)$_POST['price'];
        $m_return    = (float)$_POST['monthly_return'];
        $win_rate    = (float)$_POST['win_rate'];
        $risk        = mysqli_real_escape_string($conn, $_POST['risk_level']);
        $trades      = (int)$_POST['trades_per_day'];
        $model       = mysqli_real_escape_string($conn, $_POST['ai_model']);
        $status      = mysqli_real_escape_string($conn, $_POST['status']);
        $icon        = mysqli_real_escape_string($conn, $_POST['icon']);
        $gradient    = mysqli_real_escape_string($conn, $_POST['gradient']);
        $min_bal     = (float)$_POST['min_balance'];

        $add_q = "INSERT INTO `ai_trading_bots` 
                  (`name`, `description`, `price`, `monthly_return`, `win_rate`, `risk_level`, `trades_per_day`, `ai_model`, `status`, `icon`, `gradient`, `min_balance`, `created_at`) 
                  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
        
        if ($stmt = mysqli_prepare($conn, $add_q)) {
            mysqli_stmt_bind_param($stmt, "ssdddsissssd", $name, $desc, $price, $m_return, $win_rate, $risk, $trades, $model, $status, $icon, $gradient, $min_bal);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "New AI Model '$name' is now live.";
                $_SESSION['swal_title'] = "Success";
            }
            mysqli_stmt_close($stmt);
        }
    }

    // 3. EDIT ACTION
    elseif ($action === 'edit' && isset($_POST['bot_id'])) {
        $bot_id      = (int)$_POST['bot_id'];
        $name        = mysqli_real_escape_string($conn, $_POST['name']);
        $desc        = mysqli_real_escape_string($conn, $_POST['description']);
        $price       = (float)$_POST['price'];
        $m_return    = (float)$_POST['monthly_return'];
        $win_rate    = (float)$_POST['win_rate'];
        $risk        = mysqli_real_escape_string($conn, $_POST['risk_level']);
        $trades      = (int)$_POST['trades_per_day'];
        $model       = mysqli_real_escape_string($conn, $_POST['ai_model']);
        $status      = mysqli_real_escape_string($conn, $_POST['status']);
        $icon        = mysqli_real_escape_string($conn, $_POST['icon']);
        $gradient    = mysqli_real_escape_string($conn, $_POST['gradient']);
        $min_bal     = (float)$_POST['min_balance'];

        $upd_q = "UPDATE `ai_trading_bots` SET 
                  `name`=?, `description`=?, `price`=?, `monthly_return`=?, `win_rate`=?, `risk_level`=?, `trades_per_day`=?, `ai_model`=?, `status`=?, `icon`=?, `gradient`=?, `min_balance`=? 
                  WHERE `id`=?";
        
        if ($stmt = mysqli_prepare($conn, $upd_q)) {
            mysqli_stmt_bind_param($stmt, "ssdddsissssdi", $name, $desc, $price, $m_return, $win_rate, $risk, $trades, $model, $status, $icon, $gradient, $min_bal, $bot_id);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "Configuration for '$name' updated.";
                $_SESSION['swal_title'] = "Updated";
            }
            mysqli_stmt_close($stmt);
        }
    }

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

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

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

$query = "SELECT * FROM `ai_trading_bots` ORDER BY `created_at` DESC LIMIT $limit OFFSET $offset";
$result = mysqli_query($conn, $query);

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

<style>
    body { font-family: 'Inter', sans-serif !important; }
    .status-pill { padding: 2px 8px; border-radius: 4px; font-size: 10px; font-weight: 700; text-transform: uppercase; }
    .bot-icon-bg { width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; }
    .pagination-btn { transition: all 0.2s; border: 1px solid #1e293b; color: #94a3b8; }
    .pagination-btn.active { background: #3b82f6; border-color: #3b82f6; color: white; }
</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">Trading Algorithms</div>
            <h1 class="text-3xl font-bold text-white tracking-tight">AI Bot Configuration</h1>
            <p class="text-slate-400 mt-1 text-sm">Configure and manage automated trading intelligence</p>
        </div>
        <button onclick="botModal('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>
            Add New Bot
        </button>
    </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">Bot Identifier</th>
                        <th class="p-4">Pricing & Entry</th>
                        <th class="p-4 text-center">ROI & Accuracy</th>
                        <th class="p-4 text-center">Risk Level</th>
                        <th class="p-4 text-center">Status</th>
                        <th class="p-4 text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="text-sm text-slate-300 divide-y divide-slate-800/50">
                    <?php if($result && mysqli_num_rows($result) > 0): ?>
                        <?php while ($row = mysqli_fetch_assoc($result)): ?>
                        <tr class="hover:bg-slate-800/30 transition-colors">
                            <td class="p-4">
                                <div class="flex items-center gap-3">
                                    <div class="bot-icon-bg bg-gradient-to-br <?php echo htmlspecialchars($row['gradient'] ?? 'from-slate-700 to-slate-800'); ?> text-white font-bold">
                                        <?php echo substr($row['name'] ?? 'B', 0, 1); ?>
                                    </div>
                                    <div>
                                        <div class="font-bold text-slate-100"><?php echo htmlspecialchars($row['name'] ?? 'Unknown Bot'); ?></div>
                                        <div class="text-[10px] text-slate-500 font-mono uppercase"><?php echo htmlspecialchars($row['ai_model'] ?? 'N/A'); ?></div>
                                    </div>
                                </div>
                            </td>
                            <td class="p-4">
                                <div class="text-white font-bold">$<?php echo number_format($row['price'] ?? 0, 2); ?> <span class="text-[10px] text-slate-500 font-normal">Fee</span></div>
                                <div class="text-[11px] text-slate-400">Min Bal: $<?php echo number_format($row['min_balance'] ?? 0, 2); ?></div>
                            </td>
                            <td class="p-4 text-center">
                                <div class="text-emerald-400 font-bold"><?php echo number_format($row['monthly_return'] ?? 0, 1); ?>% Monthly</div>
                                <div class="text-[10px] text-slate-500"><?php echo number_format($row['win_rate'] ?? 0, 1); ?>% Win Rate</div>
                            </td>
                            <td class="p-4 text-center">
                                <span class="status-pill <?php echo ($row['risk_level'] == 'high') ? 'bg-red-500/10 text-red-400 border border-red-500/20' : 'bg-blue-500/10 text-blue-400 border border-blue-500/20'; ?>">
                                    <?php echo htmlspecialchars($row['risk_level'] ?? 'Normal'); ?>
                                </span>
                            </td>
                            <td class="p-4 text-center">
                                <?php if(($row['status'] ?? '') == 'active'): ?>
                                    <span class="status-pill bg-emerald-500/10 text-emerald-500 border border-emerald-500/20">Available</span>
                                <?php else: ?>
                                    <span class="status-pill bg-slate-800 text-slate-500 border border-slate-700">Disabled</span>
                                <?php endif; ?>
                            </td>
                            <td class="p-4 text-right">
                                <div class="flex justify-end gap-3">
                                    <button onclick='botModal("edit", <?php echo json_encode($row); ?>)' class="text-blue-500 text-[10px] font-bold uppercase hover:underline">Configure</button>
                                    <form method="POST" class="inline" onsubmit="return confirm('Permanently remove this bot configuration?');">
                                        <input type="hidden" name="bot_id" value="<?php echo $row['id']; ?>">
                                        <input type="hidden" name="action" value="delete">
                                        <button type="submit" class="text-red-500 text-[10px] font-bold uppercase hover:underline">Delete</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr><td colspan="6" class="p-12 text-center text-slate-500 italic">No AI Bots configured in the library.</td></tr>
                    <?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 font-medium">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="pagination-btn px-3 py-1.5 rounded text-xs">Prev</a>
                <?php endif; ?>
                <?php for($i = max(1, $page-1); $i <= min($total_pages, $page+1); $i++): ?>
                    <a href="?page=<?php echo $i; ?>" class="pagination-btn px-3 py-1.5 rounded text-xs <?php echo ($i == $page) ? 'active' : ''; ?>"><?php echo $i; ?></a>
                <?php endfor; ?>
                <?php if($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>" class="pagination-btn px-3 py-1.5 rounded text-xs">Next</a>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</main>

<script>
function botModal(mode, data = null) {
    Swal.fire({
        title: mode === 'add' ? 'Architect New AI Bot' : 'Reconfigure Bot Intelligence',
        background: '#0f172a',
        color: '#f1f5f9',
        width: '800px',
        html: `
            <form id="botForm" method="POST" class="text-left grid grid-cols-2 gap-4 mt-4">
                <input type="hidden" name="action" value="${mode === 'add' ? 'add' : 'edit'}">
                ${mode === 'edit' ? `<input type="hidden" name="bot_id" value="${data.id}">` : ''}
                
                <div class="col-span-2 md:col-span-1">
                    <label class="text-[10px] uppercase font-bold text-slate-500">Bot Name</label>
                    <input type="text" name="name" value="${data ? data.name : ''}" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1 shadow-sm">
                </div>

                <div class="col-span-2 md:col-span-1">
                    <label class="text-[10px] uppercase font-bold text-slate-500">AI Model / Engine</label>
                    <input type="text" name="ai_model" value="${data ? data.ai_model : ''}" placeholder="e.g. GPT-NeoX / Quantum-v2" required 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">Short Description</label>
                    <textarea name="description" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1 h-20 text-sm">${data ? data.description : ''}</textarea>
                </div>

                <div>
                    <label class="text-[10px] uppercase font-bold text-slate-500">Monthly ROI (%)</label>
                    <input type="number" step="0.1" name="monthly_return" value="${data ? data.monthly_return : ''}" 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">Win Rate (%)</label>
                    <input type="number" step="0.1" name="win_rate" value="${data ? data.win_rate : ''}" 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">Setup Price ($)</label>
                    <input type="number" step="0.01" name="price" value="${data ? data.price : ''}" 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">Min. Deposit ($)</label>
                    <input type="number" step="0.01" name="min_balance" value="${data ? data.min_balance : ''}" 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">Risk Level</label>
                    <select name="risk_level" class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                        <option value="low" ${data && data.risk_level === 'low' ? 'selected' : ''}>Low Risk</option>
                        <option value="medium" ${data && data.risk_level === 'medium' ? 'selected' : ''}>Medium Risk</option>
                        <option value="high" ${data && data.risk_level === 'high' ? 'selected' : ''}>High Risk</option>
                    </select>
                </div>

                <div>
                    <label class="text-[10px] uppercase font-bold text-slate-500">Daily Trade Frequency</label>
                    <input type="number" name="trades_per_day" value="${data ? data.trades_per_day : ''}" 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">Activation Status</label>
                    <select name="status" class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                        <option value="active" ${data && data.status === 'active' ? 'selected' : ''}>Active / Listed</option>
                        <option value="inactive" ${data && data.status === 'inactive' ? 'selected' : ''}>Maintenance / Hidden</option>
                    </select>
                </div>

                <div>
                    <label class="text-[10px] uppercase font-bold text-slate-500">Card Gradient Class</label>
                    <input type="text" name="gradient" value="${data ? data.gradient : 'from-blue-600 to-indigo-600'}" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1 font-mono text-xs">
                </div>

                <div class="col-span-2">
                    <label class="text-[10px] uppercase font-bold text-slate-500">Display Icon (SVG path or Lucide name)</label>
                    <input type="text" name="icon" value="${data ? data.icon : 'cpu'}" placeholder="e.g. cpu, activity, Zap" class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1 font-mono text-xs">
                </div>
            </form>
        `,
        showCancelButton: true,
        confirmButtonText: mode === 'add' ? 'Construct Bot' : 'Save Configuration',
        confirmButtonColor: '#3b82f6',
        preConfirm: () => { document.getElementById('botForm').submit(); }
    });
}

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

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