<?php
// add_bonus.php
session_start();
ini_set('display_errors', 1);
error_reporting(0);

require_once 'config.php';
require_once 'auth_guard.php';
// -------------------------
// CSRF Token
// -------------------------
if (empty($_SESSION['csrf_bonus'])) {
  $_SESSION['csrf_bonus'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_bonus'];

// -------------------------
// Helpers
// -------------------------
function respond_json($arr){ header('Content-Type: application/json; charset=utf-8'); echo json_encode($arr, JSON_UNESCAPED_UNICODE); exit; }

// -------------------------
// AJAX: search users
// -------------------------
if (isset($_GET['ajax']) && $_GET['ajax'] === 'search_users') {
  $q = trim($_GET['q'] ?? '');
  $rows = [];
  if ($q !== '') {
    $like = "%$q%";
    $stmt = $conn->prepare("
      SELECT email,
             COALESCE(NULLIF(TRIM(fullname),''), NULLIF(TRIM(username),''), email) AS display_name
      FROM aspnetusers
      WHERE email LIKE :q OR username LIKE :q OR fullname LIKE :q
      ORDER BY display_name ASC
      LIMIT 20
    ");
    $stmt->execute([':q'=>$like]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  }
  respond_json(['ok'=>true, 'users'=>$rows]);
}

// -------------------------
// AJAX: search accounts
// -------------------------
if (isset($_GET['ajax']) && $_GET['ajax'] === 'search_accounts') {
  $q = trim($_GET['q'] ?? '');
  $rows = [];
  if ($q !== '') {
    $like = "%$q%";
    $stmt = $conn->prepare("
      SELECT trade_id, email
      FROM liveaccount
      WHERE trade_id LIKE :q OR email LIKE :q
      ORDER BY trade_id ASC
      LIMIT 20
    ");
    $stmt->execute([':q'=>$like]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  }
  respond_json(['ok'=>true, 'accounts'=>$rows]);
}

// -------------------------
// AJAX: accounts for a user
// -------------------------
if (isset($_GET['ajax']) && $_GET['ajax'] === 'accounts') {
  $email = trim($_GET['email'] ?? '');
  $rows = [];
  if ($email !== '') {
    $stmt = $conn->prepare("SELECT trade_id FROM liveaccount WHERE email = :email ORDER BY trade_id ASC");
    $stmt->execute([':email'=>$email]);
    $rows = $stmt->fetchAll(PDO::FETCH_COLUMN);
  }
  respond_json(['ok'=>true, 'accounts'=>$rows]);
}

// -------------------------
// Fetch all users for select
// -------------------------
$users = [];
try {
  $stmt = $conn->query("
    SELECT email, COALESCE(NULLIF(TRIM(fullname),''), NULLIF(TRIM(username),''), email) AS display_name
    FROM aspnetusers
    ORDER BY display_name ASC
  ");
  $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
  $users = [];
}

// -------------------------
// MT5 deposit helper
// -------------------------
// Make sure this matches your view_wallet_deposit setup. You can centralize constants in config.php if you prefer.
function mt5_credit_bonus(string $trade_id, float $amount, string $comment='Bonus'){
  // Path & class names must match your project (same as view_wallet_deposit)
  $apiPath = __DIR__ . "/mt5_api/mt5_api.php";
  if (!file_exists($apiPath)) throw new Exception("MT5 API script not found at $apiPath");
  require_once $apiPath;

  // Reuse the same constants you use in view_wallet_deposit
  if (!defined('AGENT'))                  define('AGENT', 'WebAPIBonusCredit');
  if (!defined('PATH_TO_LOGS'))           define('PATH_TO_LOGS', __DIR__ . '/logs');
  if (!defined('MT5_CRYPT_PROTOCOL'))     define('MT5_CRYPT_PROTOCOL', true);
  if (!defined('IS_WRITE_DEBUG_LOG'))     define('IS_WRITE_DEBUG_LOG', true);
  if (!defined('MT5_CONNECTION_TIMEOUT')) define('MT5_CONNECTION_TIMEOUT', 5);

  // IMPORTANT: Set these to the same values you use in view_wallet_deposit:
  if (!defined('MT5_SERVER_IP'))           define('MT5_SERVER_IP',    "access.tgshost.org");
  if (!defined('MT5_SERVER_PORT'))         define('MT5_SERVER_PORT',  "26043");
  if (!defined('MT5_SERVER_WEB_LOGIN'))    define('MT5_SERVER_WEB_LOGIN', "7020");
  if (!defined('MT5_SERVER_WEB_PASSWORD')) define('MT5_SERVER_WEB_PASSWORD', "Aa@123456");
//   define("MT5_SERVER_IP", "access.tgshost.org");
// define("MT5_SERVER_PORT", "26043");
// define("MT5_SERVER_WEB_LOGIN", "7020");
// define("MT5_SERVER_WEB_PASSWORD", "Aa@123456");

  $api = new MTWebAPI(AGENT, PATH_TO_LOGS, MT5_CRYPT_PROTOCOL);
  $api->SetLoggerWriteDebug(IS_WRITE_DEBUG_LOG);

  $rc = $api->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, MT5_CONNECTION_TIMEOUT, MT5_SERVER_WEB_LOGIN, MT5_SERVER_WEB_PASSWORD);
  if ($rc != MTRetCode::MT_RET_OK) throw new Exception("MT5 connect failed (code $rc)");

  // Verify account (optional but recommended)
  $account = null;
  $rc = $api->UserAccountGet($trade_id, $account);
  if ($rc != MTRetCode::MT_RET_OK) throw new Exception("MT5 account fetch failed (code $rc)");

  $dealType = MTEnDealAction::DEAL_BALANCE;           // balance operation
  $cmt = trim($comment) !== '' ? $comment : 'Bonus';  // ensure non-empty
  $rc = $api->UserDepositChange($trade_id, (float)$amount, $cmt, $dealType);
  if ($rc != MTRetCode::MT_RET_OK) throw new Exception("MT5 deposit failed (code $rc)");

  return true;
}

// -------------------------
// Handle submit
// -------------------------
$flash = ['type'=>null,'msg'=>null];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $posted_csrf = $_POST['csrf'] ?? '';
  $user_email  = trim($_POST['user_email'] ?? '');
  $trade_id    = trim($_POST['trade_id'] ?? '');
  $amount      = trim($_POST['bonus_amount'] ?? '');
  $comment     = trim($_POST['comment'] ?? '');

  if (!hash_equals($csrf, $posted_csrf)) {
    $flash = ['type'=>'error','msg'=>'Invalid request (CSRF). Please refresh and try again.'];
  } elseif ($user_email === '' || $trade_id === '' || $amount === '' || !is_numeric($amount) || (float)$amount <= 0) {
    $flash = ['type'=>'error','msg'=>'Please select user, account and enter a positive amount.'];
  } else {
    $amount_f = number_format((float)$amount, 2, '.', '');

    // ensure the (user_email, trade_id) pair is valid
    $okPair = false;
    try {
      $chk = $conn->prepare("SELECT 1 FROM liveaccount WHERE email = :email AND trade_id = :tid LIMIT 1");
      $chk->execute([':email'=>$user_email, ':tid'=>$trade_id]);
      $okPair = (bool)$chk->fetchColumn();
    } catch (Throwable $e) {}

    if (!$okPair) {
      $flash = ['type'=>'error','msg'=>'Selected account does not belong to the chosen user.'];
    } else {
      try {
        $conn->beginTransaction();

        // 1) Insert log into bonus table (adjust columns if your schema differs)
        try {
          $insBonus = $conn->prepare("INSERT INTO bonus (email, trade_id, amount, comment, created_at)
                                      VALUES (:email, :trade_id, :amount, :comment, NOW())");
          $insBonus->execute([
            ':email'    => $user_email,
            ':trade_id' => $trade_id,
            ':amount'   => $amount_f,
            ':comment'  => $comment
          ]);
        } catch (Throwable $e) {
          // If your bonus table has different columns, tweak the query above.
          // Uncomment next line to enforce strict failure:
          // throw $e;
        }

        // 2) Insert into total_balance (deposit)
        $insTB = $conn->prepare("INSERT INTO total_balance
                                  (email, trade_id, deposit_amount, deposit_type, status)
                                  VALUES (:email, :trade_id, :deposit_amount, :deposit_type, :status)");
        $insTB->execute([
          ':email'          => $user_email,
          ':trade_id'       => $trade_id,
          ':deposit_amount' => $amount_f,
          ':deposit_type'   => 'bonus',
          ':status'         => 'Approved'
        ]);

        // 3) Credit MT5 Manager (same pattern as view_wallet_deposit)
        mt5_credit_bonus($trade_id, (float)$amount_f, 'Bonus'.($comment ? " - $comment" : ''));

        $conn->commit();
        $flash = ['type'=>'success','msg'=>'Bonus added, total_balance updated, and MT5 credited.'];

      } catch (Throwable $e) {
        if ($conn->inTransaction()) $conn->rollBack();
        $flash = ['type'=>'error','msg'=>'Operation failed: '.$e->getMessage()];
      }
    }
  }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Add Bonus</title>
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50">

<?php include "header.php"; ?>

<div class="flex min-h-screen">
  <?php include "side_bar.php"; ?>

  <!-- Main Content -->
  <main class="flex-1 p-6 md:ml-64">
    <h2 class="text-3xl font-semibold text-[#CD7F32] mb-6 text-center">Add Bonus</h2>

    <?php if ($flash['type']==='success'): ?>
      <div class="mb-6 bg-emerald-50 border border-emerald-200 text-emerald-800 px-4 py-3 rounded">
        <?= htmlspecialchars($flash['msg']) ?>
      </div>
    <?php elseif ($flash['type']==='error'): ?>
      <div class="mb-6 bg-rose-50 border border-rose-200 text-rose-800 px-4 py-3 rounded">
        <?= htmlspecialchars($flash['msg']) ?>
      </div>
    <?php endif; ?>

    <!-- Search Section -->
    <div class="max-w-2xl mx-auto bg-white p-4 rounded-lg shadow mb-6">
      <h3 class="text-base font-semibold text-slate-800 mb-3">Search</h3>

      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <!-- Search Users -->
        <div class="relative">
          <label class="block text-sm font-medium text-[#CD7F32] mb-1">Search User (name/email)</label>
          <input id="searchUser" type="text" placeholder="Type name, username, or email…"
                 class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#CD7F32]">
          <ul id="searchUserList"
              class="absolute z-20 left-0 right-0 bg-white border border-gray-200 shadow rounded-md mt-1 hidden max-h-64 overflow-auto"></ul>
          <p class="text-xs text-gray-500 mt-1">Pick a user to auto-fill the User dropdown.</p>
        </div>

        <!-- Search Accounts -->
        <div class="relative">
          <label class="block text-sm font-medium text-[#CD7F32] mb-1">Search Account (trade ID / email)</label>
          <input id="searchAcc" type="text" placeholder="Type trade ID or email…"
                 class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#CD7F32]">
          <ul id="searchAccList"
              class="absolute z-20 left-0 right-0 bg-white border border-gray-200 shadow rounded-md mt-1 hidden max-h-64 overflow-auto"></ul>
          <p class="text-xs text-gray-500 mt-1">Pick an account to set user + select the MT5 account.</p>
        </div>
      </div>
    </div>

    <!-- Form -->
    <form method="POST" class="space-y-6 max-w-2xl mx-auto bg-white p-6 rounded-lg shadow">
      <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf) ?>"/>

      <!-- User -->
      <div>
        <label for="user_email" class="block text-[#CD7F32] text-lg font-medium mb-2">Select User</label>
        <select id="user_email" name="user_email"
                class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#CD7F32]" required>
          <option value="">Select a user</option>
          <?php foreach ($users as $u): ?>
            <option value="<?= htmlspecialchars($u['email']) ?>">
              <?= htmlspecialchars($u['display_name'].' — '.$u['email']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <!-- Account (populates after user selection) -->
      <div>
        <label for="trade_id" class="block text-[#CD7F32] text-lg font-medium mb-2">Select MT5 Account</label>
        <select id="trade_id" name="trade_id" disabled
                class="w-full p-3 border border-gray-300 rounded-lg bg-gray-50 disabled:opacity-70 disabled:cursor-not-allowed focus:outline-none focus:ring-2 focus:ring-[#CD7F32]" required>
          <option value="">Select an account</option>
        </select>
        <div id="accHint" class="text-sm text-gray-500 mt-1">Pick a user to load their accounts.</div>
      </div>

      <!-- Amount -->
      <div>
        <label for="bonus_amount" class="block text-[#CD7F32] text-lg font-medium mb-2">Bonus Amount (USD)</label>
        <input type="number" id="bonus_amount" name="bonus_amount" min="1" step="0.01" required
               class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#CD7F32]">
      </div>

      <!-- Comment -->
      <div>
        <label for="comment" class="block text-[#CD7F32] text-lg font-medium mb-2">Comment</label>
        <textarea id="comment" name="comment" rows="3"
                  class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#CD7F32]"
                  placeholder="Optional"></textarea>
      </div>

      <div class="text-center">
        <button type="submit"
                class="w-full md:w-1/2 py-3 bg-[#CD7F32] text-white font-semibold rounded-lg shadow-md hover:bg-[#b76e2b] transition">
          Add Bonus
        </button>
      </div>
    </form>

    <?php include "footer.php"; ?>
  </main>
</div>

<script>
// ---------- existing helpers from earlier snippet ----------
async function loadAccounts(email){
  const accSel = document.getElementById('trade_id');
  const accHint = document.getElementById('accHint');
  accSel.innerHTML = '<option value="">Loading...</option>';
  accSel.setAttribute('disabled', 'disabled');
  try {
    const url = new URL(window.location.href);
    url.searchParams.set('ajax','accounts');
    url.searchParams.set('email', email);
    const res = await fetch(url.toString(), { credentials:'same-origin' });
    const data = await res.json();
    accSel.innerHTML = '';
    if (data && data.ok && Array.isArray(data.accounts) && data.accounts.length) {
      accSel.append(new Option('Select an account',''));
      data.accounts.forEach(tid => accSel.append(new Option(tid, tid)));
      accSel.removeAttribute('disabled');
      accHint.textContent = 'Select the MT5 account to credit.';
      accHint.className   = 'text-sm text-gray-500 mt-1';
    } else {
      accSel.append(new Option('No accounts found',''));
      accHint.textContent = 'No accounts for this user.';
      accHint.className   = 'text-sm text-rose-600 mt-1';
    }
  } catch (e) {
    accSel.innerHTML = '<option value="">Error loading accounts</option>';
    accHint.textContent = 'Failed to load accounts.';
    accHint.className   = 'text-sm text-rose-600 mt-1';
  }
}

// ---------- wire user select to accounts ----------
const userSel = document.getElementById('user_email');
userSel?.addEventListener('change', (e) => {
  const email = e.target.value;
  const accSel = document.getElementById('trade_id');
  const accHint= document.getElementById('accHint');
  if (!email) {
    accSel.innerHTML = '<option value="">Select an account</option>';
    accSel.setAttribute('disabled', 'disabled');
    accHint.textContent = 'Pick a user to load their accounts.';
    accHint.className   = 'text-sm text-gray-500 mt-1';
    return;
  }
  loadAccounts(email);
});

// ---------- Search wiring ----------
(function(){
  const userSel   = document.getElementById('user_email');
  const accSel    = document.getElementById('trade_id');

  const suInput   = document.getElementById('searchUser');
  const suList    = document.getElementById('searchUserList');

  const saInput   = document.getElementById('searchAcc');
  const saList    = document.getElementById('searchAccList');

  const debounce = (fn, ms=250) => { let t; return (...a)=>{ clearTimeout(t); t=setTimeout(()=>fn(...a), ms); }; };
  const closeLists = () => { suList.classList.add('hidden'); saList.classList.add('hidden'); };

  const buildUrl = (kind, q) => {
    const url = new URL(window.location.href);
    url.searchParams.set('ajax', kind);
    url.searchParams.set('q', q);
    return url.toString();
  };

  // Users search
  const renderUserResults = (arr=[]) => {
    suList.innerHTML = '';
    if (!arr.length) { suList.classList.add('hidden'); return; }
    arr.forEach(u => {
      const li = document.createElement('li');
      li.className = 'px-3 py-2 text-sm hover:bg-gray-50 cursor-pointer';
      li.textContent = `${u.display_name} — ${u.email}`;
      li.dataset.email = u.email;
      suList.appendChild(li);
    });
    suList.classList.remove('hidden');
  };
  const doSearchUsers = debounce(async (q) => {
    if (!q || q.trim().length < 2) { suList.classList.add('hidden'); return; }
    try {
      const res = await fetch(buildUrl('search_users', q.trim()), { credentials: 'same-origin' });
      const data = await res.json();
      renderUserResults(data?.users || []);
    } catch { suList.classList.add('hidden'); }
  }, 250);
  suInput?.addEventListener('input', e => doSearchUsers(e.target.value));
  suList?.addEventListener('click', async (e) => {
    const li = e.target.closest('li'); if (!li) return;
    const email = li.dataset.email;
    if (userSel) {
      userSel.value = email;
      await loadAccounts(email);
      accSel.value = '';
    }
    suInput.value = li.textContent;
    closeLists();
  });

  // Accounts search
  const renderAccResults = (arr=[]) => {
    saList.innerHTML = '';
    if (!arr.length) { saList.classList.add('hidden'); return; }
    arr.forEach(a => {
      const li = document.createElement('li');
      li.className = 'px-3 py-2 text-sm hover:bg-gray-50 cursor-pointer';
      li.textContent = `${a.trade_id} — ${a.email}`;
      li.dataset.email = a.email;
      li.dataset.trade = a.trade_id;
      saList.appendChild(li);
    });
    saList.classList.remove('hidden');
  };
  const doSearchAccs = debounce(async (q) => {
    if (!q || q.trim().length < 2) { saList.classList.add('hidden'); return; }
    try {
      const res = await fetch(buildUrl('search_accounts', q.trim()), { credentials: 'same-origin' });
      const data = await res.json();
      renderAccResults(data?.accounts || []);
    } catch { saList.classList.add('hidden'); }
  }, 250);
  saInput?.addEventListener('input', e => doSearchAccs(e.target.value));
  saList?.addEventListener('click', async (e) => {
    const li = e.target.closest('li'); if (!li) return;
    const email = li.dataset.email;
    const trade = li.dataset.trade;
    if (userSel) userSel.value = email;
    await loadAccounts(email);
    if (accSel) accSel.value = trade;
    saInput.value = `${trade} — ${email}`;
    closeLists();
  });

  // Close lists
  document.addEventListener('click', (e) => {
    if (!suList.contains(e.target) && e.target !== suInput) suList.classList.add('hidden');
    if (!saList.contains(e.target) && e.target !== saInput) saList.classList.add('hidden');
  });
  document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeLists(); });
})();
</script>
</body>
</html>
