<?php
$page = 'amounts';
require_once __DIR__ . '/header.php';
global $pdo;

// ===============================
// GUARDAR NUEVO
// ===============================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

  /* NUEVO MONTO */
  if (isset($_POST['action']) && $_POST['action'] === 'add') {

    $amount = (int)$_POST['amount'];
    $title  = trim($_POST['title'] ?? '');
    $desc   = trim($_POST['description'] ?? '');
    $icon   = null;

    // Guardar ícono si se subió
    if (!empty($_FILES['icon']['tmp_name'])) {
      $name = 'icon_' . time() . '_' . rand(1000, 9999) . '.png';
      $dest = __DIR__ . '/../icons/' . $name;

      if (!is_dir(__DIR__ . '/../icons')) {
        mkdir(__DIR__ . '/../icons', 0777, true);
      }

      move_uploaded_file($_FILES['icon']['tmp_name'], $dest);
      $icon = 'icons/' . $name;
    }

    if ($amount > 0 && $title !== '') {
      $stmt = $pdo->prepare("
        INSERT INTO amount_options (amount, title, description, is_active, icon)
        VALUES (?,?,?,?,?)
      ");
      $stmt->execute([$amount, $title, $desc, 1, $icon]);
    }
  }

  /* EDITAR MONTO */
  if (isset($_POST['action']) && $_POST['action'] === 'edit') {
    $id = (int)$_POST['id'];
    $amount = (int)$_POST['amount'];
    $title = trim($_POST['title']);
    $desc = trim($_POST['description']);
    $icon = $_POST['current_icon'];

    // Si hay nueva imagen
    if (!empty($_FILES['icon']['tmp_name'])) {
      $name = 'icon_' . time() . '_' . rand(1000,9999) . '.png';
      $dest = __DIR__ . '/../icons/' . $name;
      move_uploaded_file($_FILES['icon']['tmp_name'], $dest);
      $icon = 'icons/' . $name;
    }

    $stmt = $pdo->prepare("
      UPDATE amount_options 
      SET amount=?, title=?, description=?, icon=?
      WHERE id=?
    ");
    $stmt->execute([$amount, $title, $desc, $icon, $id]);
  }

  /* ACTIVAR/DESACTIVAR */
  if (isset($_POST['action']) && $_POST['action'] === 'toggle') {
    $id = (int)$_POST['id'];
    $pdo->prepare("UPDATE amount_options SET is_active = 1 - is_active WHERE id = ?")
        ->execute([$id]);
  }

  header("Location: amounts.php");
  exit;
}

// Obtener montos
$stmt = $pdo->query("SELECT * FROM amount_options ORDER BY amount ASC");
$rows = $stmt->fetchAll();
?>

<h1 class="h4 mb-4">Montos disponibles</h1>

<!-- ===============================
     AGREGAR NUEVO
================================= -->
<div class="card shadow-sm mb-4">
  <div class="card-body">

    <h5 class="mb-3">Agregar nuevo monto</h5>

    <form method="post" enctype="multipart/form-data" class="row g-3">
      <input type="hidden" name="action" value="add">

      <div class="col-md-2">
        <label class="form-label">Monto</label>
        <input type="number" name="amount" class="form-control" required>
      </div>

      <div class="col-md-3">
        <label class="form-label">Título</label>
        <input type="text" name="title" class="form-control" required>
      </div>

      <div class="col-md-5">
        <label class="form-label">Descripción</label>
        <input type="text" name="description" class="form-control">
      </div>

      <div class="col-md-2">
        <label class="form-label">Ícono</label>
        <input type="file" name="icon" accept="image/*" class="form-control">
      </div>

      <div class="col-md-12 text-end">
        <button class="btn btn-primary">
          <i class="fa-solid fa-plus"></i> Agregar
        </button>
      </div>
    </form>
  </div>
</div>

<!-- ===============================
     TABLA DE MONTOS
================================= -->
<div class="table-responsive">
  <table class="table table-hover align-middle">
    <thead class="table-dark">
      <tr>
        <th>Ícono</th>
        <th>Monto</th>
        <th>Título</th>
        <th>Descripción</th>
        <th>Activo</th>
        <th style="width:150px;">Acciones</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($rows as $r): ?>
      <tr>
        <td>
          <?php if ($r['icon']): ?>
            <img src="../<?php echo $r['icon']; ?>" style="width:50px;height:50px;object-fit:cover;border-radius:8px;">
          <?php else: ?>
            <span class="text-muted">Sin ícono</span>
          <?php endif; ?>
        </td>

        <td>$<?php echo number_format($r['amount'],2); ?></td>
        <td><?php echo htmlspecialchars($r['title']); ?></td>
        <td><?php echo htmlspecialchars($r['description']); ?></td>

        <td>
          <?php echo $r['is_active'] ? 'Sí' : 'No'; ?>
        </td>

        <td>
          <!-- Toggle -->
          <form method="post" class="d-inline">
            <input type="hidden" name="action" value="toggle">
            <input type="hidden" name="id" value="<?php echo $r['id']; ?>">
            <button class="btn btn-sm btn-outline-secondary">
              Cambiar estado
            </button>
          </form>

          <!-- Edit -->
          <button 
            class="btn btn-sm btn-primary"
            data-bs-toggle="modal"
            data-bs-target="#editModal<?php echo $r['id']; ?>">
            Editar
          </button>
        </td>
      </tr>

      <!-- ===============================
           MODAL EDITAR
      =============================== -->
      <div class="modal fade" id="editModal<?php echo $r['id']; ?>">
        <div class="modal-dialog">
          <div class="modal-content">

            <form method="post" enctype="multipart/form-data">
              <input type="hidden" name="action" value="edit">
              <input type="hidden" name="id" value="<?php echo $r['id']; ?>">
              <input type="hidden" name="current_icon" value="<?php echo $r['icon']; ?>">

              <div class="modal-header">
                <h5 class="modal-title">Editar monto</h5>
                <button class="btn-close" data-bs-dismiss="modal"></button>
              </div>

              <div class="modal-body">

                <div class="mb-3">
                  <label class="form-label">Monto</label>
                  <input type="number" name="amount" 
                    value="<?php echo $r['amount']; ?>" class="form-control">
                </div>

                <div class="mb-3">
                  <label class="form-label">Título</label>
                  <input type="text" name="title"
                    value="<?php echo htmlspecialchars($r['title']); ?>"
                    class="form-control">
                </div>

                <div class="mb-3">
                  <label class="form-label">Descripción</label>
                  <input type="text" name="description"
                    value="<?php echo htmlspecialchars($r['description']); ?>"
                    class="form-control">
                </div>

                <div class="mb-3">
                  <label class="form-label">Ícono</label>
                  <?php if ($r['icon']): ?>
                    <div class="mb-2">
                      <img src="../<?php echo $r['icon']; ?>" style="width:60px;height:60px;object-fit:cover;border-radius:8px;">
                    </div>
                  <?php endif; ?>
                  <input type="file" name="icon" accept="image/*" class="form-control">
                </div>

              </div>

              <div class="modal-footer">
                <button class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                <button class="btn btn-primary">Guardar cambios</button>
              </div>

            </form>
          </div>
        </div>
      </div>

      <?php endforeach; ?>
    </tbody>
  </table>
</div>

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