<?php include "includes/header.php"; ?>

<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="assets/css/avatrade.css">

<script src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script>

<style>
  /* =========================================
     Premium & Responsive CSS 
     ========================================= */
  :root {
    --primary-color: #2563eb;
    --text-main: #1f2937;
    --text-muted: #6b7280;
    --bg-light: #f9fafb;
    --border-color: #e5e7eb;
    --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  }

  body {
    font-family: 'Inter', sans-serif;
    background-color: #f4f7f6;
    color: var(--text-main);
  }

  /* Core Card Styling */
  .glass-card {
    background: #ffffff;
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.04);
    transition: var(--transition);
  }

  /* Regulator Logo Area */
  .regulator-logo-wrapper {
    height: 160px;
    background: var(--bg-light);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: inset 0 2px 4px rgba(0,0,0,0.02);
    padding: 20px;
    border: 1px dashed var(--border-color);
  }

  .regulator-logo {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
    mix-blend-mode: multiply;
  }

  /* Dealer Info List */
  .dealer-info-li {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: var(--bg-light);
    padding: 16px;
    border-radius: 12px;
    margin-bottom: 12px;
    border: 1px solid transparent;
    transition: var(--transition);
  }

  .dealer-info-li:hover {
    background: #ffffff;
    border-color: var(--primary-color);
    box-shadow: 0 4px 12px rgba(37, 99, 235, 0.05);
    transform: translateX(4px);
  }

  .info-title {
    font-size: 0.85rem;
    font-weight: 600;
    color: var(--text-muted);
    text-transform: uppercase;
    letter-spacing: 0.5px;
  }

  .info-value {
    font-size: 1rem;
    font-weight: 700;
    color: var(--text-main);
  }

  /* Badges & Tags */
  .custom-badge {
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    gap: 6px;
  }
  
  .badge-soft-blue { background: #eff6ff; color: #1d4ed8; }
  .badge-soft-orange { background: #fff7ed; color: #c2410c; }
  .badge-soft-green { background: #f0fdf4; color: #15803d; }

  /* Feature Cards */
  .feature-card {
    background: #fff;
    border: 1px solid var(--border-color);
    border-radius: 12px;
    padding: 20px;
    height: 100%;
    transition: var(--transition);
  }

  .feature-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 25px rgba(0,0,0,0.05);
    border-color: #d1d5db;
  }

  .feature-icon {
    width: 40px;
    height: 40px;
    object-fit: contain;
  }

  /* Broker Box / Members */
  .broker-card {
    display: flex;
    align-items: flex-start;
    padding: 20px;
    background: #fff;
    border-radius: 16px;
    border: 1px solid var(--border-color);
    transition: var(--transition);
    height: 100%;
    text-decoration: none;
    color: inherit;
  }

  .broker-card:hover {
    border-color: var(--primary-color);
    box-shadow: 0 10px 30px rgba(37, 99, 235, 0.08);
  }

  .broker-img-box {
    width: 80px;
    height: 80px;
    flex-shrink: 0;
    background: #fff;
    border-radius: 50%;
    padding: 10px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .broker-img-box img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
  }

  .tag-pill {
    background-color: #f1f5f9;
    color: #475569;
    border-radius: 6px;
    padding: 4px 10px;
    font-size: 0.75rem;
    font-weight: 500;
    margin: 4px 4px 0 0;
    display: inline-block;
  }

  .score-highlight {
    font-size: 1.5rem;
    font-weight: 800;
    color: var(--primary-color);
  }

  /* Chart Container Fixes */
  .chart-container {
    width: 100%;
    height: 260px;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  @media (max-width: 768px) {
    .dealer-info-li {
      flex-direction: column;
      align-items: flex-start;
      gap: 10px;
    }
    .dealer-info-li-c, .dealer-info-li-r { text-align: left; margin-top: 0; }
  }
</style>

<?php
include("config.php");

// Set base URL fallback directly if not defined
$safe_base_url = rtrim($base_url ?? '', '/'); 
$regulator = $_GET['regulator'] ?? '';

// Prepare and execute query safely
$stmt = $dbh->prepare("SELECT * FROM brokers WHERE regulator LIKE ?");
$stmt->execute(["%$regulator%"]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (!empty($results)) {
  $row = $results[0]; // Header stats

  $regLevel = strtolower(trim($row['regulation_level'] ?? ''));
  switch ($regLevel) {
    case 'high':
      $regClass = 'text-success';
      $regDisplay = 'High Security';
      break;
    case 'medium':
      $regClass = 'text-warning';
      $regDisplay = 'Medium Risk';
      break;
    case 'low':
      $regClass = 'text-danger';
      $regDisplay = 'Low Regulation';
      break;
    default:
      $regClass = 'text-primary';
      $regDisplay = 'Standard';
  }
?>

  <div class="container my-5">
    <div class="glass-card p-4 p-md-5 mb-5 relative">
      
      <div class="row g-4 align-items-center">
        <div class="col-lg-3 col-md-4 text-center">
          <div class="regulator-logo-wrapper mx-auto">
            <?php $logo_path = !empty($row['regulator_logo']) ? $safe_base_url.'/uploads/regulator/'.htmlspecialchars($row['regulator_logo']) : $safe_base_url.'/uploads/logo-grey.png'; ?>
            <img src="<?= $logo_path ?>" alt="Regulator Logo" class="regulator-logo" onerror="this.src='https://via.placeholder.com/150x100?text=No+Logo'">
          </div>
        </div>

        <div class="col-lg-5 col-md-8">
          <h2 class="fw-bold mb-3"><?= htmlspecialchars($row['regulator'] ?? 'Unknown Regulator') ?></h2>
          <div class="d-flex flex-wrap gap-2 mb-4">
            <span class="custom-badge badge-soft-blue"><i class="fas fa-shield-alt"></i> <?= htmlspecialchars($row['regulator'] ?? '') ?></span>
            <span class="custom-badge badge-soft-green"><i class="fas fa-landmark"></i> Gov Regulated</span>
            <span class="custom-badge badge-soft-orange"><i class="fas fa-chart-pie"></i> <?= htmlspecialchars($row['assets'] ?? 'Forex') ?> Assets</span>
          </div>
          
          <div class="dealer-info-li">
            <div>
              <div class="info-title">Environment Rating</div>
              <div class="info-value text-success mt-1">AAA Perfect</div>
            </div>
            <div class="text-end">
              <span class="custom-badge bg-light text-dark border">638.4 Avg Trans.</span>
            </div>
          </div>
          
          <div class="dealer-info-li">
            <div>
              <div class="info-title">Capital Status</div>
              <div class="info-value mt-1">$775,194 <span class="text-muted small">USD</span></div>
            </div>
            <div><i class="fas fa-check-circle text-success fs-5"></i></div>
          </div>
        </div>

        <div class="col-lg-4 text-center">
          <div class="p-3 bg-light rounded-4 border">
            <p class="mb-1 text-muted fw-semibold text-uppercase" style="letter-spacing: 1px;">Regulatory Level</p>
            <h4 class="<?= $regClass ?> fw-bold mb-0">
              <?= htmlspecialchars($row['regulation_rating'] ?? 'AA') ?> <span class="fs-6">(<?= $regDisplay ?>)</span>
            </h4>
            <div class="chart-container">
              <div id="ratingChart_<?= $row['id'] ?>" style="width: 100%; height: 100%;"></div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="mt-4 pt-3 border-top d-flex justify-content-between align-items-center">
        <span class="text-muted small"><i class="fas fa-globe me-2"></i> Official Registry</span>
        <a href="#" class="text-decoration-none fw-semibold"><?= htmlspecialchars($row['regulator'] ?? 'Visit Website') ?> <i class="fas fa-external-link-alt ms-1 small"></i></a>
      </div>
    </div>

    <div class="row g-4 mb-5">
      <div class="col-md-6 col-lg-3">
        <div class="feature-card text-center">
          <img src="https://img.fx696.com/Regulator/ico.png_wiki-template-global" alt="IOSCO" class="feature-icon mb-3">
          <h5 class="fw-bold fs-6">IOSCO Member</h5>
          <p class="text-muted small mb-0">Enjoy premium global association services.</p>
        </div>
      </div>
      <div class="col-md-6 col-lg-3">
        <div class="feature-card text-center">
          <img src="https://img.fx696.com/Regulator/descico.png_wiki-template-global" alt="FSCS" class="feature-icon mb-3">
          <h5 class="fw-bold fs-6">FSCS Protection</h5>
          <p class="text-muted small mb-0">Up to £85,000 compensation coverage.</p>
        </div>
      </div>
      <div class="col-md-6 col-lg-3">
        <div class="feature-card text-center">
          <img src="https://img.fx696.com/Regulator/ico.png_wiki-template-global" alt="FOS" class="feature-icon mb-3">
          <h5 class="fw-bold fs-6">Ombudsman Service</h5>
          <p class="text-muted small mb-0">Direct handling of financial complaints.</p>
        </div>
      </div>
      <div class="col-md-6 col-lg-3">
        <div class="feature-card text-center">
          <img src="https://img.fx696.com/Regulator/descico.png_wiki-template-global" alt="FCA" class="feature-icon mb-3">
          <h5 class="fw-bold fs-6">Market Integrity</h5>
          <p class="text-muted small mb-0">Strict consumer protection protocols.</p>
        </div>
      </div>
    </div>

    <div class="d-flex justify-content-between align-items-center bg-white p-3 px-4 rounded-pill shadow-sm border mb-4">
      <h4 class="mb-0 fs-5 fw-bold"><i class="fas fa-users text-primary me-2"></i> Registered Brokers</h4>
      <span class="badge bg-dark rounded-pill px-3 py-2 fs-6"><?= count($results) ?> Total</span>
    </div>

    <div class="row g-4">
      <?php if (!empty($results)): ?>
        <?php foreach ($results as $member): ?>
          <div class="col-lg-6">
            <a href="/en/dealer/<?= htmlspecialchars($member['id'] ?? '') ?>.html" target="_blank" class="broker-card d-flex text-decoration-none">
              
              <div class="broker-img-box me-3">
                <?php $broker_logo = !empty($member['logo']) ? $safe_base_url.'/uploads/'.htmlspecialchars($member['logo']) : 'https://via.placeholder.com/80?text=Logo'; ?>
                <img src="<?= $broker_logo ?>" alt="<?= htmlspecialchars($member['name'] ?? 'Broker') ?>" onerror="this.src='https://via.placeholder.com/80?text=No+Logo'">
              </div>
              
              <div class="flex-grow-1">
                <div class="d-flex justify-content-between align-items-start mb-2">
                  <h3 class="fs-5 fw-bold text-dark mb-0"><?= htmlspecialchars($member['name'] ?? 'Unknown Broker') ?></h3>
                  <div class="text-end">
                    <div class="score-highlight"><?= number_format($member['score'] ?? 0, 2) ?></div>
                    <div class="text-muted" style="font-size: 10px; text-transform: uppercase;">Rating Score</div>
                  </div>
                </div>
                
                <div class="tags-container">
                  <span class="tag-pill"><i class="fas fa-calendar-alt text-muted me-1"></i> 10+ Years</span>
                  <span class="tag-pill"><i class="fas fa-map-marker-alt text-muted me-1"></i> <?= htmlspecialchars($member['country'] ?? 'Global') ?></span>
                  <span class="tag-pill">MM License</span>
                  <span class="tag-pill">MT4/MT5</span>
                </div>
              </div>
              
              <div class="ms-2 align-self-center text-muted">
                <i class="fas fa-chevron-right"></i>
              </div>
            </a>
          </div>
        <?php endforeach; ?>
      <?php else: ?>
        <div class="col-12 text-center py-5">
          <i class="fas fa-box-open fs-1 text-muted mb-3"></i>
          <h5 class="text-muted">No registered brokers found under this regulator.</h5>
        </div>
      <?php endif; ?>
    </div>
  </div>

  <script>
    document.addEventListener("DOMContentLoaded", function() {
      const chartElement = document.getElementById('ratingChart_<?= $row['id'] ?>');
      if (chartElement) {
        const chart = echarts.init(chartElement);
        const option = {
          tooltip: { trigger: 'item' },
          radar: {
            radius: '65%',
            center: ['50%', '50%'],
            indicator: [
              { name: 'License', max: 10 },
              { name: 'Business', max: 10 },
              { name: 'Risk Ctrl', max: 10 },
              { name: 'Software', max: 10 },
              { name: 'Regulate', max: 10 }
            ],
            splitArea: {
              areaStyle: {
                color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.1)']
              }
            },
            axisName: {
              color: '#6b7280',
              fontWeight: 500,
              fontSize: 11
            }
          },
          series: [{
            type: 'radar',
            data: [{
              value: [9.43, 8.89, 9.89, 9.99, 9.42],
              name: 'Rating Data',
              areaStyle: { color: 'rgba(37, 99, 235, 0.2)' },
              lineStyle: { color: '#2563eb', width: 2 },
              itemStyle: { color: '#2563eb' },
              symbolSize: 6
            }]
          }],
          graphic: {
            elements: [{
              type: 'text',
              left: 'center',
              top: 'center',
              style: {
                text: '9.49',
                fontSize: 22,
                fontWeight: 'bold',
                fill: '#1f2937'
              }
            }]
          }
        };
        chart.setOption(option);
        
        // Make chart perfectly responsive
        window.addEventListener('resize', function() {
          chart.resize();
        });
      }
    });
  </script>

<?php } else { ?>
  <div class="container my-5">
    <div class="alert alert-warning text-center rounded-4 shadow-sm py-4">
      <i class="fas fa-exclamation-circle fs-3 mb-2 d-block"></i>
      <strong>Oops!</strong> No broker found for the selected regulator.
    </div>
  </div>
<?php } ?>

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