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

function getSettings() {
  global $pdo;
  $stmt = $pdo->query("SELECT * FROM settings LIMIT 1");
  $row = $stmt->fetch();
  if (!$row) {
    // valores por defecto
    $row = [
      'business_name'      => 'Mi Negocio',
      'base_url'           => BASE_URL,
      'stripe_public_key'  => '',
      'stripe_secret_key'  => '',
      'smtp_host'          => '',
      'smtp_port'          => 587,
      'smtp_user'          => '',
      'smtp_pass'          => '',
      'smtp_from_email'    => '',
      'smtp_from_name'     => 'Giftcards',
      'points_per_currency'=> 1.0,
      'currency_unit'      => 'MXN',
      'default_days_valid' => 30,
    ];
  }
  return $row;
}

/**
 * Envía email al remitente con todas las giftcards de una compra.
 * Usa mail() del servidor (en la mayoría de los hostings compartidos funciona).
 */
function sendGiftcardsEmailToSender($senderEmail, $senderName, $giftcards) {
  if (!filter_var($senderEmail, FILTER_VALIDATE_EMAIL)) {
    return false;
  }

  $settings = getSettings();
  $from     = $settings['smtp_from_email'] ?: $senderEmail;
  $fromName = $settings['smtp_from_name'] ?: ($settings['business_name'] ?? 'Giftcards');
  $baseUrl  = rtrim($settings['base_url'] ?: BASE_URL, '/');

  $subject = "Tus tarjetas de regalo - " . ($settings['business_name'] ?? '');

  $rowsHtml = '';
  foreach ($giftcards as $g) {
    $code   = htmlspecialchars($g['code'] ?? '');
    $amount = number_format((float)($g['amount'] ?? 0), 2);
    $to     = htmlspecialchars($g['recipient_name'] ?? '');
    $msg    = nl2br(htmlspecialchars($g['message'] ?? ''));
    $valUrl = $g['qr_payload'] ?: ($baseUrl . '/validar.php?code=' . urlencode($code));

    $rowsHtml .= "
      <tr>
        <td>{$to}</td>
        <td>{$amount}</td>
        <td>{$code}</td>
        <td>{$msg}</td>
        <td><a href='{$valUrl}'>Ver / Validar</a></td>
      </tr>
    ";
  }

  $html = "
  <html><body>
    <h2>Gracias por tu compra, " . htmlspecialchars($senderName) . "</h2>
    <p>Aquí están los detalles de tus tarjetas de regalo:</p>
    <table border='1' cellpadding='6' cellspacing='0'>
      <thead>
        <tr>
          <th>Para</th>
          <th>Monto</th>
          <th>Código</th>
          <th>Mensaje</th>
          <th>Validar</th>
        </tr>
      </thead>
      <tbody>
        {$rowsHtml}
      </tbody>
    </table>
    <p>Presenta el código o el enlace de validación al usar la tarjeta.</p>
  </body></html>";

  $headers  = "MIME-Version: 1.0\r\n";
  $headers .= "Content-type:text/html;charset=UTF-8\r\n";
  $headers .= "From: {$fromName} <{$from}>\r\n";

  return mail($senderEmail, $subject, $html, $headers);
}

/**
 * Acumula puntos al remitente en base al total gastado.
 */
function addLoyaltyPoints($senderEmail, $senderName, $totalAmount, $purchaseToken) {
  global $pdo;
  if (!filter_var($senderEmail, FILTER_VALIDATE_EMAIL)) {
    return;
  }
  $settings = getSettings();
  $ppc  = (float)($settings['points_per_currency'] ?? 1.0);
  $pts  = (int)round($totalAmount * $ppc);

  $pdo->beginTransaction();
  try {
    // Buscar o crear cliente
    $stmt = $pdo->prepare("SELECT * FROM customers WHERE email = ?");
    $stmt->execute([$senderEmail]);
    $cust = $stmt->fetch();

    if ($cust) {
      $pdo->prepare("UPDATE customers 
                     SET total_spent = total_spent + ?, 
                         points_balance = points_balance + ? 
                     WHERE id = ?")
          ->execute([$totalAmount, $pts, $cust['id']]);
      $customerId = $cust['id'];
    } else {
      $pdo->prepare("INSERT INTO customers (email,name,total_spent,points_balance) 
                     VALUES (?,?,?,?)")
          ->execute([$senderEmail, $senderName, $totalAmount, $pts]);
      $customerId = $pdo->lastInsertId();
    }

    // Log de puntos
    $pdo->prepare("INSERT INTO points_log (customer_id,giftcards_batch,amount,points_added,description)
                   VALUES (?,?,?,?,?)")
        ->execute([
          $customerId,
          $purchaseToken,
          $totalAmount,
          $pts,
          "Puntos por compra de giftcards"
        ]);

    $pdo->commit();
  } catch (Exception $e) {
    $pdo->rollBack();
  }
}
