<?php
session_start();
include('config.php');

// 1. Authentication Check
if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: login.php");
    exit;
}

// 2. Handle Broker Deletion (GET)
if (isset($_GET['delete_id'])) {
    $delete_id = $_GET['delete_id'];
    
    // Fetch logo path before deleting record
    $stmt = $dbh->prepare("SELECT logo FROM brokers WHERE id = :id");
    $stmt->execute([':id' => $delete_id]);
    $broker = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($broker && !empty($broker['logo'])) {
        $logo_path = "../uploads/" . $broker['logo'];
        if (file_exists($logo_path)) {
            unlink($logo_path);
        }
    }
    
    // Delete from database
    $stmt = $dbh->prepare("DELETE FROM brokers WHERE id = :id");
    $stmt->execute([':id' => $delete_id]);
    
    $_SESSION['message'] = "Broker deleted successfully!";
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// 3. Handle Regulator Update (POST)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['broker_id'], $_POST['regulator'])) {
    $stmt = $dbh->prepare("UPDATE brokers SET regulator = :regulator WHERE id = :id");
    $stmt->execute([
        ':regulator' => $_POST['regulator'],
        ':id' => $_POST['broker_id']
    ]);
    $_SESSION['message'] = "Regulator updated successfully!";
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// 4. Fetch All Brokers
$stmt = $dbh->prepare("SELECT * FROM brokers ORDER BY id DESC");
$stmt->execute();
$brokers = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Include Premium Admin Header & Sidebar
include "includes/header.php";
include "includes/sidebar.php";
?>

<style>
  /* ── Layout & Page Header ── */
  .dash { max-width: 1380px; margin: 0 auto; padding: 30px 26px; z-index: 1; position: relative; }
  
  .page-header { display: flex; align-items: flex-end; justify-content: space-between; margin-bottom: 28px; flex-wrap: wrap; gap: 14px; }
  .ph-eyebrow { font-family: 'JetBrains Mono', monospace; font-size: 0.6rem; letter-spacing: 3.5px; text-transform: uppercase; color: var(--yellow-dim); margin-bottom: 6px; display: flex; align-items: center; gap: 7px; }
  .ph-eyebrow::before { content: ''; display: inline-block; width: 20px; height: 2px; background: var(--yellow); border-radius: 2px; }
  .ph-title { font-family: 'Syne', sans-serif; font-size: 2rem; font-weight: 800; color: var(--text-1); letter-spacing: -0.5px; line-height: 1.1; }
  
  .btn-primary-custom { background: var(--yellow); color: var(--dark-900); padding: 10px 20px; border-radius: 8px; font-weight: 700; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; font-size: 0.9rem; transition: 0.2s; border: none; cursor: pointer; }
  .btn-primary-custom:hover { background: var(--yellow-bright); transform: translateY(-2px); box-shadow: 0 4px 12px rgba(245,197,24,0.3); }

  /* ── Alerts ── */
  .custom-alert { background: rgba(62,203,119,0.1); border: 1px solid rgba(62,203,119,0.2); color: var(--green); padding: 14px 20px; border-radius: 10px; margin-bottom: 24px; display: flex; align-items: center; justify-content: space-between; font-weight: 500; font-size: 0.9rem; transition: opacity 0.5s ease; }
  .custom-alert i { font-size: 1.1rem; }
  .alert-close { background: none; border: none; color: var(--green); cursor: pointer; font-size: 1.1rem; opacity: 0.7; }
  .alert-close:hover { opacity: 1; }

  /* ── Broker Row (Interactive Form) ── */
  .broker-row { 
      background: var(--dark-700); 
      border: 1px solid rgba(255,255,255,0.05); 
      border-radius: 12px; 
      padding: 16px 22px; 
      margin-bottom: 14px; 
      display: flex; 
      align-items: center; 
      gap: 20px; 
      transition: all 0.3s ease; 
  }
  .broker-row:hover { border-color: var(--yellow-border); box-shadow: 0 8px 30px rgba(0,0,0,0.3); transform: translateY(-2px); }
  
  /* Logo Area */
  .br-logo-box { width: 90px; height: 50px; background: #ffffff; border-radius: 8px; border: 1px solid rgba(255,255,255,0.03); display: flex; align-items: center; justify-content: center; padding: 5px; flex-shrink: 0; }
  .br-logo-box img { max-width: 100%; max-height: 100%; object-fit: contain; }
  .br-no-logo { font-family: 'JetBrains Mono', monospace; font-size: 0.55rem; color: var(--text-3); text-transform: uppercase; letter-spacing: 1px; }

  /* Info Area */
  .br-info { flex: 1; display: flex; flex-direction: column; justify-content: center; }
  .br-name { font-family: 'Syne', sans-serif; font-size: 1.1rem; font-weight: 700; color: var(--text-1); margin-bottom: 2px; }
  .br-id { font-family: 'JetBrains Mono', monospace; font-size: 0.65rem; color: var(--text-3); }
  
  /* Dropdown Area */
  .br-select-group { display: flex; flex-direction: column; gap: 6px; width: 180px; }
  .br-label { font-family: 'JetBrains Mono', monospace; font-size: 0.6rem; text-transform: uppercase; color: var(--text-3); letter-spacing: 1px; }
  .form-select-custom { 
      background: var(--dark-800); 
      border: 1px solid rgba(255,255,255,0.08); 
      color: var(--text-1); 
      border-radius: 8px; 
      padding: 8px 12px; 
      font-size: 0.85rem; 
      outline: none; 
      transition: 0.2s; 
      cursor: pointer;
      appearance: none;
      background-image: url('data:image/svg+xml;charset=US-ASCII,<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="%238a90a6" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"></polyline></svg>');
      background-repeat: no-repeat;
      background-position: right 12px center;
  }
  .form-select-custom:focus { border-color: var(--yellow); box-shadow: 0 0 0 3px var(--yellow-glass); }

  /* Action Buttons Area */
  .br-actions { display: flex; gap: 8px; align-items: center; flex-shrink: 0; }
  .btn-act { width: 38px; height: 38px; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 0.9rem; border: none; cursor: pointer; transition: 0.2s; text-decoration: none; }
  
  .btn-act-save { background: rgba(62,203,119,0.1); color: var(--green); border: 1px solid rgba(62,203,119,0.2); }
  .btn-act-save:hover { background: var(--green); color: #fff; box-shadow: 0 4px 10px rgba(62,203,119,0.3); }
  
  .btn-act-view { background: rgba(76,168,245,0.1); color: var(--blue); border: 1px solid rgba(76,168,245,0.2); }
  .btn-act-view:hover { background: var(--blue); color: #fff; box-shadow: 0 4px 10px rgba(76,168,245,0.3); }
  
  .btn-act-edit { background: rgba(245,160,32,0.1); color: var(--orange); border: 1px solid rgba(245,160,32,0.2); }
  .btn-act-edit:hover { background: var(--orange); color: #fff; box-shadow: 0 4px 10px rgba(245,160,32,0.3); }
  
  .btn-act-del { background: rgba(239,79,74,0.1); color: var(--red); border: 1px solid rgba(239,79,74,0.2); }
  .btn-act-del:hover { background: var(--red); color: #fff; box-shadow: 0 4px 10px rgba(239,79,74,0.3); }

  /* Empty State */
  .empty-state { text-align: center; padding: 60px 20px; background: var(--dark-700); border-radius: 14px; border: 1px dashed rgba(255,255,255,0.1); }
  .empty-state i { font-size: 3rem; color: var(--text-3); margin-bottom: 15px; }
  .empty-state p { color: var(--text-2); font-size: 0.95rem; }

  @media (max-width: 768px) {
      .broker-row { flex-direction: column; align-items: stretch; text-align: center; gap: 15px; }
      .br-info { align-items: center; }
      .br-select-group { width: 100%; }
      .br-actions { justify-content: center; margin-top: 5px; }
      .br-logo-box { margin: 0 auto; width: 120px; height: 60px; }
  }
</style>

<main class="dash">

    <!-- Page Header -->
    <div class="page-header">
        <div>
            <div class="ph-eyebrow">Database</div>
            <div class="ph-title">Broker <strong>Management</strong></div>
        </div>
        <div>
            <a href="add-broker.php" class="btn-primary-custom">
                <i class="fas fa-plus-circle"></i> Add New Broker
            </a>
        </div>
    </div>

    <!-- Alert Message -->
    <?php if (isset($_SESSION['message'])): ?>
        <div class="custom-alert" id="auto-alert">
            <div><i class="fas fa-check-circle"></i> &nbsp; <?= $_SESSION['message'] ?></div>
            <button class="alert-close" onclick="closeAlert()"><i class="fas fa-times"></i></button>
        </div>
        <?php unset($_SESSION['message']); ?>
    <?php endif; ?>

    <!-- Broker List -->
    <div>
        <?php if (empty($brokers)): ?>
            <div class="empty-state">
                <i class="fas fa-folder-open"></i>
                <p>No brokers found in the database. Add your first broker to get started!</p>
            </div>
        <?php else: ?>
            
            <?php foreach ($brokers as $broker): ?>
                <form method="POST" action="" class="broker-row">
                    <input type="hidden" name="broker_id" value="<?= $broker['id'] ?>">
                    
                    <!-- Logo -->
                    <div class="br-logo-box">
                        <?php if(!empty($broker['logo'])): ?>
                            <img src="../uploads/<?= htmlentities($broker['logo']) ?>" alt="Logo">
                        <?php else: ?>
                            <span class="br-no-logo">No Logo</span>
                        <?php endif; ?>
                    </div>

                    <!-- Name & ID -->
                    <div class="br-info">
                        <div class="br-name"><?= htmlentities($broker['name']) ?></div>
                        <div class="br-id">Broker ID: #<?= $broker['id'] ?></div>
                    </div>

                    <!-- Regulator Dropdown -->
                    <div class="br-select-group">
                        <span class="br-label">Regulator</span>
                        <select name="regulator" class="form-select-custom">
                            <option value="FCA" <?= $broker['regulator'] == 'FCA' ? 'selected' : '' ?>>FCA (UK)</option>
                            <option value="ASIC" <?= $broker['regulator'] == 'ASIC' ? 'selected' : '' ?>>ASIC (Australia)</option>
                            <option value="CySEC" <?= $broker['regulator'] == 'CySEC' ? 'selected' : '' ?>>CySEC (Cyprus)</option>
                            <option value="Other" <?= $broker['regulator'] == 'Other' ? 'selected' : '' ?>>Other</option>
                        </select>
                    </div>

                    <!-- Action Buttons -->
                    <div class="br-actions">
                        <button type="submit" class="btn-act btn-act-save" title="Save Changes">
                            <i class="fas fa-save"></i>
                        </button>
                        
                        <a href="broker-details.php?id=<?= $broker['id'] ?>" class="btn-act btn-act-view" title="View Details">
                            <i class="fas fa-eye"></i>
                        </a>
                        
                        <a href="admin-broker-edit.php?id=<?= $broker['id'] ?>" class="btn-act btn-act-edit" title="Edit Record">
                            <i class="fas fa-pencil-alt"></i>
                        </a>
                        
                        <a href="?delete_id=<?= $broker['id'] ?>" 
                           class="btn-act btn-act-del" 
                           title="Delete Broker"
                           onclick="return confirm('CRITICAL WARNING: Are you sure? This will delete the broker and their logo permanently.');">
                            <i class="fas fa-trash-alt"></i>
                        </a>
                    </div>
                </form>
            <?php endforeach; ?>

        <?php endif; ?>
    </div>

</main>

<!-- Vanilla JS for Alerts -->
<script>
    function closeAlert() {
        const alertBox = document.getElementById('auto-alert');
        if (alertBox) {
            alertBox.style.opacity = '0';
            setTimeout(() => alertBox.remove(), 500);
        }
    }

    // Auto dismiss alert after 5 seconds
    document.addEventListener("DOMContentLoaded", function() {
        setTimeout(closeAlert, 5000);
    });
</script>

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