<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/billing.php';

// Read Wompi event body
$payload = file_get_contents('php://input');
$event = json_decode($payload, true);

if (!$event) {
  http_response_code(400);
  echo 'Invalid payload';
  exit;
}

// Wompi sends events like { event, data: { transaction: { id, status, reference, currency, amount_in_cents } } }
$type = $event['event'] ?? '';
$tx = $event['data']['transaction'] ?? [];
$status = $tx['status'] ?? '';
$reference = $tx['reference'] ?? '';
$txId = $tx['id'] ?? '';

// Optional: verify source via a shared secret header if configured (implementation depends on Wompi settings)
// For minimal setup we proceed without verification; protect URL with randomness if needed.

function getPeriodEndForPlan($planCode) {
    $plan = getPlanByCode($planCode);
    if ($plan && !empty($plan['months'])) {
        $dt = new DateTime('now');
        $dt->modify('+' . (int)$plan['months'] . ' months');
        return $dt->format('Y-m-d H:i:s');
    }
    // Fallback: 1 año si no se reconoce el plan.
    return date('Y-m-d H:i:s', strtotime('+1 year'));
} 

function upsertSubscriptionGeneric($db, $userId, $customerRef, $subId, $status, $periodEnd) {
    $stmt = $db->prepare("UPDATE suscripciones SET stripe_customer_id=?, stripe_subscription_id=?, status=?, current_period_end=?, cancel_at_period_end=0, actualizado_el=NOW() WHERE id_de_usuario=?");
    $stmt->bind_param('ssssi', $customerRef, $subId, $status, $periodEnd, $userId);
    $stmt->execute();
    if ($stmt->affected_rows === 0) {
        $stmt = $db->prepare("INSERT INTO suscripciones (id_de_usuario, stripe_customer_id, stripe_subscription_id, status, current_period_end, cancel_at_period_end, creado_el, actualizado_el) VALUES (?, ?, ?, ?, ?, 0, NOW(), NOW())");
        $stmt->bind_param('issss', $userId, $customerRef, $subId, $status, $periodEnd);
        $stmt->execute();
    }
} 
 
try {
  // Consider APPROVED transactions as a 1-year activation window 
  if ($type === 'transaction.updated' && $status === 'APPROVED' && $reference) {
    if (preg_match('/sub_([A-Za-z0-9]+)_uid_(\d+)_/', $reference, $m)) {
      $planCode = strtolower($m[1]);
      $userId = (int)$m[2];
      $db = getDatabaseConnection();
      // Set subscription validity based on plan duration (months).
      $periodEnd = getPeriodEndForPlan($planCode);
      upsertSubscriptionGeneric($db, $userId, 'wompi', $txId, 'active', $periodEnd);
    }
  }
} catch (Throwable $e) {
  error_log('Wompi webhook error: ' . $e->getMessage());
}

http_response_code(200); 
echo json_encode(['received' => true]);
