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

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

// ==========================================
// 1. DELETE LOGIC
// ==========================================
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $stmt = $dbh->prepare("DELETE FROM trader_safety.trading_conditions WHERE id = ?");
    $stmt->execute([$id]);
    header("Location: manage_trad_env.php?msg=deleted");
    exit;
}

// ==========================================
// 2. UPDATE LOGIC (Inline Edit)
// ==========================================
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'update') {
    $id = $_POST['id'];
    $rank_num = $_POST['rank_num'];
    $name = $_POST['name'];
    $account_type = $_POST['account_type'];
    $overall_rating = $_POST['overall_rating'];
    $execution_speed = $_POST['execution_speed'];

  $logo_url = $_POST['current_logo_url'] ?? '';
  if (isset($_FILES['logo_image']) && $_FILES['logo_image']['error'] === UPLOAD_ERR_OK && !empty($_FILES['logo_image']['name'])) {
    $uploadDir = '../uploads/';
    if (!is_dir($uploadDir)) {
      mkdir($uploadDir, 0777, true);
    }

    $fileName = time() . '_' . basename($_FILES['logo_image']['name']);
    $targetPath = $uploadDir . $fileName;
    if (move_uploaded_file($_FILES['logo_image']['tmp_name'], $targetPath)) {
      $logo_url = $targetPath;
    }
  }

    // Update query for the visible columns in the table
    $sql = "UPDATE trader_safety.trading_conditions 
            SET rank_num = ?, name = ?, logo_url = ?, account_type = ?, overall_rating = ?, execution_speed = ? 
            WHERE id = ?";
    $stmt = $dbh->prepare($sql);
    $stmt->execute([$rank_num, $name, $logo_url, $account_type, $overall_rating, $execution_speed, $id]);

    header("Location: manage_trad_env.php?msg=updated");
    exit;
}

// ==========================================
// 3. FETCH RECORDS
// ==========================================
$stmt = $dbh->query("SELECT * FROM trader_safety.trading_conditions ORDER BY rank_num ASC");
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

<style>
  /* ── Layout & Page Styles ── */
  .dash { max-width: 1380px; margin: 0 auto; padding: 30px 26px; z-index: 1; position: relative; }
  .panel { background: var(--dark-700); border: 1px solid rgba(255,255,255,0.05); border-radius: 14px; overflow: hidden; }
  .panel-head { display: flex; align-items: center; justify-content: space-between; padding: 16px 20px; border-bottom: 1px solid rgba(255,255,255,0.04); background: var(--dark-600); }
  .panel-title { font-family: 'Syne', sans-serif; font-size: 1.2rem; font-weight: 700; color: var(--text-1); }
  
  .btn-add { background: var(--yellow); color: var(--dark-900); padding: 8px 16px; border-radius: 8px; text-decoration: none; font-weight: 600; font-size: 0.85rem; transition: 0.2s; }
  .btn-add:hover { background: var(--yellow-bright); box-shadow: 0 4px 10px rgba(245,197,24,0.2); }
  
  /* ── Table Styles ── */
  .data-table { width: 100%; border-collapse: collapse; }
  .data-table th { font-family: 'JetBrains Mono', monospace; font-size: 0.65rem; text-transform: uppercase; color: var(--text-3); padding: 16px 18px; border-bottom: 1px solid rgba(255,255,255,0.04); text-align: left; background: var(--dark-600); }
  .data-table td { padding: 14px 18px; font-size: 0.85rem; color: var(--text-1); border-bottom: 1px solid rgba(255,255,255,0.03); vertical-align: middle; }
  .data-table tr:hover td { background: rgba(255,255,255,0.015); }
  
  .td-type { background: rgba(255,255,255,0.05); color: var(--text-2); padding: 4px 10px; border-radius: 6px; font-size: 0.75rem; font-weight: 600; }

  /* ── Inline Editing Input Styles ── */
  .edit-input { width: 100%; padding: 6px 10px; background: var(--dark-900); border: 1px solid rgba(255,255,255,0.1); border-radius: 6px; color: var(--text-1); font-size: 0.85rem; font-family: 'Manrope', sans-serif; outline: none; }
  .edit-input:focus { border-color: var(--yellow); box-shadow: 0 0 0 2px var(--yellow-glass); }
  input[type="file"].edit-input { padding: 9px 12px; color: var(--text-2); }
  input[type="file"].edit-input::file-selector-button { background: var(--dark-600); color: var(--text-1); border: 1px solid rgba(255,255,255,0.1); padding: 5px 12px; border-radius: 6px; margin-right: 12px; cursor: pointer; font-family: 'JetBrains Mono', monospace; font-size: 0.7rem; transition: 0.2s; }
  input[type="file"].edit-input::file-selector-button:hover { background: var(--yellow-glass); color: var(--yellow); border-color: var(--yellow); }
  select.edit-input { cursor: pointer; }

  /* ── Action Buttons (Icons Only for Sleek Look) ── */
  .action-wrap { display: flex; gap: 8px; }
  .action-btn { width: 32px; height: 32px; border-radius: 6px; display: flex; align-items: center; justify-content: center; font-size: 0.85rem; border: none; cursor: pointer; transition: 0.2s; text-decoration: none; }
  
  /* View Mode Buttons */
  .btn-edit-mode { background: rgba(76,168,245,0.1); color: #4ca8f5; border: 1px solid rgba(76,168,245,0.2); }
  .btn-edit-mode:hover { background: #4ca8f5; color: #fff; }
  .btn-delete-mode { background: rgba(239,79,74,0.1); color: var(--red); border: 1px solid rgba(239,79,74,0.2); }
  .btn-delete-mode:hover { background: var(--red); color: white; }

  /* Edit Mode Buttons */
  .btn-save-mode { background: rgba(16,185,129,0.1); color: #10b981; border: 1px solid rgba(16,185,129,0.2); }
  .btn-save-mode:hover { background: #10b981; color: white; box-shadow: 0 4px 10px rgba(16,185,129,0.3); }
  .btn-cancel-mode { background: rgba(255,255,255,0.05); color: var(--text-2); border: 1px solid rgba(255,255,255,0.1); }
  .btn-cancel-mode:hover { background: rgba(255,255,255,0.1); color: #fff; }

  /* Alerts */
  .alert-box { padding: 12px 16px; border-radius: 8px; font-size: 0.9rem; font-weight: 500; margin-bottom: 20px; display: flex; align-items: center; gap: 10px; }
  .alert-success { background: rgba(16,185,129,0.1); color: #10b981; border: 1px solid rgba(16,185,129,0.2); }
  .alert-danger { background: rgba(239,79,74,0.1); color: var(--red); border: 1px solid rgba(239,79,74,0.2); }
</style>

<main class="dash">
  
  <!-- Alerts System -->
  <?php if(isset($_GET['msg'])): ?>
      <?php if($_GET['msg'] == 'deleted'): ?>
        <div class="alert-box alert-danger"><i class="fas fa-trash-alt"></i> Record deleted successfully.</div>
      <?php elseif($_GET['msg'] == 'updated'): ?>
        <div class="alert-box alert-success"><i class="fas fa-check-circle"></i> Record updated successfully.</div>
      <?php endif; ?>
  <?php endif; ?>

  <div class="panel">
    <div class="panel-head">
      <div class="panel-title"><i class="fas fa-cogs" style="color: var(--yellow); margin-right: 8px;"></i> Manage Trading Conditions</div>
      <a href="add_trad_env.php" class="btn-add"><i class="fas fa-plus"></i> Add New</a>
    </div>
    
    <div style="overflow-x:auto;">
      <table class="data-table">
        <thead>
          <tr>
            <th>Rank</th>
            <th>Logo</th>
            <th>Broker Name</th>
            <th>Type</th>
            <th>Overall Rating</th>
            <th>Exec. Speed</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($records as $row): $id = $row['id']; ?>
          
          <!-- Invisible Form mapped to this specific row via form="..." attribute -->
          <form id="edit-form-<?= $id ?>" method="POST" action="" enctype="multipart/form-data"></form>
          <input type="hidden" form="edit-form-<?= $id ?>" name="action" value="update">
          <input type="hidden" form="edit-form-<?= $id ?>" name="id" value="<?= $id ?>">

          <tr>
            <!-- 1. Rank Column -->
            <td>
              <span class="view-mode-<?= $id ?>" style="color: var(--yellow); font-weight: 800; font-style: italic; font-size: 1.1rem;">#<?= $row['rank_num'] ?></span>
              <input type="number" form="edit-form-<?= $id ?>" name="rank_num" class="edit-mode-<?= $id ?> edit-input" value="<?= $row['rank_num'] ?>" style="display:none; width: 60px;" required>
            </td>

            <!-- 2. Logo Column -->
            <td>
              <div class="view-mode-<?= $id ?>">
                  <img src="<?= htmlspecialchars($row['logo_url']) ?>" height="30" style="object-fit: contain; max-width: 80px;">
              </div>
              <div class="edit-mode-<?= $id ?>" style="display:none;">
                <input type="hidden" form="edit-form-<?= $id ?>" name="current_logo_url" value="<?= htmlspecialchars($row['logo_url']) ?>">
                <img src="<?= htmlspecialchars($row['logo_url']) ?>" height="30" style="object-fit: contain; max-width: 80px; display:block; margin-bottom: 8px;">
                <input type="file" form="edit-form-<?= $id ?>" name="logo_image" class="edit-input" accept="image/*" style="width: 180px;">
              </div>
            </td>

            <!-- 3. Name Column -->
            <td>
              <strong class="view-mode-<?= $id ?>"><?= htmlspecialchars($row['name']) ?></strong>
              <input type="text" form="edit-form-<?= $id ?>" name="name" class="edit-mode-<?= $id ?> edit-input" value="<?= htmlspecialchars($row['name']) ?>" style="display:none; width: 140px;" required>
            </td>

            <!-- 4. Account Type Column -->
            <td>
              <span class="view-mode-<?= $id ?> td-type"><?= htmlspecialchars($row['account_type']) ?></span>
              <select form="edit-form-<?= $id ?>" name="account_type" class="edit-mode-<?= $id ?> edit-input" style="display:none; width: 110px;">
                  <option value="Standard" <?= ($row['account_type'] == 'Standard') ? 'selected' : '' ?>>Standard</option>
                  <option value="ECN" <?= ($row['account_type'] == 'ECN') ? 'selected' : '' ?>>ECN</option>
              </select>
            </td>

            <!-- 5. Overall Rating Column -->
            <td>
              <span class="view-mode-<?= $id ?>" style="font-weight: 700;"><?= htmlspecialchars($row['overall_rating']) ?></span>
              <input type="text" form="edit-form-<?= $id ?>" name="overall_rating" class="edit-mode-<?= $id ?> edit-input" value="<?= htmlspecialchars($row['overall_rating']) ?>" style="display:none; width: 70px;" required>
            </td>

            <!-- 6. Execution Speed Column -->
            <td>
              <span class="view-mode-<?= $id ?>"><?= htmlspecialchars($row['execution_speed']) ?></span>
              <input type="text" form="edit-form-<?= $id ?>" name="execution_speed" class="edit-mode-<?= $id ?> edit-input" value="<?= htmlspecialchars($row['execution_speed']) ?>" style="display:none; width: 100px;">
            </td>

            <!-- 7. Action Buttons -->
            <td>
              <!-- Default View Mode -->
              <div class="view-mode-<?= $id ?> action-wrap">
                <button type="button" onclick="toggleEdit(<?= $id ?>, true)" class="action-btn btn-edit-mode" title="Edit">
                    <i class="fas fa-pencil-alt"></i>
                </button>
                <a href="manage_trad_env.php?delete=<?= $id ?>" onclick="return confirm('Are you sure you want to delete this broker?');" class="action-btn btn-delete-mode" title="Delete">
                    <i class="fas fa-trash-alt"></i>
                </a>
              </div>
              
              <!-- Edit Mode (Hidden initially) -->
              <div class="edit-mode-<?= $id ?> action-wrap" style="display:none;">
                <button type="submit" form="edit-form-<?= $id ?>" class="action-btn btn-save-mode" title="Save">
                    <i class="fas fa-check"></i>
                </button>
                <button type="button" onclick="toggleEdit(<?= $id ?>, false)" class="action-btn btn-cancel-mode" title="Cancel">
                    <i class="fas fa-times"></i>
                </button>
              </div>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</main>

<script>
    // Inline Edit Toggle Logic
    function toggleEdit(id, showEdit) {
        // Find all view elements and edit elements for this specific row ID
        const views = document.querySelectorAll('.view-mode-' + id);
        const edits = document.querySelectorAll('.edit-mode-' + id);
        
        // Loop through and toggle their visibility
        views.forEach(el => el.style.display = showEdit ? 'none' : '');
        edits.forEach(el => {
            // Display blocks for inputs, flex for action buttons wrapper
            if(showEdit) {
                el.style.display = el.classList.contains('action-wrap') ? 'flex' : 'inline-block';
            } else {
                el.style.display = 'none';
            }
        });
    }
</script>

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