<?php
require_once __DIR__ . '/db.php';

header('Content-Type: application/json');

$code = $_POST['code'] ?? '';
$days = (int)($_POST['days'] ?? 0);

if (!$code || $days < 0) {
  http_response_code(400);
  echo json_encode(['error'=>true,'message'=>'Datos inválidos']);
  exit;
}

$stmt = $pdo->prepare("SELECT id FROM giftcards WHERE code = ?");
$stmt->execute([$code]);
$gift = $stmt->fetch();

if (!$gift) {
  http_response_code(404);
  echo json_encode(['error'=>true,'message'=>'Tarjeta no encontrada']);
  exit;
}

$pdo->prepare("UPDATE giftcards SET days_remaining = ? WHERE code = ?")
    ->execute([$days, $code]);

echo json_encode(['error'=>false,'message'=>'Días restantes actualizados']);
