<?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['master_id'])) {
        $master_id = (int)$_POST['master_id'];
        $del_q = "DELETE FROM `expert_traders` WHERE `id` = ?";
        if ($stmt = mysqli_prepare($conn, $del_q)) {
            mysqli_stmt_bind_param($stmt, "i", $master_id);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "Master trader removed from the system.";
                $_SESSION['swal_title'] = "Deleted";
            }
            mysqli_stmt_close($stmt);
        }
    }

    // 2. ADD ACTION
    elseif ($action === 'add') {
        $name     = mysqli_real_escape_string($conn, $_POST['name']);
        $initials = mysqli_real_escape_string($conn, $_POST['initials']);
        $spec     = mysqli_real_escape_string($conn, $_POST['specialty']);
        $foll     = (int)$_POST['followers'];
        $roi      = (float)$_POST['roi'];
        $win      = (float)$_POST['win_rate'];
        $tier     = mysqli_real_escape_string($conn, $_POST['tier']);
        $grad     = mysqli_real_escape_string($conn, $_POST['avatar_gradient']);
        $active   = (int)$_POST['is_active'];

        $add_q = "INSERT INTO `expert_traders` (`name`, `initials`, `specialty`, `followers`, `roi`, `win_rate`, `tier`, `avatar_gradient`, `is_active`, `created_at`) 
                  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
        
        if ($stmt = mysqli_prepare($conn, $add_q)) {
            mysqli_stmt_bind_param($stmt, "sssiiddsi", $name, $initials, $spec, $foll, $roi, $win, $tier, $grad, $active);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "New Expert Master '$name' created successfully.";
                $_SESSION['swal_title'] = "Created";
            }
            mysqli_stmt_close($stmt);
        }
    }

    // 3. EDIT ACTION
    elseif ($action === 'edit' && isset($_POST['master_id'])) {
        $mid      = (int)$_POST['master_id'];
        $name     = mysqli_real_escape_string($conn, $_POST['name']);
        $initials = mysqli_real_escape_string($conn, $_POST['initials']);
        $spec     = mysqli_real_escape_string($conn, $_POST['specialty']);
        $foll     = (int)$_POST['followers'];
        $roi      = (float)$_POST['roi'];
        $win      = (float)$_POST['win_rate'];
        $tier     = mysqli_real_escape_string($conn, $_POST['tier']);
        $grad     = mysqli_real_escape_string($conn, $_POST['avatar_gradient']);
        $active   = (int)$_POST['is_active'];

        $upd_q = "UPDATE `expert_traders` SET `name`=?, `initials`=?, `specialty`=?, `followers`=?, `roi`=?, `win_rate`=?, `tier`=?, `avatar_gradient`=?, `is_active`=? WHERE `id`=?";
        if ($stmt = mysqli_prepare($conn, $upd_q)) {
            mysqli_stmt_bind_param($stmt, "sssiiddsii", $name, $initials, $spec, $foll, $roi, $win, $tier, $grad, $active, $mid);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "Profile for '$name' updated.";
                $_SESSION['swal_title'] = "Updated";
            }
            mysqli_stmt_close($stmt);
        }
    }

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

$query = "SELECT * FROM `expert_traders` 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; }
    .tier-badge { font-size: 9px; font-weight: 800; text-transform: uppercase; padding: 1px 6px; border-radius: 4px; }
    .master-avatar { width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; border-radius: 10px; font-weight: 800; font-size: 14px; color: white; }
    .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">Copytrade Management</div>
            <h1 class="text-3xl font-bold text-white tracking-tight">Master Traders</h1>
            <p class="text-slate-400 mt-1 text-sm">Control the experts listed for user copying</p>
        </div>
        <button onclick="masterModal('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 Master
        </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-[900px]">
                <thead>
                    <tr class="border-b border-slate-800 bg-slate-950 text-xs text-slate-400 uppercase tracking-widest">
                        <th class="p-4">Trader Details</th>
                        <th class="p-4 text-center">Followers</th>
                        <th class="p-4 text-center">ROI / Win Rate</th>
                        <th class="p-4 text-center">Status</th>
                        <th class="p-4 text-right">Action</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="master-avatar bg-gradient-to-br <?php echo $row['avatar_gradient'] ?? 'from-slate-700 to-slate-800'; ?>">
                                        <?php echo $row['initials'] ?? '??'; ?>
                                    </div>
                                    <div>
                                        <div class="font-bold text-slate-100"><?php echo htmlspecialchars($row['name'] ?? ''); ?></div>
                                        <div class="text-[10px] text-slate-500 flex items-center gap-2">
                                            <span><?php echo htmlspecialchars($row['specialty'] ?? ''); ?></span>
                                            <span class="tier-badge bg-blue-500/10 text-blue-400 border border-blue-500/20"><?php echo htmlspecialchars($row['tier'] ?? ''); ?></span>
                                        </div>
                                    </div>
                                </div>
                            </td>
                            <td class="p-4 text-center font-bold text-slate-200">
                                <?php echo number_format($row['followers'] ?? 0); ?>
                            </td>
                            <td class="p-4 text-center">
                                <div class="text-emerald-400 font-bold"><?php echo number_format($row['roi'] ?? 0, 1); ?>% ROI</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">
                                <?php if($row['is_active']): ?>
                                    <span class="px-2 py-0.5 rounded text-[10px] uppercase font-bold bg-emerald-500/10 text-emerald-500 border border-emerald-500/20">Listed</span>
                                <?php else: ?>
                                    <span class="px-2 py-0.5 rounded text-[10px] uppercase font-bold bg-slate-800 text-slate-500 border border-slate-700">Hidden</span>
                                <?php endif; ?>
                            </td>
                            <td class="p-4 text-right">
                                <div class="flex justify-end gap-3">
                                    <button onclick='masterModal("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('Delete this Master Trader? All current followers will remain in their positions but the trader will disappear from the list.');">
                                        <input type="hidden" name="master_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="5" class="p-12 text-center text-slate-500 italic">No Master Traders 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 masterModal(mode, data = null) {
    Swal.fire({
        title: mode === 'add' ? 'New Master Trader' : 'Edit Master Profile',
        background: '#0f172a',
        color: '#f1f5f9',
        width: '600px',
        html: `
            <form id="masterForm" 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="master_id" value="${data.id}">` : ''}
                
                <div class="col-span-2 md:col-span-1">
                    <label class="text-[10px] uppercase font-bold text-slate-500">Trader 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">
                </div>

                <div class="col-span-2 md:col-span-1">
                    <label class="text-[10px] uppercase font-bold text-slate-500">Initials (2 Chars)</label>
                    <input type="text" name="initials" value="${data ? data.initials : ''}" maxlength="2" 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">Specialty (Markets)</label>
                    <input type="text" name="specialty" value="${data ? data.specialty : ''}" placeholder="e.g. Crypto / Stock Indices" 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">ROI (%)</label>
                    <input type="number" step="0.1" name="roi" value="${data ? data.roi : ''}" 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">Followers Count</label>
                    <input type="number" name="followers" value="${data ? data.followers : ''}" 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">Tier / Rank</label>
                    <input type="text" name="tier" value="${data ? data.tier : ''}" placeholder="e.g. Elite / Pro / Top" 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">Avatar Gradient (Tailwind CSS)</label>
                    <input type="text" name="avatar_gradient" value="${data ? data.avatar_gradient : 'from-blue-600 to-cyan-500'}" 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">Visibility</label>
                    <select name="is_active" class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                        <option value="1" ${data && data.is_active == 1 ? 'selected' : ''}>Visible to Users</option>
                        <option value="0" ${data && data.is_active == 0 ? 'selected' : ''}>Hidden / Archive</option>
                    </select>
                </div>
            </form>
        `,
        showCancelButton: true,
        confirmButtonText: mode === 'add' ? 'Create Master' : 'Save Changes',
        confirmButtonColor: '#3b82f6',
        preConfirm: () => { document.getElementById('masterForm').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'; ?>