<?php
/**
 * manage_live_accounts.php
 * ...
 */

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/session_boot.php';   // start session & idle timeout
require_once __DIR__ . '/config.php';         // provides $conn (PDO)

// --- Backward compatibility: map old 'alogin' -> 'clogin' if needed ---
if (empty($_SESSION['clogin']) && !empty($_SESSION['alogin'])) {
  $_SESSION['clogin'] = $_SESSION['alogin'];
}

require_once __DIR__ . '/auth_guard.php';     // will check $_SESSION['clogin'] and load $me

if (!isset($conn) || !($conn instanceof PDO)) {
  die('Database connection not established. Check config.php (PDO).');
}

// (rest of your file stays the same)

/* -------------------------------------------
   Delete a leverage option (DELETE)
-------------------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_option'])) {
    $lev_id = (int)($_POST['lev_id'] ?? 0);
    if ($lev_id > 0) {
        // Optional safety: block deletion if used by any liveaccount (uncomment if you store per-account leverage)
        /*
        $inUse = $conn->prepare("SELECT COUNT(*) FROM liveaccount WHERE leverage IN (
                                   SELECT account_leverage FROM leverage WHERE id = :id
                                 )");
        $inUse->execute([':id' => $lev_id]);
        if ((int)$inUse->fetchColumn() > 0) {
            echo "<script>alert('Cannot delete: this leverage is in use by one or more accounts.');history.back();</script>";
            exit;
        }
        */

        $del = $conn->prepare("DELETE FROM leverage WHERE id = :id");
        $del->execute([':id' => $lev_id]);
    }
    header("Location: " . strtok($_SERVER['REQUEST_URI'], '?'));
    exit;
}

/* ------------ AJAX: get account types by group ------------- */
/* ------------ AJAX: get account types by group (TRIM-safe) ------------- */
if (isset($_GET['action']) && $_GET['action'] === 'get_types') {
    header('Content-Type: application/json; charset=utf-8');

    $grp = isset($_GET['group']) ? trim((string)$_GET['group']) : '';
    if ($grp === '') { echo json_encode([]); exit; }

    $sql = "
        SELECT DISTINCT TRIM(account_type) AS account_type
        FROM leverage
        WHERE TRIM(account_group) = :grp
          AND COALESCE(TRIM(account_type), '') <> ''
        ORDER BY account_type
    ";
    $stmt = $conn->prepare($sql);
    $stmt->execute([':grp' => $grp]);
    $types = $stmt->fetchAll(PDO::FETCH_COLUMN);

    echo json_encode($types, JSON_UNESCAPED_UNICODE);
    exit;
}


/* -------------------------------------------
   Inline edits for leverage master (UPDATE)
-------------------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_option'])) {
    $lev_id  = (int)($_POST['lev_id'] ?? 0);
    $new_val = trim($_POST['new_account_leverage'] ?? '');

    if ($lev_id > 0 && $new_val !== '') {
        $stmt = $conn->prepare("UPDATE leverage SET account_leverage = :lev WHERE id = :id");
        $stmt->execute([':lev' => $new_val, ':id' => $lev_id]);
        header("Location: " . strtok($_SERVER['REQUEST_URI'], '?'));
        exit;
    }
}

/* -------------------------------------------
   Add a new leverage option (INSERT)
-------------------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_option'])) {
    $account_group   = trim($_POST['account_group'] ?? '');
    $account_type    = trim($_POST['account_type'] ?? '');
    $account_lev_val = trim($_POST['account_leverage'] ?? '');

    if ($account_lev_val !== '') {
        $ins = $conn->prepare("INSERT INTO leverage (account_group, account_type, account_leverage)
                               VALUES (:grp, :typ, :lev)");
        $ins->execute([
            ':grp' => $account_group ?: null,
            ':typ' => $account_type  ?: null,
            ':lev' => $account_lev_val
        ]);
        header("Location: " . strtok($_SERVER['REQUEST_URI'], '?'));
        exit;
    }
}

/* -------------------------------------------
   Fetch MT5 accounts
-------------------------------------------- */
$accounts = [];
try {
    // If you want only the logged-in user’s accounts, add WHERE email = :email
    $q = $conn->query("SELECT trade_id FROM liveaccount ORDER BY trade_id");
    $accounts = $q->fetchAll(PDO::FETCH_COLUMN);
} catch (Throwable $e) {
    // Handle silently for now
}

/* -------------------------------------------
   Fetch leverage master & group by account_type
-------------------------------------------- */
$levOptions = [];
try {
    $stmt = $conn->query("SELECT id, account_group, account_type, account_leverage
                          FROM leverage
                          ORDER BY account_type, account_leverage+0, account_leverage");
    $levOptions = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    // Handle silently for now
}

$grouped = [];
foreach ($levOptions as $row) {
    $grouped[$row['account_type']][] = $row;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1.0"/>
  <title>Update MT5 Leverage</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
  <style>
    :root{ --vm-border:#e5e7eb; --vm-orange:#CD7F32; }
    .card{ background:#fff;border:1px solid var(--vm-border);border-radius:14px;box-shadow:0 8px 24px rgba(0,0,0,.06) }
    .pill{ border:2px solid var(--vm-orange) }
    @media (min-width: 768px){ main.md\:ml-64 { margin-left: 16rem !important; } } /* keep space for fixed sidebar */
  </style>
</head>
<body class="bg-gray-100">
<?php include "header.php";?>
<div class="flex flex-col md:flex-row min-h-screen">
  <!-- Sidebar -->
  <?php include "side_bar.php";?>

  <!-- Main Content -->
  <main class="flex-1 p-6 md:ml-64">
    <!-- Top Navigation -->
    <div class="container mx-auto">
      <span class="text-[var(--vm-orange)] font-semibold text-lg">Update MT5 Leverage</span>
    </div>

    
    <!-- Manage Leverage Options (always visible list) -->
    <div class="container mx-auto px-6 mt-10">
      <div class="card p-4 max-w-5xl mx-auto">
        <h3 class="font-semibold text-gray-800 mb-4 text-lg">Manage Leverage Options</h3>

        <div class="overflow-x-auto">
          <table class="min-w-full text-sm">
            <thead>
              <tr class="bg-gray-50">
                <th class="text-left p-3 border-b">ID</th>
                <th class="text-left p-3 border-b">Account Group</th>
                <th class="text-left p-3 border-b">Account Type</th>
                <th class="text-left p-3 border-b">Leverage</th>
                <th class="text-left p-3 border-b">Action</th>
              </tr>
            </thead>
            <tbody>
              <?php if (empty($levOptions)): ?>
                <tr><td colspan="5" class="p-4 text-center text-gray-500">No rows in <code>leverage</code> table.</td></tr>
              <?php else: ?>
                <?php foreach ($levOptions as $row): ?>
                  <tr class="odd:bg-white even:bg-gray-50">
                    <td class="p-3 border-b align-middle"><?= (int)$row['id'] ?></td>
                    <td class="p-3 border-b align-middle"><?= htmlspecialchars($row['account_group'] ?? '') ?></td>
                    <td class="p-3 border-b align-middle"><?= htmlspecialchars($row['account_type'] ?? '') ?></td>
                    <td class="p-3 border-b align-middle">
                      <form method="POST" class="flex items-center gap-2">
                        <input type="hidden" name="lev_id" value="<?= (int)$row['id'] ?>">
                        <input type="text" name="new_account_leverage"
                               value="<?= htmlspecialchars($row['account_leverage'] ?? '') ?>"
                               class="w-28 p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-[var(--vm-orange)]"
                               placeholder="e.g., 100"/>
                        <button type="submit" name="update_option"
                                class="px-3 py-2 rounded-md bg-[var(--vm-orange)] text-white hover:brightness-95">
                          Update
                        </button>
                      </form>
                       <form method="POST" onsubmit="return confirm('Delete this leverage option? This cannot be undone.');">
      <input type="hidden" name="lev_id" value="<?= (int)$row['id'] ?>">
      <button type="submit" name="delete_option"
              class="px-3 py-2 rounded-md border border-red-200 text-red-600 hover:bg-red-50">
        Delete
      </button>
    </form>
                    </td>
                    <td class="p-3 border-b align-middle">
                      <span class="inline-flex items-center gap-2 text-gray-500">
                        <i class="fa-regular fa-circle-question"></i>
                        <span>Use just the number (e.g., <b>100</b> creates <b>1:100</b>).</span>
                      </span>
                    </td>
                  </tr>
                <?php endforeach; ?>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
<!-- Add New Leverage Row -->
<div class="mt-6 border-t pt-4">
  <h4 class="font-semibold mb-3">Add New Leverage</h4>

  <form method="POST" class="grid grid-cols-1 md:grid-cols-5 gap-3 items-start" id="addLeverageForm">
    <!-- Account Group (select existing groups) -->
    <div class="col-span-1">
      <label class="block text-sm text-gray-700 mb-1">Account Group</label>
      <?php
      $groups = $conn->query("
        SELECT DISTINCT TRIM(account_group) AS g
        FROM leverage
        WHERE COALESCE(TRIM(account_group), '') <> ''
        ORDER BY g
      ")->fetchAll(PDO::FETCH_COLUMN);
      ?>
      <select name="account_group" id="account_group_select"
              class="w-full p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-[var(--vm-orange)]">
        <option value="">-- Select Group --</option>
        <?php foreach ($groups as $grp): $grpTrim = trim($grp); ?>
          <option value="<?= htmlspecialchars($grpTrim) ?>"><?= htmlspecialchars($grpTrim) ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <!-- Account Type (custom dropdown with Add button inside) -->
    <div class="col-span-1">
      <label class="block text-sm text-gray-700 mb-1">Account Type</label>

      <!-- Hidden input that actually submits value -->
      <input type="hidden" name="account_type" id="account_type_value">

      <!-- Toggle button -->
      <div class="relative" id="atypeDropdown">
        <button type="button" id="atypeBtn"
                class="w-full p-2 pr-9 border border-gray-300 rounded-md text-left flex items-center justify-between focus:ring-2 focus:ring-[var(--vm-orange)]">
          <span id="atypeLabel" class="truncate text-gray-700">-- Select Type --</span>
          <i class="fa-solid fa-chevron-down text-gray-500 ml-2 absolute right-2"></i>
        </button>

        <!-- Dropdown panel -->
        <div id="atypeMenu"
             class="hidden absolute left-0 right-0 mt-1 bg-white border border-gray-200 rounded-md shadow-lg z-50">
          <div class="max-h-56 overflow-auto" id="atypeListWrapper">
            <ul id="atypeList" class="py-1 text-sm"></ul>
          </div>

          <div class="border-t p-2">
            <button type="button" id="atypeAddBtn"
                    class="w-full inline-flex items-center justify-center gap-2 px-3 py-2 rounded-md border border-dashed border-gray-300 hover:border-gray-400">
              <i class="fa-solid fa-plus"></i>
              <span>Add new type…</span>
            </button>

            <div id="atypeAddForm" class="hidden mt-2">
              <div class="flex gap-2">
                <input type="text" id="atypeNewInput" placeholder="Enter new account type"
                       class="flex-1 p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-[var(--vm-orange)]">
                <button type="button" id="atypeSaveTemp"
                        class="px-3 py-2 rounded-md bg-[var(--vm-orange)] text-white hover:brightness-95">
                  Add
                </button>
              </div>
              <p class="text-xs text-gray-500 mt-1">This will be selected now; it will be saved when you submit the form.</p>
            </div>
          </div>
        </div>
      </div>
      <p class="text-xs text-gray-500 mt-1" id="typeHelp"></p>
    </div>

    <!-- Leverage -->
    <div class="col-span-1">
      <label class="block text-sm text-gray-700 mb-1">Leverage</label>
      <input type="text" name="account_leverage" placeholder="e.g., 100"
             class="w-full p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-[var(--vm-orange)]" required>
    </div>

    <!-- Add Button (spans) -->
    <div class="col-span-1 md:col-span-2 flex items-end">
      <button type="submit" name="add_option"
              class="px-4 py-2 rounded-md bg-[var(--vm-orange)] text-white hover:brightness-95">
        Add
      </button>
    </div>
  </form>
</div>




      </div>
    </div>

  </main>
</div>
<?php include "footer.php"; ?>
<script>
(function(){
  const groupSel = document.getElementById('account_group_select');

  // Custom dropdown elements
  const dd      = document.getElementById('atypeDropdown');
  const btn     = document.getElementById('atypeBtn');
  const menu    = document.getElementById('atypeMenu');
  const list    = document.getElementById('atypeList');
  const label   = document.getElementById('atypeLabel');
  const hidden  = document.getElementById('account_type_value');
  const help    = document.getElementById('typeHelp');

  const addBtn  = document.getElementById('atypeAddBtn');
  const addWrap = document.getElementById('atypeAddForm');
  const addInp  = document.getElementById('atypeNewInput');
  const addSave = document.getElementById('atypeSaveTemp');

  function toggleMenu(show) {
    if (show === undefined) show = menu.classList.contains('hidden');
    menu.classList.toggle('hidden', !show);
  }

  function closeOnOutside(e){
    if (!dd.contains(e.target)) toggleMenu(false);
  }

  function resetTypesUI() {
    list.innerHTML = '';
    label.textContent = '-- Select Type --';
    hidden.value = '';
    help.textContent = '';
    addWrap.classList.add('hidden');
    addInp.value = '';
  }

  // Build one clickable item
  function makeItem(text) {
    const li = document.createElement('li');
    li.className = 'px-3 py-2 hover:bg-gray-50 cursor-pointer';
    li.textContent = text;
    li.addEventListener('click', () => {
      label.textContent = text;
      hidden.value = text;
      toggleMenu(false);
    });
    return li;
  }

  // Load types for selected group
  async function loadTypesForGroup(grp){
    resetTypesUI();
    if (!grp) return;

    try {
      const res   = await fetch(`<?= basename(__FILE__) ?>?action=get_types&group=${encodeURIComponent(grp)}`, {cache:'no-store'});
      const types = await res.json();

      if (Array.isArray(types) && types.length) {
        types.forEach(t => list.appendChild(makeItem(t)));
        help.textContent = 'Select a type or click “Add new type…” below.';
      } else {
        help.textContent = 'No types for this group. Click “Add new type…” to create one.';
      }
    } catch (err) {
      console.error(err);
      help.textContent = 'Could not load types. You can add a new one below.';
    }
  }

  // Events
  groupSel?.addEventListener('change', () => {
    loadTypesForGroup(groupSel.value.trim());
  });

  btn?.addEventListener('click', () => {
    // open
    toggleMenu();
    if (!menu.classList.contains('hidden') && list.children.length === 0) {
      // If opening and no items yet, try to fetch for current group
      const grp = groupSel?.value?.trim() || '';
      if (!grp) {
        help.textContent = 'Select a group first.';
      } else {
        loadTypesForGroup(grp);
      }
    }
  });

  document.addEventListener('click', closeOnOutside);
  document.addEventListener('keydown', (e) => { if (e.key === 'Escape') toggleMenu(false); });

  // Add new type inside dropdown (doesn't write DB now; selected & submitted)
  addBtn?.addEventListener('click', () => {
    addWrap.classList.toggle('hidden');
    if (!addWrap.classList.contains('hidden')) {
      addInp.focus();
    }
  });

  addSave?.addEventListener('click', () => {
    const val = (addInp.value || '').trim();
    if (!val) return;
    // Select it immediately
    label.textContent = val;
    hidden.value = val;

    // Put it at top of the list for visual confirmation
    list.prepend(makeItem(val));

    toggleMenu(false);
  });
})();
</script>


</body>
</html>
