<?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['signal_id'])) {
        $sig_id = (int)$_POST['signal_id'];
        $del_q = "DELETE FROM `premium_signals` WHERE `id` = ?";
        if ($stmt = mysqli_prepare($conn, $del_q)) {
            mysqli_stmt_bind_param($stmt, "i", $sig_id);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "Trading signal removed from broadcast.";
                $_SESSION['swal_title'] = "Deleted";
            }
            mysqli_stmt_close($stmt);
        }
    }

    // 2. ADD ACTION
    elseif ($action === 'add') {
        $symbol     = mysqli_real_escape_string($conn, $_POST['symbol']);
        $type       = mysqli_real_escape_string($conn, $_POST['type']);
        $entry      = (float)$_POST['entry_price'];
        $target     = (float)$_POST['target_price'];
        $sl         = (float)$_POST['stop_loss'];
        $tf         = mysqli_real_escape_string($conn, $_POST['timeframe']);
        $stat       = mysqli_real_escape_string($conn, $_POST['status']);
        $acc        = (int)$_POST['accuracy'];
        $provider   = mysqli_real_escape_string($conn, $_POST['signal_provider']);
        $tier       = mysqli_real_escape_string($conn, $_POST['provider_tier']);
        $conf       = (int)$_POST['confidence_score'];
        $market     = mysqli_real_escape_string($conn, $_POST['market']);
        $desc       = mysqli_real_escape_string($conn, $_POST['description']);

        $add_q = "INSERT INTO `premium_signals` 
                  (`symbol`, `type`, `entry_price`, `target_price`, `stop_loss`, `timeframe`, `status`, `accuracy`, `signal_provider`, `provider_tier`, `confidence_score`, `market`, `description`, `created_at`) 
                  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
        
        if ($stmt = mysqli_prepare($conn, $add_q)) {
            mysqli_stmt_bind_param($stmt, "ssdddssississ", $symbol, $type, $entry, $target, $sl, $tf, $stat, $acc, $provider, $tier, $conf, $market, $desc);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "New signal for $symbol published successfully.";
                $_SESSION['swal_title'] = "Published";
            }
            mysqli_stmt_close($stmt);
        }
    }

    // 3. EDIT ACTION
    elseif ($action === 'edit' && isset($_POST['signal_id'])) {
        $sig_id     = (int)$_POST['signal_id'];
        $symbol     = mysqli_real_escape_string($conn, $_POST['symbol']);
        $type       = mysqli_real_escape_string($conn, $_POST['type']);
        $entry      = (float)$_POST['entry_price'];
        $target     = (float)$_POST['target_price'];
        $sl         = (float)$_POST['stop_loss'];
        $tf         = mysqli_real_escape_string($conn, $_POST['timeframe']);
        $stat       = mysqli_real_escape_string($conn, $_POST['status']);
        $acc        = (int)$_POST['accuracy'];
        $provider   = mysqli_real_escape_string($conn, $_POST['signal_provider']);
        $tier       = mysqli_real_escape_string($conn, $_POST['provider_tier']);
        $conf       = (int)$_POST['confidence_score'];
        $market     = mysqli_real_escape_string($conn, $_POST['market']);
        $desc       = mysqli_real_escape_string($conn, $_POST['description']);

        $upd_q = "UPDATE `premium_signals` SET 
                  `symbol`=?, `type`=?, `entry_price`=?, `target_price`=?, `stop_loss`=?, `timeframe`=?, `status`=?, `accuracy`=?, `signal_provider`=?, `provider_tier`=?, `confidence_score`=?, `market`=?, `description`=? 
                  WHERE `id`=?";
        
        if ($stmt = mysqli_prepare($conn, $upd_q)) {
            mysqli_stmt_bind_param($stmt, "ssdddssississi", $symbol, $type, $entry, $target, $sl, $tf, $stat, $acc, $provider, $tier, $conf, $market, $desc, $sig_id);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "Signal updates for $symbol synchronized.";
                $_SESSION['swal_title'] = "Updated";
            }
            mysqli_stmt_close($stmt);
        }
    }

    header("Location: publish_signals.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 `premium_signals` ");
$total_data = mysqli_fetch_assoc($total_res);
$total_records = $total_data['total'] ?? 0;
$total_pages = ceil($total_records / $limit);

$query = "SELECT * FROM `premium_signals` 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; }
    .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">Market Intelligence</div>
            <h1 class="text-3xl font-bold text-white tracking-tight">Signal Broadcast</h1>
            <p class="text-slate-400 mt-1 text-sm">Publish and manage premium trading indicators</p>
        </div>
        <button onclick="signalModal('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>
            Create New Signal
        </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">Symbol / TF</th>
                        <th class="p-4">Entry & Targets</th>
                        <th class="p-4">Provider</th>
                        <th class="p-4 text-center">Confidence</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="font-bold text-slate-100"><?php echo htmlspecialchars($row['symbol'] ?? 'N/A'); ?></div>
                                <div class="text-[10px] text-blue-400 font-bold tracking-widest"><?php echo htmlspecialchars($row['timeframe'] ?? ''); ?> • <?php echo htmlspecialchars($row['market'] ?? ''); ?></div>
                            </td>
                            <td class="p-4">
                                <div class="text-xs text-slate-400">Entry: <span class="text-slate-100 font-mono"><?php echo number_format($row['entry_price'] ?? 0, 4); ?></span></div>
                                <div class="text-[11px] text-emerald-400">TP: <?php echo number_format($row['target_price'] ?? 0, 4); ?></div>
                                <div class="text-[11px] text-red-400">SL: <?php echo number_format($row['stop_loss'] ?? 0, 4); ?></div>
                            </td>
                            <td class="p-4">
                                <div class="font-bold text-slate-200"><?php echo htmlspecialchars($row['signal_provider'] ?? ''); ?></div>
                                <div class="text-[10px] text-slate-500 uppercase tracking-tighter"><?php echo htmlspecialchars($row['provider_tier'] ?? 'Standard'); ?> Tier</div>
                            </td>
                            <td class="p-4 text-center">
                                <div class="text-blue-400 font-bold"><?php echo ($row['confidence_score'] ?? 0); ?>%</div>
                                <div class="text-[10px] text-slate-500">Accuracy: <?php echo ($row['accuracy'] ?? 0); ?>%</div>
                            </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">Active</span>
                                <?php elseif(($row['status'] ?? '') == 'closed'): ?>
                                    <span class="status-pill bg-slate-800 text-slate-500 border border-slate-700">Closed</span>
                                <?php else: ?>
                                    <span class="status-pill bg-amber-500/10 text-amber-500 border border-amber-500/20"><?php echo htmlspecialchars($row['status'] ?? 'Pending'); ?></span>
                                <?php endif; ?>
                            </td>
                            <td class="p-4 text-right">
                                <div class="flex justify-end gap-3">
                                    <button onclick='signalModal("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('Archive this signal broadcast?');">
                                        <input type="hidden" name="signal_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 signals found in the database.</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 signalModal(mode, data = null) {
    Swal.fire({
        title: mode === 'add' ? 'Publish Premium Signal' : 'Modify Signal Parameters',
        background: '#0f172a',
        color: '#f1f5f9',
        width: '800px',
        html: `
            <form id="signalForm" 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="signal_id" value="${data.id}">` : ''}
                
                <div class="col-span-2 md:col-span-1">
                    <label class="text-[10px] uppercase font-bold text-slate-500">Asset Symbol</label>
                    <input type="text" name="symbol" value="${data ? data.symbol : ''}" placeholder="e.g. BTC/USD or EUR/USD" 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 md:col-span-1">
                    <label class="text-[10px] uppercase font-bold text-slate-500">Market Category</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' : ''}>Cryptocurrency</option>
                        <option value="forex" ${data && data.market === 'forex' ? 'selected' : ''}>Forex Market</option>
                        <option value="stocks" ${data && data.market === 'stocks' ? 'selected' : ''}>Stock Market</option>
                        <option value="commodities" ${data && data.market === 'commodities' ? 'selected' : ''}>Commodities</option>
                    </select>
                </div>

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

                <div>
                    <label class="text-[10px] uppercase font-bold text-slate-500">Timeframe</label>
                    <input type="text" name="timeframe" value="${data ? data.timeframe : ''}" placeholder="e.g. 15M, 1H, 4H" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                </div>

                <div class="grid grid-cols-3 gap-2 col-span-2">
                    <div>
                        <label class="text-[10px] uppercase font-bold text-slate-500">Entry Price</label>
                        <input type="number" step="0.00000001" name="entry_price" value="${data ? data.entry_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">Take Profit</label>
                        <input type="number" step="0.00000001" name="target_price" value="${data ? data.target_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">Stop Loss</label>
                        <input type="number" step="0.00000001" name="stop_loss" value="${data ? data.stop_loss : ''}" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                    </div>
                </div>

                <div class="col-span-2 md:col-span-1">
                    <label class="text-[10px] uppercase font-bold text-slate-500">Signal Provider Name</label>
                    <input type="text" name="signal_provider" value="${data ? data.signal_provider : ''}" placeholder="e.g. Alpha Analyst" 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 md:col-span-1">
                    <label class="text-[10px] uppercase font-bold text-slate-500">Provider Tier</label>
                    <select name="provider_tier" class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                        <option value="Standard" ${data && data.provider_tier === 'Standard' ? 'selected' : ''}>Standard Tier</option>
                        <option value="Premium" ${data && data.provider_tier === 'Premium' ? 'selected' : ''}>Premium Tier</option>
                        <option value="Elite" ${data && data.provider_tier === 'Elite' ? 'selected' : ''}>Elite Tier</option>
                    </select>
                </div>

                <div>
                    <label class="text-[10px] uppercase font-bold text-slate-500">Confidence (%)</label>
                    <input type="number" name="confidence_score" value="${data ? data.confidence_score : ''}" 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">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' : ''}>Live Broadcast</option>
                        <option value="closed" ${data && data.status === 'closed' ? 'selected' : ''}>Closed / Expired</option>
                        <option value="pending" ${data && data.status === 'pending' ? 'selected' : ''}>Awaiting Entry</option>
                    </select>
                </div>

                <div class="col-span-2">
                    <label class="text-[10px] uppercase font-bold text-slate-500">Expected Accuracy (%)</label>
                    <input type="number" name="accuracy" value="${data ? data.accuracy : ''}" 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">Technical Brief / Description</label>
                    <textarea name="description" 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>
            </form>
        `,
        showCancelButton: true,
        confirmButtonText: mode === 'add' ? 'Publish Signal' : 'Save Changes',
        confirmButtonColor: '#3b82f6',
        preConfirm: () => { document.getElementById('signalForm').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'; ?>