<?php


/* DEBUG ONLY — remove after fixing */
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);


include('config.php');           // MUST define $conn as PDO
require_once('auth_guard.php');  // your auth check

// Ensure PDO throws exceptions (even if config.php didn’t)
try {
  if ($conn instanceof PDO) {
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
  } else {
    throw new RuntimeException('DB connection $conn is not a PDO instance.');
  }
} catch (Throwable $e) {
  die("DB init failed: " . $e->getMessage());
}

// ---------- Helpers ----------
function json_out($arr, $code=200){
  http_response_code($code);
  header('Content-Type: application/json; charset=UTF-8');
  echo json_encode($arr);
  exit;
}

// Small ping to check page isn’t blocked by auth or BOMs
if (isset($_GET['ping'])) { echo "pong"; exit; }

// ---------- AJAX: fetch user's trade_ids ----------
if (isset($_GET['action']) && $_GET['action'] === 'trades') {
  try {
    $user_id = (int)($_GET['user_id'] ?? 0);
    if ($user_id <= 0) json_out(['ok'=>false,'msg'=>'Invalid user id'], 400);

    // 1) get user's email from aspnetusers
    $stmt = $conn->prepare("SELECT email FROM aspnetusers WHERE id = :id LIMIT 1");
    $stmt->execute([':id'=>$user_id]);
    $email = $stmt->fetchColumn();
    if (!$email) json_out(['ok'=>false,'msg'=>'User not found'], 404);

    // 2) fetch trade_ids for that email from liveaccount
    $stmt = $conn->prepare("SELECT trade_id FROM liveaccount WHERE email = :em ORDER BY trade_id ASC");
    $stmt->execute([':em'=>$email]);
    $rows = $stmt->fetchAll(PDO::FETCH_COLUMN) ?: [];

    json_out(['ok'=>true,'email'=>$email,'trade_ids'=>$rows]);
  } catch (Throwable $e) {
    json_out(['ok'=>false,'msg'=>'Error: '.$e->getMessage()], 500);
  }
}

// ---------- AJAX: fetch account types ----------
if (isset($_GET['action']) && $_GET['action'] === 'acctypes') {
  try {
    $stmt = $conn->query("SELECT ac_index, ac_name, ac_group FROM account_types ORDER BY ac_name ASC");
    $types = $stmt ? $stmt->fetchAll() : [];
    json_out(['ok'=>true,'types'=>$types]);
  } catch (Throwable $e) {
    json_out(['ok'=>false,'msg'=>'Error: '.$e->getMessage()], 500);
  }
}

// ---------- Handle POST (update liveaccount) ----------
$flash = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    $user_id   = (int)($_POST['user_id'] ?? 0);
    $trade_id  = trim($_POST['trade_id'] ?? '');
    $ac_index  = (int)($_POST['ac_index'] ?? 0);

    if ($user_id<=0 || $trade_id==='' || $ac_index<=0) {
      throw new InvalidArgumentException('All fields are required.');
    }

    // Get user's email
    $stmt = $conn->prepare("SELECT email FROM aspnetusers WHERE id = :id LIMIT 1");
    $stmt->execute([':id'=>$user_id]);
    $email = $stmt->fetchColumn();
    if (!$email) throw new RuntimeException('Invalid user.');

    // Get selected account type details
    $stmt = $conn->prepare("SELECT ac_name, ac_group FROM account_types WHERE ac_index = :idx LIMIT 1");
    $stmt->execute([':idx'=>$ac_index]);
    $type = $stmt->fetch();
    if (!$type) throw new RuntimeException('Invalid account type.');

    // Update liveaccount for that user+trade
    $stmt = $conn->prepare("
      UPDATE liveaccount
         SET account_name = :ac_name,
             account_type = :ac_group
       WHERE email = :email AND trade_id = :trade_id
       LIMIT 1
    ");
    $stmt->execute([
      ':ac_name'  => $type['ac_name'],
      ':ac_group' => $type['ac_group'],
      ':email'    => $email,
      ':trade_id' => $trade_id
    ]);

    if ($stmt->rowCount() < 1) {
      $flash = ['type'=>'error','msg'=>'No matching live account found or nothing changed.'];
    } else {
      $flash = ['type'=>'success','msg'=>'Live account updated successfully.'];
    }
  } catch (Throwable $e) {
    $flash = ['type'=>'error','msg'=>'Update 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 Client to IB</title>
  <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="bg-gray-50">
<?php include "header.php"; ?>

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

  <main class="flex-1 p-6 md:ml-64">
    <div class="container mx-auto">
      <h1 class="text-3xl font-bold text-center mb-6" style="color:#CD7F32;">Move Client to IB</h1>

      <?php if ($flash): ?>
        <div class="max-w-2xl mx-auto mb-6 p-4 rounded-md border
          <?= $flash['type']==='success' ? 'bg-green-50 border-green-200 text-green-700' : 'bg-red-50 border-red-200 text-red-700' ?>">
          <?= e($flash['msg']) ?>
        </div>
      <?php endif; ?>

      <form method="POST" class="max-w-2xl mx-auto bg-white p-8 rounded-lg shadow-lg border border-gray-200" id="moveForm">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <!-- Select User -->
          <div>
            <label for="user_id" class="block text-[#CD7F32] text-lg font-semibold uppercase tracking-wide mb-2">
              Select User:
            </label>
            <select id="user_id" name="user_id"
              class="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-[#CD7F32]">
              <option value="">-- choose user --</option>
              <?php
                try {
                  $stmt = $conn->query("SELECT id, email, COALESCE(fullname, username, email) AS label FROM aspnetusers ORDER BY id DESC LIMIT 500");
                  $users = $stmt ? $stmt->fetchAll() : [];
                } catch (Throwable $e) {
                  $users = [];
                  echo '<div class="text-red-600 text-sm">Users load failed: '.e($e->getMessage()).'</div>';
                }
                foreach ($users as $row):
              ?>
                <option value="<?= (int)$row['id'] ?>">
                  <?= e($row['label']) ?> (<?= e($row['email']) ?>)
                </option>
              <?php endforeach; ?>
            </select>
            <p id="chosen_email" class="text-sm text-gray-500 mt-1"></p>
          </div>

          <!-- Select Trade ID -->
          <div>
            <label for="trade_id" class="block text-[#CD7F32] text-lg font-semibold uppercase tracking-wide mb-2">
              Select Trade ID:
            </label>
            <select id="trade_id" name="trade_id"
              class="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-[#CD7F32]">
              <option value="">-- choose trade id --</option>
            </select>
          </div>

          <!-- Select Account Type -->
          <div class="md:col-span-2">
            <label for="ac_index" class="block text-[#CD7F32] text-lg font-semibold uppercase tracking-wide mb-2">
              Select Account Type:
            </label>
            <select id="ac_index" name="ac_index"
              class="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-[#CD7F32]">
              <option value="">-- choose account type --</option>
            </select>
            <p id="ac_group_hint" class="text-sm text-gray-500 mt-1"></p>
          </div>
        </div>

        <div class="mt-6 text-center">
          <button type="submit"
            class="w-full md:w-auto px-6 py-3 bg-[#CD7F32] text-white font-semibold rounded-md shadow-md hover:bg-green-700 transition duration-300">
            Update Live Account
          </button>
        </div>
      </form>
    </div>
  </main>
  <?php include "footer.php"; ?>
</div>

<script>
(async function(){
  // preload account types
  const acSel = document.getElementById('ac_index');
  const groupHint = document.getElementById('ac_group_hint');
  let acTypes = [];
  try {
    const res = await fetch('add_client_ib.php?action=acctypes');
    const json = await res.json();
    if (json.ok) {
      acTypes = json.types || [];
      acTypes.forEach(t => {
        const opt = document.createElement('option');
        opt.value = t.ac_index;
        opt.textContent = `${t.ac_name}  —  (${t.ac_group})`;
        opt.dataset.group = t.ac_group;
        acSel.appendChild(opt);
      });
    } else {
      console.error(json.msg || 'Failed to load account types');
    }
  } catch(e){ console.error(e); }
  acSel.addEventListener('change', () => {
    const sel = acSel.options[acSel.selectedIndex];
    groupHint.textContent = sel && sel.dataset.group ? `Selected group: ${sel.dataset.group}` : '';
  });

  // when user changes, load trades
  const userSel = document.getElementById('user_id');
  const tradeSel = document.getElementById('trade_id');
  const chosenEmail = document.getElementById('chosen_email');

  userSel.addEventListener('change', async () => {
    tradeSel.innerHTML = '<option value="">-- choose trade id --</option>';
    chosenEmail.textContent = '';
    const uid = userSel.value;
    if (!uid) return;

    try {
      const res = await fetch('add_client_ib.php?action=trades&user_id='+encodeURIComponent(uid));
      const json = await res.json();
      if (json.ok) {
        chosenEmail.textContent = `Email: ${json.email}`;
        (json.trade_ids || []).forEach(tid => {
          const opt = document.createElement('option');
          opt.value = tid;
          opt.textContent = tid;
          tradeSel.appendChild(opt);
        });
      } else {
        alert(json.msg || 'Unable to load trades.');
      }
    } catch (e) {
      console.error(e);
      alert('Network error while loading trades.');
    }
  });
})();
</script>
</body>
</html>
