<?php
/*******************************************************
 * add_ib_plan.php  (ONE PAGE: form + processing)
 *******************************************************/


/* ===== TEMP: show errors while fixing blank page ===== */
error_reporting(E_ALL);
ini_set('display_errors', '1');

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

// Ensure PDO throws exceptions (so we see real errors)
if (isset($conn) && $conn instanceof PDO) {
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

/* ---------------- Helpers ---------------- */
function flash($msg = '', $type = '') {
  if ($msg !== '') $_SESSION['_flash'] = ['msg' => $msg, 'type' => $type];
  $f = $_SESSION['_flash'] ?? null;
  unset($_SESSION['_flash']);
  return $f;
}


/* ------------- Handle POST (create plan) ------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $plan_raw = trim($_POST['plan_name'] ?? '');
  $group    = trim($_POST['ac_group'] ?? '');

  if ($plan_raw === '' || $group === '') {
    flash('Plan name and group are required.', 'error');
    header('Location: add_ib_plan.php'); exit;
  }

  // Normalize plan name (Title Case, collapse spaces)
  $plan = preg_replace('/\s+/', ' ', $plan_raw);
  $plan = ucwords(strtolower($plan)); // e.g., "gold plus" => "Gold Plus"

  try {
    // 1) Fetch a template row from selected group
    //    (avoid ac_index — use a stable, existing column like ac_name)
    $stmt = $conn->prepare("
      SELECT *
      FROM account_types
      WHERE ac_group = :grp
      ORDER BY ac_name ASC
      LIMIT 1
    ");
    $stmt->execute([':grp'=>$group]);
    $template = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$template) {
      flash("No template account found for group: {$group}", 'error');
      header('Location: add_ib_plan.php'); exit;
    }

    // 2) Build new account name by inserting plan before the trailing word "Account"
    $baseName = trim((string)$template['ac_name']);
    if ($baseName === '') $baseName = 'Account';

    if (preg_match('/\bAccount\b$/i', $baseName)) {
      $newName = preg_replace('/\bAccount\b$/i', $plan.' Account', $baseName, 1);
    } else {
      $newName = rtrim($baseName).' '.$plan;
    }

    // Prevent duplicates: same group + same ac_name
    $chk = $conn->prepare("
      SELECT COUNT(*) FROM account_types
      WHERE ac_group = :grp AND ac_name = :nm
    ");
    $chk->execute([':grp'=>$group, ':nm'=>$newName]);
    if ((int)$chk->fetchColumn() > 0) {
      flash("An account named '".e($newName)."' already exists in group '".e($group)."'.", 'error');
      header('Location: add_ib_plan.php'); exit;
    }

    // 3) Copy fields from template (defensive defaults)
    $copy = [
      'ac_min_deposit'  => $template['ac_min_deposit']  ?? null,
      'ac_max_deposit'  => $template['ac_max_deposit']  ?? null,
      'ac_max_leverage' => $template['ac_max_leverage'] ?? null,
      'ac_lot_size'     => $template['ac_lot_size']     ?? null,
      'ac_group'        => $template['ac_group']        ?? $group,
      'ac_spread'       => $template['ac_spread']       ?? null,
      'ac_type'         => $template['ac_type']         ?? null,
      'ib_commission1'  => $template['ib_commission1']  ?? 0,
      'ib_commission2'  => $template['ib_commission2']  ?? 0,
      'ib_commission3'  => $template['ib_commission3']  ?? 0,
      'ib_commission4'  => $template['ib_commission4']  ?? 0,
      'ib_commission5'  => $template['ib_commission5']  ?? 0,
      'ib_commission6'  => $template['ib_commission6']  ?? 0,
      'ib_commission7'  => $template['ib_commission7']  ?? 0,
      'ib_commission8'  => $template['ib_commission8']  ?? 0,
      'ib_commission9'  => $template['ib_commission9']  ?? 0,
      'ib_commission10' => $template['ib_commission10'] ?? 0,
    ];

    // 4) Insert new row with updated name
    $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, :ac_min_deposit, :ac_max_deposit, :ac_max_leverage, :ac_lot_size, :ac_group, :ac_spread, :ac_type,
               :ib1, :ib2, :ib3, :ib4, :ib5, :ib6, :ib7, :ib8, :ib9, :ib10)";

    $ins = $conn->prepare($sql);
    $ok = $ins->execute([
      ':ac_name'         => $newName,
      ':ac_min_deposit'  => $copy['ac_min_deposit'],
      ':ac_max_deposit'  => $copy['ac_max_deposit'],
      ':ac_max_leverage' => $copy['ac_max_leverage'],
      ':ac_lot_size'     => $copy['ac_lot_size'],
      ':ac_group'        => $copy['ac_group'],
      ':ac_spread'       => $copy['ac_spread'],
      ':ac_type'         => $copy['ac_type'],
      ':ib1'             => $copy['ib_commission1'],
      ':ib2'             => $copy['ib_commission2'],
      ':ib3'             => $copy['ib_commission3'],
      ':ib4'             => $copy['ib_commission4'],
      ':ib5'             => $copy['ib_commission5'],
      ':ib6'             => $copy['ib_commission6'],
      ':ib7'             => $copy['ib_commission7'],
      ':ib8'             => $copy['ib_commission8'],
      ':ib9'             => $copy['ib_commission9'],
      ':ib10'            => $copy['ib_commission10'],
    ]);

    if ($ok) {
      flash("Added '".$newName."' under group '".$group."'.", 'success');
    } else {
      flash("Insert failed. Please try again.", 'error');
    }
  } catch (Throwable $ex) {
    // Show real reason during debugging
    flash('Error: '.$ex->getMessage(), 'error');
  }

  header('Location: add_ib_plan.php'); exit;
}

/* --------- Fetch groups for dropdown (GET) --------- */
$groups = [];
try {
  $stmt = $conn->query("
    SELECT DISTINCT ac_group
    FROM account_types
    WHERE COALESCE(ac_group, '') <> ''
    ORDER BY ac_group
  ");
  $groups = $stmt->fetchAll(PDO::FETCH_COLUMN);
} catch (Throwable $e) {
  // keep page rendering; show inline warning below
  $groups_err = $e->getMessage();
}

// Grab & clear flash
$flash = flash();
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Add IB Plan</title>
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50">

  <?php if (file_exists('header.php')) include 'header.php'; ?>

  <div class="flex min-h-screen">
    <?php if (file_exists('side_bar.php')) include 'side_bar.php'; ?>

    <main class="flex-1 p-6 md:ml-64">
      <div class="container mx-auto p-8 bg-white rounded-2xl border border-gray-200 w-full max-w-3xl">
        <h2 class="text-4xl font-bold text-center text-[#CD7F32] mb-6">Add IB Plan</h2>

        <?php if (!empty($flash['msg'])): ?>
          <div class="mb-6 rounded-md border px-4 py-3 text-sm <?= ($flash['type']==='error'?'border-red-200 bg-red-50 text-red-700':'border-green-200 bg-green-50 text-green-700') ?>">
            <?= e($flash['msg']) ?>
          </div>
        <?php endif; ?>

        <?php if (!empty($groups_err)): ?>
          <div class="mb-6 rounded-md border px-4 py-3 text-sm border-yellow-200 bg-yellow-50 text-yellow-700">
            Couldn’t load groups: <?= e($groups_err) ?>
          </div>
        <?php endif; ?>

        <form method="POST" class="space-y-6">
          <!-- Plan Name -->
          <div>
            <label for="plan_name" class="block text-[#CD7F32] text-lg font-bold uppercase tracking-wide mb-2">Plan Name</label>
            <input type="text" id="plan_name" name="plan_name"
                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#CD7F32] transition-shadow focus:shadow-md"
                   required placeholder="e.g., Gold">
            <p class="text-xs text-gray-500 mt-1">Example: If base is “Ai Account”, this will create “Ai Gold Account”.</p>
          </div>

          <!-- Select Group -->
          <div>
            <label for="ac_group" class="block text-[#CD7F32] text-lg font-bold uppercase tracking-wide mb-2">Select Group</label>
            <select id="ac_group" name="ac_group"
                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#CD7F32] transition-shadow focus:shadow-md"
                    required>
              <option value="" disabled selected>-- choose a group --</option>
              <?php foreach ($groups as $g): ?>
                <option value="<?= e($g) ?>"><?= e($g) ?></option>
              <?php endforeach; ?>
            </select>
          </div>

          <!-- Submit -->
          <div class="text-center">
            <button type="submit"
                    class="w-full md:w-auto px-6 py-3 bg-[#CD7F32] text-white font-bold rounded-lg shadow-md hover:bg-[#B87333] hover:scale-105 transition duration-300">
              Add IB Plan
            </button>
          </div>
        </form>
      </div>

      <?php if (file_exists('footer.php')) include 'footer.php'; ?>
    </main>
  </div>
</body>
</html>
