<?php
// add_ib_commission.php (merged with full listing)
declare(strict_types=1);

require_once __DIR__ . '/config.php'; // must define $conn as PDO
require_once __DIR__ . '/auth_guard.php';
if (!isset($conn) || !($conn instanceof PDO)) {
  http_response_code(500);
  echo "DB not connected. Ensure config.php sets \$conn as a PDO instance.";
  exit;
}
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

function h(?string $s): string { return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }
$flash = ['type'=>null, 'msg'=>null];

/* ---------------------------
   AJAX: fetch details by ac_name
---------------------------- */
if (($_GET['mode'] ?? '') === 'details') {
  header('Content-Type: application/json; charset=utf-8');
  $ac_name = trim($_GET['ac_name'] ?? '');
  if ($ac_name === '') { echo json_encode(['ok'=>false, 'error'=>'Missing ac_name']); exit; }

  $stmt = $conn->prepare("
    SELECT ac_group,
           ib_commission1, ib_commission2, ib_commission3, ib_commission4, ib_commission5,
           ib_commission6, ib_commission7, ib_commission8, ib_commission9, ib_commission10
    FROM account_types
    WHERE ac_name = :ac_name
    LIMIT 1
  ");
  $stmt->execute([':ac_name' => $ac_name]);
  $row = $stmt->fetch(PDO::FETCH_ASSOC);
  if (!$row) { echo json_encode(['ok'=>false, 'error'=>'Account not found']); exit; }

  $comm = [];
  for ($i=1; $i<=10; $i++) {
    $key = "ib_commission{$i}";
    $comm[$key] = isset($row[$key]) ? (int)$row[$key] : 0;
  }
  echo json_encode(['ok'=>true, 'ac_group'=>$row['ac_group'] ?? '', 'commissions'=>$comm]);
  exit;
}

/* ---------------------------
   POST: Update commissions
---------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $plan_name = trim($_POST['plan_name'] ?? '');   // ac_name
  if ($plan_name === '') {
    $flash = ['type'=>'error', 'msg'=>'Please select an Account Name.'];
  } else {
    $params = [':ac_name' => $plan_name];
    $sets = [];
    for ($i=1; $i<=10; $i++) {
      $key = "ib_commission{$i}";
      $val = $_POST[$key] ?? '';
      $val = is_numeric($val) ? (int)$val : null; // allow NULLs
      $sets[] = "$key = :$key";
      $params[":$key"] = $val;
    }
    $sql = "UPDATE account_types SET ".implode(', ', $sets)." WHERE ac_name = :ac_name";
    $st = $conn->prepare($sql);
    try {
      $st->execute($params);
      $flash = ['type'=>'success', 'msg'=>'IB commissions updated successfully.'];
    } catch (Throwable $e) {
      $flash = ['type'=>'error', 'msg'=>'Update failed: '.$e->getMessage()];
    }
  }
}

/* ---------------------------
   Data for dropdown + listing
---------------------------- */
$plans = $conn->query("
  SELECT DISTINCT ac_name 
  FROM account_types 
  WHERE ac_name IS NOT NULL AND ac_name <> '' 
  ORDER BY ac_name ASC
")->fetchAll(PDO::FETCH_COLUMN);

$allRows = $conn->query("
  SELECT ac_name, ac_group,
         COALESCE(ib_commission1,0)  AS c1,
         COALESCE(ib_commission2,0)  AS c2,
         COALESCE(ib_commission3,0)  AS c3,
         COALESCE(ib_commission4,0)  AS c4,
         COALESCE(ib_commission5,0)  AS c5,
         COALESCE(ib_commission6,0)  AS c6,
         COALESCE(ib_commission7,0)  AS c7,
         COALESCE(ib_commission8,0)  AS c8,
         COALESCE(ib_commission9,0)  AS c9,
         COALESCE(ib_commission10,0) AS c10
  FROM account_types
  ORDER BY ac_name ASC
")->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Add / View IB Commission</title>
  <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
  <style>
    .brand-gradient { background: linear-gradient(135deg, rgba(255,122,0,0.08), rgba(255,122,0,0.02)); }
    .ring-orange:focus { box-shadow: 0 0 0 3px rgba(255,122,0,0.35); outline: none; }
    .btn-orange { background:#ff7a00; }
    .btn-orange:hover { background:#e46f00; }
    .chip { background: rgba(255,122,0,0.08); color:#b45500; }
    .table-sticky thead th { position: sticky; top: 0; background: #fff; z-index: 1; }
    .scroll-shadow { box-shadow: inset 0 1px 0 0 rgba(0,0,0,.04); }
  </style>
</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-4 md:p-8 md:ml-64">
      <!-- Page Header -->
      <div class="brand-gradient rounded-2xl p-6 md:p-8 border border-orange-100 shadow-sm">
        <div class="flex items-center justify-between">
          <div>
            <h1 class="text-2xl md:text-3xl font-extrabold text-gray-900">IB Commissions — Add / Update & List</h1>
            <p class="text-gray-600 mt-1">Select an <span class="font-semibold text-orange-600">Account Name</span> to auto-fill its Group & current commissions, then save. Below, see a full listing of all accounts with level-wise commissions.</p>
          </div>
          <span class="chip px-3 py-1 rounded-full text-sm font-medium border border-orange-200">DM</span>
        </div>
      </div>

      <?php if ($flash['type']): ?>
        <div class="mt-6 rounded-xl p-4 <?=
            $flash['type']==='success' ? 'bg-green-50 border border-green-200 text-green-800'
                                       : 'bg-red-50 border border-red-200 text-red-800'
          ?>">
          <?= h($flash['msg']) ?>
        </div>
      <?php endif; ?>

      <!-- Form Card -->
      <div class="mt-6 max-w-5xl">
        <form action="" method="POST" class="bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden">
          <!-- Top bar -->
          <div class="px-5 md:px-8 py-4 border-b border-gray-100 flex items-center justify-between bg-white">
            <div class="flex items-center gap-3">
              <div class="w-10 h-10 rounded-xl flex items-center justify-center bg-orange-50 border border-orange-100">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-orange-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 1.567-3 3.5S10.343 15 12 15s3-1.567 3-3.5S13.657 8 12 8z" />
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11.5c0 4.142-3.582 7.5-7 7.5s-7-3.358-7-7.5" />
                </svg>
              </div>
              <div>
                <div class="text-xs uppercase tracking-widest text-gray-400">Commission Settings</div>
                <div class="font-semibold text-gray-900">Level-wise IB Commission</div>
              </div>
            </div>
            <!--<button type="submit" class="btn-orange text-white font-semibold px-4 py-2 rounded-xl shadow hover:shadow-md transition">-->
            <!--  Save Changes-->
            <!--</button>-->
          </div>

          <!-- Body -->
          <div class="p-5 md:p-8 grid grid-cols-1 gap-6">
            <!-- Select Account Name & Auto Group -->
            <div class="grid md:grid-cols-2 gap-6">
              <!-- Account Name -->
              <div>
                <label for="plan_name" class="block text-gray-700 font-medium mb-2">Account Name</label>
                <div class="relative">
                  <select id="plan_name" name="plan_name"
                          class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-xl focus:border-orange-400 ring-orange"
                          required>
                    <option value="">-- Select Account Name --</option>
                    <?php foreach ($plans as $p): ?>
                      <option value="<?= h($p) ?>"><?= h($p) ?></option>
                    <?php endforeach; ?>
                  </select>
                  <div class="pointer-events-none absolute inset-y-0 right-3 flex items-center text-gray-400">▼</div>
                </div>
                <p class="text-xs text-gray-500 mt-1">Pulled from <code>account_types.ac_name</code></p>
              </div>

              <!-- Auto Group -->
              <div>
                <label for="group_name" class="block text-gray-700 font-medium mb-2">Account Group (Auto)</label>
                <input id="group_name" name="group_name" type="text"
                       class="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl text-gray-700"
                       placeholder="—" readonly>
                <p class="text-xs text-gray-500 mt-1">Auto-filled from <code>account_types.ac_group</code></p>
              </div>
            </div>

            <div class="h-px bg-gradient-to-r from-transparent via-orange-200 to-transparent my-2"></div>

            <!-- Commission Grid -->
            <div>
              <div class="flex items-end justify-between mb-3">
                <div>
                  <h3 class="text-lg font-semibold text-gray-900">IB Commission Levels</h3>
                  <p class="text-sm text-gray-500">Edit values; leave 0 for unused levels.</p>
                </div>
                <button type="button" id="btnClear"
                        class="px-3 py-1.5 text-sm rounded-lg border border-gray-200 hover:border-gray-300">
                  Clear All
                </button>
              </div>

              <div class="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
                <?php for ($i=1; $i<=10; $i++): ?>
                  <div class="bg-orange-50 border border-orange-100 rounded-xl p-4">
                    <label for="ib_commission<?= $i ?>" class="block text-sm font-medium text-gray-800 mb-1">
                      Level <?= $i ?> Commission
                    </label>
                    <input type="number" step="1" min="0" id="ib_commission<?= $i ?>" name="ib_commission<?= $i ?>"
                           value="<?= isset($_POST["ib_commission$i"]) ? h((string)$_POST["ib_commission$i"]) : '' ?>"
                           class="w-full px-3 py-2 bg-white border border-orange-200 rounded-lg focus:border-orange-400 ring-orange"
                           placeholder="0">
                  </div>
                <?php endfor; ?>
              </div>
            </div>

          </div>

          <!-- Footer -->
          <div class="px-5 md:px-8 py-4 bg-gray-50 border-t border-gray-100 flex items-center justify-between">
            <div class="text-xs text-gray-500">
              Updating in table: <code>account_types</code> (columns <code>ib_commission1..10</code> by <code>ac_name</code>)
            </div>
            <button type="submit" class="btn-orange text-white font-semibold px-4 py-2 rounded-xl shadow hover:shadow-md transition">
              Save Changes
            </button>
          </div>
        </form>
      </div>

      <!-- All Accounts & Commissions -->
      <div class="mt-10">
        <div class="flex items-center justify-between mb-3">
          <div>
            <h2 class="text-xl md:text-2xl font-bold text-gray-900">All Accounts & Commissions</h2>
            <p class="text-sm text-gray-600">Quickly review every account with level-wise commissions.</p>
          </div>
          <div class="flex items-center gap-2">
            <input id="tableSearch" type="text" placeholder="Search accounts, groups, values..."
                   class="px-3 py-2 w-64 max-w-full border border-gray-300 rounded-xl focus:border-orange-400 ring-orange">
            <button id="btnResetSearch" class="px-3 py-2 border border-gray-200 rounded-xl hover:border-gray-300">Reset</button>
          </div>
        </div>

        <div class="bg-white rounded-2xl border border-gray-100 shadow-lg overflow-hidden">
          <div class="overflow-auto scroll-shadow">
            <table class="min-w-full table-auto table-sticky">
              <thead>
                <tr class="text-left text-gray-700 border-b border-gray-100">
                  <th class="px-4 py-3 font-semibold">#</th>
                  <th class="px-4 py-3 font-semibold">Account Name</th>
                  <th class="px-4 py-3 font-semibold">Group</th>
                  <?php for ($i=1; $i<=10; $i++): ?>
                    <th class="px-4 py-3 font-semibold">L<?= $i ?></th>
                  <?php endfor; ?>
                </tr>
              </thead>
              <tbody id="acctBody">
                <?php $idx=1; foreach ($allRows as $r): ?>
                  <tr class="border-b border-gray-50 hover:bg-orange-50">
                    <td class="px-4 py-2 text-gray-500"><?= $idx++ ?></td>
                    <td class="px-4 py-2 font-medium text-gray-900"><?= h($r['ac_name']) ?></td>
                    <td class="px-4 py-2 text-gray-800"><?= h($r['ac_group']) ?></td>
                    <td class="px-4 py-2"><?= (int)$r['c1'] ?></td>
                    <td class="px-4 py-2"><?= (int)$r['c2'] ?></td>
                    <td class="px-4 py-2"><?= (int)$r['c3'] ?></td>
                    <td class="px-4 py-2"><?= (int)$r['c4'] ?></td>
                    <td class="px-4 py-2"><?= (int)$r['c5'] ?></td>
                    <td class="px-4 py-2"><?= (int)$r['c6'] ?></td>
                    <td class="px-4 py-2"><?= (int)$r['c7'] ?></td>
                    <td class="px-4 py-2"><?= (int)$r['c8'] ?></td>
                    <td class="px-4 py-2"><?= (int)$r['c9'] ?></td>
                    <td class="px-4 py-2"><?= (int)$r['c10'] ?></td>
                  </tr>
                <?php endforeach; ?>
                <?php if (empty($allRows)): ?>
                  <tr><td class="px-4 py-6 text-center text-gray-500" colspan="13">No accounts found.</td></tr>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
          <div class="px-4 py-3 text-xs text-gray-500 border-t border-gray-100">
            Showing <?= count($allRows) ?> account(s).
          </div>
        </div>
      </div>

      <div class="h-24"></div>
    </main>

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

  <script>
    // --- Form JS ---
    const planSel = document.getElementById('plan_name');
    const groupInput = document.getElementById('group_name');
    const clearBtn = document.getElementById('btnClear');

    const levelInputs = [];
    for (let i=1; i<=10; i++) levelInputs.push(document.getElementById('ib_commission'+i));

    function fillCommissions(data){
      if (!data || !data.commissions) return;
      for (let i=1; i<=10; i++) {
        const key = 'ib_commission'+i;
        if (levelInputs[i-1]) levelInputs[i-1].value = (data.commissions[key] ?? 0);
      }
    }
    function clearCommissions(){ levelInputs.forEach(inp => inp.value = ''); }

    planSel.addEventListener('change', async (e) => {
      const ac_name = e.target.value;
      groupInput.value = '';
      clearCommissions();
      if (!ac_name) return;

      try {
        const r = await fetch(`?mode=details&ac_name=${encodeURIComponent(ac_name)}`);
        const j = await r.json();
        if (j.ok) {
          groupInput.value = j.ac_group || '';
          fillCommissions(j);
        } else {
          alert(j.error || 'Unable to fetch details');
        }
      } catch (err) {
        console.error(err);
        alert('Network error while fetching account details.');
      }
    });

    if (clearBtn) clearBtn.addEventListener('click', clearCommissions);

    // --- Table live search ---
    const searchInput = document.getElementById('tableSearch');
    const resetBtn = document.getElementById('btnResetSearch');
    const tbody = document.getElementById('acctBody');

    function normalize(str){ return (str || '').toString().toLowerCase().trim(); }

    function filterRows(){
      const q = normalize(searchInput.value);
      const rows = tbody.querySelectorAll('tr');
      rows.forEach(tr => {
        const text = normalize(tr.innerText);
        tr.style.display = text.indexOf(q) !== -1 ? '' : 'none';
      });
    }

    if (searchInput) {
      searchInput.addEventListener('input', filterRows);
    }
    if (resetBtn) {
      resetBtn.addEventListener('click', () => {
        searchInput.value = '';
        filterRows();
      });
    }
  </script>
</body>
</html>
