<?php
// add_account_type.php
declare(strict_types=1);
session_start();
require_once __DIR__ . '/auth_guard.php';
require_once __DIR__ . '/config.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'); }

// CSRF
if (empty($_SESSION['csrf_account'])) {
  $_SESSION['csrf_account'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_account'];

$flash = ['type'=>null,'msg'=>null];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $posted_csrf = $_POST['csrf'] ?? '';
  if (!hash_equals($csrf, $posted_csrf)) {
    $flash = ['type'=>'error','msg'=>'Invalid CSRF token. Reload page and try again.'];
  } else {
    try {
      $sql = "INSERT INTO account_types
        (ac_name, ac_min_deposit, ac_max_deposit, ac_max_leverage, ac_lot_size,
         ac_group, ac_spread, ac_type,
         ib_commission1, ib_commission2, ib_commission3, ib_commission4, ib_commission5,
         ib_commission6, ib_commission7, ib_commission8, ib_commission9, ib_commission10)
        VALUES
        (:ac_name, :min_dep, :max_dep, :max_lev, :lot_size,
         :ac_group, :spread, :ac_type,
         :c1,:c2,:c3,:c4,:c5,:c6,:c7,:c8,:c9,:c10)";

      $stmt = $conn->prepare($sql);
      $params = [
        ':ac_name'  => trim($_POST['ac_name'] ?? ''),
        ':min_dep'  => $_POST['ac_min_deposit'] !== '' ? (int)$_POST['ac_min_deposit'] : null,
        ':max_dep'  => $_POST['ac_max_deposit'] !== '' ? (int)$_POST['ac_max_deposit'] : null,
        ':max_lev'  => $_POST['ac_max_leverage'] !== '' ? (int)$_POST['ac_max_leverage'] : null,
        ':lot_size' => $_POST['ac_lot_size'] !== '' ? (float)$_POST['ac_lot_size'] : null,
        ':ac_group' => trim($_POST['ac_group'] ?? ''),
        ':spread'   => $_POST['ac_spread'] !== '' ? (float)$_POST['ac_spread'] : null,
        ':ac_type'  => $_POST['ac_type'] ?? 'demo',
      ];
      for ($i=1;$i<=10;$i++) {
        $params[":c$i"] = $_POST["ib_commission$i"] !== '' ? (int)$_POST["ib_commission$i"] : null;
      }
      $stmt->execute($params);
      $flash = ['type'=>'success','msg'=>'Account type added successfully.'];
    } catch (Throwable $e) {
      $flash = ['type'=>'error','msg'=>'Insert failed: '.$e->getMessage()];
    }
  }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"/>
  <title>Add Account Type</title>
  <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
  <style>
    .btn-orange { background:#ff7a00; }
    .btn-orange:hover { background:#e46f00; }
    .ring-orange:focus { box-shadow: 0 0 0 3px rgba(255,122,0,0.35); outline:none; }
    .chip { background:rgba(255,122,0,0.08); color:#b45500; }
  </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-3 sm:p-4 md:p-8 md:ml-64">
    <div class="bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden">
      <div class="px-4 sm:px-6 md:px-8 py-4 border-b border-gray-100 flex items-center justify-between">
        <h1 class="text-xl sm:text-2xl md:text-3xl font-bold text-gray-900">Add New Account Type</h1>
        <span class="chip px-3 py-1 rounded-full text-xs sm:text-sm font-medium border border-orange-200">Orange • White</span>
      </div>

      <?php if ($flash['type']): ?>
        <div class="px-4 sm:px-6 md:px-8 py-3 text-sm <?=
          $flash['type']==='success'
            ? 'bg-green-50 border-b border-green-200 text-green-800'
            : 'bg-red-50 border-b border-red-200 text-red-800'
        ?>">
          <?= h($flash['msg']) ?>
        </div>
      <?php endif; ?>

      <form action="" method="POST" class="p-4 sm:p-6 md:p-8 grid grid-cols-1 gap-6">
        <input type="hidden" name="csrf" value="<?= h($csrf) ?>">

        <!-- Basic Info -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Account Name</label>
            <input type="text" name="ac_name" required class="w-full px-3 py-2 border border-gray-300 rounded-lg ring-orange" placeholder="Pro-ECN"/>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Group</label>
            <input type="text" name="ac_group" class="w-full px-3 py-2 border border-gray-300 rounded-lg ring-orange" placeholder="ECN-GROUP"/>
          </div>
        </div>

        <!-- Numbers -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-5">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Min Deposit</label>
            <input type="number" name="ac_min_deposit" class="w-full px-3 py-2 border border-gray-300 rounded-lg ring-orange"/>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Max Deposit</label>
            <input type="number" name="ac_max_deposit" class="w-full px-3 py-2 border border-gray-300 rounded-lg ring-orange"/>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Max Leverage</label>
            <input type="number" name="ac_max_leverage" class="w-full px-3 py-2 border border-gray-300 rounded-lg ring-orange"/>
          </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Lot Size</label>
            <input type="number" step="0.01" name="ac_lot_size" class="w-full px-3 py-2 border border-gray-300 rounded-lg ring-orange"/>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Spread</label>
            <input type="number" step="0.0001" name="ac_spread" class="w-full px-3 py-2 border border-gray-300 rounded-lg ring-orange"/>
          </div>
        </div>

        <!-- Type -->
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">Account Type</label>
          <select name="ac_type" class="w-full px-3 py-2 border border-gray-300 rounded-lg ring-orange">
            <option value="demo">Demo</option>
            <option value="real">Real</option>
          </select>
        </div>

        <!-- Commissions -->
        <div>
          <h2 class="text-lg font-semibold text-gray-900 mb-3">IB Commissions</h2>
          <div class="grid grid-cols-2 md:grid-cols-5 gap-3">
            <?php for ($i=1;$i<=10;$i++): ?>
              <div>
                <label class="block text-xs font-medium text-gray-700 mb-1">Level <?= $i ?></label>
                <input type="number" name="ib_commission<?= $i ?>" class="w-full px-2 py-2 border border-gray-300 rounded-lg ring-orange"/>
              </div>
            <?php endfor; ?>
          </div>
        </div>

        <div class="flex justify-end">
          <button type="submit" class="btn-orange text-white px-5 py-2 rounded-lg font-semibold shadow hover:shadow-md transition">
            Save Account Type
          </button>
        </div>
      </form>
    </div>
  </main>

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