<?php include "config.php";

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$apiKey = "0XNPKZQ7OEEQEI72";
$symbol_from = "EUR";
$symbol_to = "USD";

$forex_url = "https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=$symbol_from&to_currency=$symbol_to&apikey=$apiKey";
$forex_response = file_get_contents($forex_url);
$forex_data = json_decode($forex_response, true);
$rate = $forex_data["Realtime Currency Exchange Rate"] ?? null;

$bidPrice = $rate["8. Bid Price"] ?? null;
$askPrice = $rate["9. Ask Price"] ?? null;

$stmt = $dbh->prepare("SELECT id, name, logo, broker_type, spread, regulation_level, regulator, website FROM brokers ORDER BY id DESC limit 10");
$stmt->execute();
$brokers = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
  .spread-comparison-wrap {
    max-width: 1400px;
    width: min(1400px, calc(100% - 24px));
    margin: 0 auto;
    display: flex;
    flex-wrap: wrap;
    gap: 24px;
    align-items: flex-start;
    justify-content: space-between;
    padding: 20px 0;
  }

  .brokers-table {
    flex: 1 1 58%;
    min-width: 300px;
    width: 100%;
    border: 1px solid #dbe1ea;
    border-radius: 14px;
    overflow: hidden;
    background: #fff;
    box-shadow: 0 10px 28px rgba(15, 23, 42, 0.08);
    font-family: 'Segoe UI', sans-serif;
  }

  .brokers-header,
  .brokers-row {
    display: flex;
    align-items: center;
    padding: 13px 16px;
    border-bottom: 1px solid #edf0f5;
    flex-wrap: nowrap;
  }

  .brokers-header {
    background: linear-gradient(120deg, #152645, #23416d);
    color: #fff;
    font-weight: 700;
    text-transform: uppercase;
    font-size: 13px;
    letter-spacing: 0.04em;
  }

  .brokers-row:nth-child(even) {
    background: #f9fbfe;
  }

  .brokers-row:hover {
    background: #eef6ff;
  }

  .brokers-row > div,
  .brokers-header > div {
    flex: 1 1 0;
    min-width: 0;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 14px;
  }

  .brokers-link {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    text-decoration: none;
    color: #253246;
    font-weight: 600;
  }

  .brokers-link:hover {
    color: #0d5ec6;
  }

  .brokers-row img {
    width: 56px;
    height: 56px;
    object-fit: contain;
  }

  .broker-logo {
    width: 56px;
    height: 56px;
    object-fit: contain;
  }

  .spread {
    color: #d93c2c;
    font-weight: 700;
  }

  .comparison-r {
    flex: 1 1 38%;
    min-width: 280px;
    background: #fff;
    border: 1px solid #e7ebf2;
    border-radius: 14px;
    box-shadow: 0 10px 28px rgba(15, 23, 42, 0.06);
    padding: 20px 16px;
    max-height: 820px;
    overflow-y: auto;
    scrollbar-gutter: stable;
  }

  .comparison-title {
    margin: 0 0 16px;
    font-size: 32px;
    line-height: 1.1;
    font-weight: 800;
    background: linear-gradient(90deg, #f0b44d, #1c9ec6);
    -webkit-background-clip: text;
    background-clip: text;
    -webkit-text-fill-color: transparent;
  }

  .tyjys-list-box {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 14px;
  }

  .tyjys-list-a {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    width: 100%;
    min-height: 136px;
    padding: 14px 10px 12px;
    border: 1px solid #e9edf3;
    border-radius: 12px;
    background: linear-gradient(180deg, #fff, #fbfdff);
    box-shadow: 0 6px 14px rgba(15, 23, 42, 0.05);
    text-decoration: none;
    color: #1f2937;
    transition: transform 0.24s ease, box-shadow 0.24s ease, border-color 0.24s ease;
  }

  .tyjys-list-a:hover {
    transform: translateY(-3px);
    border-color: #96bdf0;
    box-shadow: 0 12px 22px rgba(24, 59, 117, 0.14);
  }

  .tyjys-list-img {
    position: relative;
    width: 78px;
    height: 72px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 10px;
  }

  .logo-overlay-wrapper {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    isolation: isolate;
  }


  .common-img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
    border-radius: 8px;
    position: relative;
    z-index: 1;
  }

  .logo-foreground.broker-logo {
    position: relative;
    z-index: 1;
  }

  .l-identification {
    position: absolute;
    bottom: -8px;
    left: 50%;
    transform: translateX(-50%);
    padding: 3px 10px;
    border-radius: 999px;
    font-size: 11px;
    line-height: 1;
    color: #fff;
    font-weight: 700;
    white-space: nowrap;
    box-shadow: 0 3px 8px rgba(0, 0, 0, 0.2);
  }

  .text_warp {
    white-space: nowrap;
  }

  .tyjys-list-a p {
    margin: 2px 0 0;
    font-size: 16px;
    font-weight: 700;
    line-height: 1.2;
    color: #1f2937;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 145px;
  }

  .card-hidden,
  .row-hidden,
  .broker-card-hidden {
    display: none;
  }

  /* ===== TABLET BREAKPOINT (max-width: 1100px) ===== */
  @media (max-width: 1100px) {
    .spread-comparison-wrap {
      width: min(1300px, calc(100% - 20px));
      gap: 18px;
      padding: 16px 0;
    }

    .brokers-table,
    .comparison-r {
      flex-basis: 100%;
      min-width: 0;
    }

    .brokers-header,
    .brokers-row {
      padding: 12px 14px;
      font-size: 13px;
    }

    .brokers-row > div,
    .brokers-header > div {
      font-size: 13px;
    }

    .brokers-row img {
      width: 52px;
      height: 52px;
    }

    .comparison-title {
      font-size: 28px;
      margin-bottom: 14px;
    }

    .tyjys-list-box {
      gap: 12px;
    }

    .tyjys-list-a {
      min-height: 128px;
      padding: 12px 8px 10px;
    }

    .tyjys-list-img {
      width: 72px;
      height: 68px;
      margin-bottom: 8px;
    }

    .tyjys-list-a p {
      font-size: 15px;
      max-width: 140px;
    }
  }

  /* ===== MOBILE BREAKPOINT (max-width: 768px) ===== */
  @media (max-width: 768px) {
    .spread-comparison-wrap {
      width: calc(100% - 16px);
      flex-direction: column;
      gap: 12px;
      padding: 12px 0;
    }

    .brokers-table {
      flex: 1;
      min-width: 0;
      border-radius: 10px;
      overflow-x: auto;
    }

    .brokers-header,
    .brokers-row {
      padding: 10px 10px;
      min-width: 500px;
    }

    .brokers-header {
      font-size: 12px;
    }

    .brokers-row > div,
    .brokers-header > div {
      font-size: 12px;
      flex: 0 0 auto;
      min-width: 90px;
    }

    .brokers-row img {
      width: 44px;
      height: 44px;
    }

    .brokers-link {
      gap: 6px;
      font-size: 12px;
    }

    .comparison-r {
      flex: 1;
      min-width: 0;
      padding: 16px 12px;
      border-radius: 10px;
      max-height: 72vh;
    }

    .comparison-title {
      font-size: 24px;
      margin-bottom: 12px;
    }

    .tyjys-list-box {
      grid-template-columns: repeat(2, 1fr);
      gap: 10px;
    }

    .tyjys-list-a {
      min-height: 120px;
      padding: 10px 6px 8px;
      border-radius: 10px;
    }

    .tyjys-list-img {
      width: 68px;
      height: 64px;
      margin-bottom: 6px;
    }

    .tyjys-list-a p {
      font-size: 13px;
      max-width: 130px;
      margin-top: 2px;
    }

    .l-identification {
      font-size: 10px;
      padding: 2px 8px;
    }
  }

  /* ===== SMALL MOBILE BREAKPOINT (max-width: 480px) ===== */
  @media (max-width: 480px) {
    .spread-comparison-wrap {
      width: calc(100vw - 16px);
      gap: 8px;
      padding: 8px 0;
    }

    .brokers-table {
      min-width: 0;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(15, 23, 42, 0.05);
    }

    .brokers-header,
    .brokers-row {
      padding: 8px 6px;
      min-width: 380px;
    }

    .brokers-header {
      font-size: 10px;
    }

    .brokers-row > div,
    .brokers-header > div {
      font-size: 10px;
      flex: 0 0 auto;
      min-width: 75px;
    }

    .brokers-row img {
      width: 36px;
      height: 36px;
    }

    .brokers-link {
      gap: 4px;
      font-size: 11px;
      flex-wrap: wrap;
    }

    .comparison-r {
      padding: 12px 8px;
      border-radius: 8px;
      max-height: 68vh;
    }

    .comparison-title {
      font-size: 20px;
      margin-bottom: 10px;
      line-height: 1.2;
    }

    .tyjys-list-box {
      grid-template-columns: repeat(2, 1fr);
      gap: 8px;
    }

    .tyjys-list-a {
      min-height: 110px;
      padding: 8px 4px 6px;
      border-radius: 8px;
    }

    .tyjys-list-img {
      width: 60px;
      height: 56px;
      margin-bottom: 4px;
    }

    .tyjys-list-a p {
      font-size: 11px;
      max-width: 110px;
      margin-top: 2px;
    }

    .l-identification {
      font-size: 9px;
      padding: 2px 6px;
      bottom: -6px;
    }

    .text_warp {
      word-break: break-word;
    }
  }

</style>


<div class="spread-comparison-wrap">

  <div class="brokers-table">
    <div class="brokers-header">
      <div>Broker</div>
      <div>Spread (pips)</div>
      <div>Spread Info</div>
      <div>Regulator</div>
      <div>Level</div>
    </div>

    <?php
    $rowLimit = 5;
    $rowCount = 0;
    foreach ($brokers as $broker):
      $simBid = $bidPrice ? number_format(floatval($bidPrice) - (mt_rand(5, 15) / 100000), 5) : 'N/A';
      $simAsk = $askPrice ? number_format(floatval($askPrice) + (mt_rand(5, 15) / 100000), 5) : 'N/A';
      $simSpread = ($simAsk !== 'N/A' && $simBid !== 'N/A') ? round((floatval($simAsk) - floatval($simBid)) * 10000, 2) : 'N/A';
      $rowClass = ($rowCount >= $rowLimit) ? 'row-hidden' : '';
    ?>
      <div class="brokers-row <?= $rowClass ?>">
        <div>
          <a href="avatrade.php?name=<?= htmlspecialchars($broker['name']) ?>" target="_blank" class="brokers-link">
            <div class="logo-overlay-wrapper">
              <img src="./uploads/<?= htmlspecialchars($broker['logo']) ?>" alt="<?= htmlspecialchars($broker['name']) ?> logo" class="logo-foreground broker-logo">
            </div>
            <span><?= htmlspecialchars($broker['name']) ?></span>
          </a>
        </div>

        <div class="spread"><?= htmlspecialchars($broker['spread'] ?? '-') ?></div>
        <div><?= htmlspecialchars($broker['spread'] ?? '-') ?></div>
        <div><?= htmlspecialchars($broker['regulator'] ?? '-') ?></div>
        <div><?= htmlspecialchars($broker['regulation_level'] ?? '-') ?></div>
      </div>
    <?php $rowCount++;
    endforeach; ?>

    <?php if (count($brokers) > $rowLimit): ?>
    <?php endif; ?>
  </div>

  <?php
  // Second data fetch exactly as requested
  ini_set('display_errors', 1);
  ini_set('display_startup_errors', 1);
  error_reporting(E_ALL);
  $apiKey = "0XNPKZQ7OEEQEI72";
  $symbol_from = "EUR";
  $symbol_to = "USD";

  $forex_url = "https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=$symbol_from&to_currency=$symbol_to&apikey=$apiKey";
  $forex_response = file_get_contents($forex_url);
  $forex_data = json_decode($forex_response, true);
  $rate = $forex_data["Realtime Currency Exchange Rate"] ?? null;

  $bidPrice = $rate["8. Bid Price"] ?? null;
  $askPrice = $rate["9. Ask Price"] ?? null;

  $stmt = $dbh->prepare("SELECT id, name, logo, broker_type, spread, regulation_level, regulator, website FROM brokers ORDER BY id DESC");
  $stmt->execute();
  $brokers = $stmt->fetchAll(PDO::FETCH_ASSOC);
  ?>

  <div class="comparison-r">
    <h3 class="comparison-title">Traders Safety Brokers</h3>
    <div class="tyjys-list">
      <div class="tyjys-list-box" id="broker-cards">
        <?php
        foreach ($brokers as $broker):
          $logo = htmlspecialchars($broker['logo']);
          $name = htmlspecialchars($broker['name']);
          $regulation = htmlspecialchars($broker['regulation_level'] ?? 'Unknown');
          $regColor = (stripos($regulation, 'offshore') !== false) ? '#FF5733' : '#2CB250';
          $url = htmlspecialchars($broker['website'] ?: '#');
        ?>
          <a href="avatrade.php?name=<?= htmlspecialchars($broker['name']) ?>" target="_blank" class="tyjys-list-a">
            <div class="tyjys-list-img">
              <div class="logo-overlay-wrapper">
                <img src="./uploads/<?= htmlspecialchars($broker['logo']) ?>" alt="<?= htmlspecialchars($broker['name']) ?> logo" loading="lazy" class="common-img logo-foreground">
              </div>
              <span class="l-identification" style="background: <?= $regColor ?>;">
                <?= $regulation ?>
              </span>
            </div>
            <p><?= $name ?></p>
          </a>
        <?php endforeach; ?>
      </div>
    </div>
  </div>

</div>
<script>
  function toggleRows() {
    const hiddenRows = document.querySelectorAll('.row-hidden');
    const btn = document.getElementById('toggle-row-btn');
    const isHidden = hiddenRows[0].style.display === 'none' || hiddenRows[0].style.display === '';

    hiddenRows.forEach(row => {
      row.style.display = isHidden ? 'flex' : 'none';
    });

    if (btn) {
      btn.innerText = isHidden ? 'View Less' : 'View More';
    }
  }

  function toggleCards() {
    const hiddenCards = document.querySelectorAll('.card-hidden');
    const btn = document.getElementById('toggle-cards-btn');
    // Check if there are any hidden cards before trying to read style
    if (hiddenCards.length > 0) {
      const isHidden = hiddenCards[0].style.display === 'none' || hiddenCards[0].style.display === '';

      hiddenCards.forEach(card => {
        card.style.display = isHidden ? 'inline-block' : 'none';
      });

      if (btn) {
        btn.innerText = isHidden ? 'View Less' : 'View More';
      }
    }
  }

  // Initialize both hidden sets to be invisible on load
  document.addEventListener("DOMContentLoaded", function() {
    toggleRows(); // First call shows them, second call hides again
    toggleRows();
  });
</script>