<?php
/**
 * TechShop Perú - Panel Admin: Gestión de Cupones
 */
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/database.php';
require_once __DIR__ . '/../includes/functions.php';

require_admin();
$db = db();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) {
        set_flash('error', 'Token inválido.');
    } else {
        $codigo = strtoupper(trim(sanitize($_POST['codigo'] ?? '')));
        $descripcion = sanitize($_POST['descripcion'] ?? '');
        $tipo = in_array($_POST['tipo'] ?? '', ['porcentaje','fijo']) ? $_POST['tipo'] : 'porcentaje';
        $valor = (float)($_POST['valor'] ?? 0);
        $minimo_compra = (float)($_POST['minimo_compra'] ?? 0);

        if (!empty($codigo) && $valor > 0) {
            $stmt = $db->prepare('
                INSERT INTO cupones (codigo, descripcion, tipo, valor, minimo_compra, activo) 
                VALUES (?, ?, ?, ?, ?, 1)
            ');
            $stmt->execute([$codigo, $descripcion, $tipo, $valor, $minimo_compra]);
            set_flash('success', '¡Nuevo cupón "' . $codigo . '" creado con éxito!');
        }
    }
    csrf_regenerate();
    redirect('panel-admin-tech/cupones.php');
}

$stmt = $db->query('SELECT * FROM cupones ORDER BY id DESC');
$cupones = $stmt->fetchAll();

$page_title = 'Gestión de Cupones de Descuento';
require_once __DIR__ . '/views/layout.php';
?>

<div class="card border-0 shadow-sm p-4 mb-4">
    <h5 class="fw-bold mb-3"><i class="bi bi-plus-circle me-2"></i>Crear Nuevo Cupón de Descuento</h5>
    <form method="POST" class="row g-3">
        <?= csrf_field() ?>
        <div class="col-md-4">
            <label class="form-label font-weight-bold">Código del Cupón *</label>
            <input type="text" name="codigo" class="form-control text-uppercase" placeholder="Ej: TECH2026" required>
        </div>
        <div class="col-md-4">
            <label class="form-label font-weight-bold">Tipo de Descuento *</label>
            <select name="tipo" class="form-select">
                <option value="porcentaje">Porcentaje (%)</option>
                <option value="fijo">Monto Fijo (S/)</option>
            </select>
        </div>
        <div class="col-md-4">
            <label class="form-label font-weight-bold">Valor del Descuento *</label>
            <input type="number" step="0.01" name="valor" class="form-control" placeholder="Ej: 10 o 50.00" required>
        </div>
        <div class="col-md-6">
            <label class="form-label font-weight-bold">Monto Mínimo de Compra (S/)</label>
            <input type="number" step="0.01" name="minimo_compra" class="form-control" value="0.00">
        </div>
        <div class="col-md-6">
            <label class="form-label font-weight-bold">Descripción Corta</label>
            <input type="text" name="descripcion" class="form-control" placeholder="Ej: 10% de descuento en tu compra">
        </div>
        <div class="col-12 text-end">
            <button type="submit" class="btn btn-primary"><i class="bi bi-ticket-perforated me-1"></i>Crear Cupón</button>
        </div>
    </form>
</div>

<div class="table-responsive bg-white rounded shadow-sm p-3">
  <table class="table table-hover align-middle mb-0">
    <thead class="table-light">
      <tr><th>Código</th><th>Descripción</th><th>Tipo</th><th>Valor</th><th>Mínimo Compra</th><th>Usos</th><th>Estado</th></tr>
    </thead>
    <tbody>
      <?php foreach ($cupones as $c): ?>
      <tr>
        <td class="fw-bold text-primary"><?= e($c['codigo']) ?></td>
        <td><?= e($c['descripcion']) ?></td>
        <td><span class="badge bg-secondary"><?= ucfirst(e($c['tipo'])) ?></span></td>
        <td class="fw-bold"><?= $c['tipo'] === 'porcentaje' ? (float)$c['valor'] . '%' : format_precio((float)$c['valor']) ?></td>
        <td><?= format_precio((float)$c['minimo_compra']) ?></td>
        <td><?= (int)$c['usos_actuales'] ?></td>
        <td><?= $c['activo'] ? '<span class="badge bg-success">Activo</span>' : '<span class="badge bg-secondary">Inactivo</span>' ?></td>
      </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>
