<?php
/**
 * Admin B2B Groups Page
 * Manage B2B groups and discounts
 */

$pageTitle = 'Grupuri B2B';

require_once __DIR__ . '/includes/init.php';
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/../../includes/B2B.php';

$db = Database::getInstance();
$b2b = new B2B();

// Handle form submissions
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_group':
                $name = $_POST['name'] ?? '';
                $discount = floatval($_POST['discount'] ?? 0);
                if ($name && $discount >= 0) {
                    $db->execute(
                        "INSERT INTO b2b_groups (name, discount_percent, is_active) VALUES (?, ?, 1)",
                        [$name, $discount]
                    );
                    $message = 'Grupul a fost adăugat cu succes!';
                } else {
                    $error = 'Toate câmpurile sunt obligatorii.';
                }
                break;
            case 'update_group':
                $groupId = intval($_POST['group_id'] ?? 0);
                $name = $_POST['name'] ?? '';
                $discount = floatval($_POST['discount'] ?? 0);
                $isActive = isset($_POST['is_active']) ? 1 : 0;
                if ($groupId && $name && $discount >= 0) {
                    $db->execute(
                        "UPDATE b2b_groups SET name = ?, discount_percent = ?, is_active = ? WHERE id = ?",
                        [$name, $discount, $isActive, $groupId]
                    );
                    $message = 'Grupul a fost actualizat cu succes!';
                }
                break;
            case 'delete_group':
                $groupId = intval($_POST['group_id'] ?? 0);
                if ($groupId) {
                    $db->execute("UPDATE b2b_groups SET is_active = 0 WHERE id = ?", [$groupId]);
                    $message = 'Grupul a fost dezactivat!';
                }
                break;
        }
    }
}

// Get all B2B groups
$groups = $db->fetchAll("SELECT bg.*, COUNT(bgu.user_id) as user_count 
                         FROM b2b_groups bg 
                         LEFT JOIN b2b_group_users bgu ON bg.id = bgu.b2b_group_id 
                         GROUP BY bg.id 
                         ORDER BY bg.created_at DESC");
?>

<div class="content">
  <div class="px-3 px-xxl-4 py-3 py-lg-4">
    <div class="card mb-3">
      <div class="card-header">
        <div class="row flex-between-center">
          <div class="col-auto">
            <h5 class="mb-0">Grupuri B2B</h5>
          </div>
          <div class="col-auto">
            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addGroupModal">
              <span class="fas fa-plus me-1"></span>Adaugă grup
            </button>
          </div>
        </div>
      </div>
      <div class="card-body">
        <?php if ($message): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
          <?php echo htmlspecialchars($message); ?>
          <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>
        <?php if ($error): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
          <?php echo htmlspecialchars($error); ?>
          <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <div class="table-responsive">
          <table class="table table-sm mb-0">
            <thead class="bg-body-tertiary">
              <tr>
                <th>Nume grup</th>
                <th>Reducere</th>
                <th>Utilizatori</th>
                <th>Status</th>
                <th>Acțiuni</th>
              </tr>
            </thead>
            <tbody>
              <?php if (empty($groups)): ?>
              <tr>
                <td colspan="5" class="text-center py-4">Nu există grupuri B2B.</td>
              </tr>
              <?php else: ?>
              <?php foreach ($groups as $group): ?>
              <tr>
                <td><?php echo htmlspecialchars($group['name']); ?></td>
                <td><?php echo number_format($group['discount_percent'], 2); ?>%</td>
                <td><?php echo number_format($group['user_count'] ?? 0); ?></td>
                <td>
                  <?php if ($group['is_active']): ?>
                  <span class="badge badge-subtle-success">Activ</span>
                  <?php else: ?>
                  <span class="badge badge-subtle-danger">Inactiv</span>
                  <?php endif; ?>
                </td>
                <td>
                  <button class="btn btn-sm btn-falcon-default" data-bs-toggle="modal" data-bs-target="#editGroupModal<?php echo $group['id']; ?>">
                    <span class="fas fa-edit"></span>
                  </button>
                  <form method="POST" class="d-inline" onsubmit="return confirm('Ești sigur că vrei să dezactivezi acest grup?');">
                    <input type="hidden" name="action" value="delete_group">
                    <input type="hidden" name="group_id" value="<?php echo $group['id']; ?>">
                    <button type="submit" class="btn btn-sm btn-falcon-default text-danger">
                      <span class="fas fa-trash"></span>
                    </button>
                  </form>
                </td>
              </tr>
              <?php endforeach; ?>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Add Group Modal -->
<div class="modal fade" id="addGroupModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Adaugă grup B2B</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST">
        <div class="modal-body">
          <input type="hidden" name="action" value="add_group">
          <div class="mb-3">
            <label class="form-label">Nume grup</label>
            <input type="text" class="form-control" name="name" required>
          </div>
          <div class="mb-3">
            <label class="form-label">Reducere (%)</label>
            <input type="number" class="form-control" name="discount" step="0.01" min="0" max="100" required>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Anulează</button>
          <button type="submit" class="btn btn-primary">Adaugă</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Edit Group Modals -->
<?php foreach ($groups as $group): ?>
<div class="modal fade" id="editGroupModal<?php echo $group['id']; ?>" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Editează grup B2B</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST">
        <div class="modal-body">
          <input type="hidden" name="action" value="update_group">
          <input type="hidden" name="group_id" value="<?php echo $group['id']; ?>">
          <div class="mb-3">
            <label class="form-label">Nume grup</label>
            <input type="text" class="form-control" name="name" value="<?php echo htmlspecialchars($group['name']); ?>" required>
          </div>
          <div class="mb-3">
            <label class="form-label">Reducere (%)</label>
            <input type="number" class="form-control" name="discount" step="0.01" min="0" max="100" value="<?php echo $group['discount_percent']; ?>" required>
          </div>
          <div class="mb-3">
            <div class="form-check">
              <input type="checkbox" class="form-check-input" name="is_active" id="is_active_<?php echo $group['id']; ?>" <?php echo $group['is_active'] ? 'checked' : ''; ?>>
              <label class="form-check-label" for="is_active_<?php echo $group['id']; ?>">Activ</label>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Anulează</button>
          <button type="submit" class="btn btn-primary">Salvează</button>
        </div>
      </form>
    </div>
  </div>
</div>
<?php endforeach; ?>

<?php require_once __DIR__ . '/includes/footer.php'; ?>

