<?php
header('Content-Type: application/json');
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/db.php';

// Leer JSON enviado desde el front
$input = json_decode(file_get_contents('php://input'), true);

if (!$input || !is_array($input)) {
  http_response_code(400);
  echo json_encode(['error' => true, 'message' => 'JSON inválido']);
  exit;
}

// Extraer datos
$recipientName    = trim($input['recipient_name'] ?? '');
$recipientContact = trim($input['recipient_contact'] ?? '');
$message          = trim($input['message'] ?? '');
$senderName       = trim($input['sender_name'] ?? '');
$senderEmail      = trim($input['sender_email'] ?? '');
$amount           = floatval($input['amount'] ?? 0);
$imageFilename    = trim($input['image_filename'] ?? '');
$code             = trim($input['code'] ?? '');
$purchaseToken    = trim($input['purchase_token'] ?? '');

// Validaciones básicas
if (!$recipientName || !$recipientContact) {
  http_response_code(400);
  echo json_encode(['error'=>true,'message'=>'Faltan datos del destinatario']);
  exit;
}

if (!filter_var($recipientContact, FILTER_VALIDATE_EMAIL)) {
  http_response_code(400);
  echo json_encode(['error'=>true,'message'=>'Correo de destinatario inválido']);
  exit;
}

if (!$senderName || !$senderEmail) {
  http_response_code(400);
  echo json_encode(['error'=>true,'message'=>'Faltan datos del remitente']);
  exit;
}

if (!filter_var($senderEmail, FILTER_VALIDATE_EMAIL)) {
  http_response_code(400);
  echo json_encode(['error'=>true,'message'=>'Correo de remitente inválido']);
  exit;
}

if ($amount <= 0) {
  http_response_code(400);
  echo json_encode(['error'=>true,'message'=>'Monto inválido']);
  exit;
}

if (!$purchaseToken) {
  http_response_code(400);
  echo json_encode(['error'=>true,'message'=>'Falta purchase_token']);
  exit;
}

// Settings
$settings   = getSettings();
$baseUrl    = rtrim($settings['base_url'] ?? BASE_URL, '/');
$daysValid  = (int)($settings['default_days_valid'] ?? 30);

// Generar QR URL
$qrUrl = $baseUrl . "/validar.php?code=" . urlencode($code);

// Guardar en BD
try {
  global $pdo;

  $stmt = $pdo->prepare("INSERT INTO giftcards
    (recipient_name, recipient_contact, message, sender_name, sender_email,
     amount, image_filename, qr_payload, days_valid, days_remaining, is_valid, code, purchase_token)
    VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");

  $stmt->execute([
    $recipientName,
    $recipientContact,
    $message,
    $senderName,
    $senderEmail,
    $amount,
    $imageFilename,
    $qrUrl,
    $daysValid,
    $daysValid, // days_remaining
    1,          // is_valid
    $code,
    $purchaseToken
  ]);

  echo json_encode([
    'error' => false,
    'message' => 'Giftcard guardada',
    'id' => $pdo->lastInsertId()
  ]);

} catch (Exception $e) {
  http_response_code(500);
  echo json_encode(['error'=>true,'message'=>'Error al guardar giftcard', 'details'=>$e->getMessage()]);
}
