<?php

// CONFIGURACIÓN DE SEGURIDAD
$DODO_WEBHOOK_SECRET = 'whsec_EXzPNvVitLkuZolnF28/WXCMCb+gYXKb'; 

// -------------------------------------------------

$payload = file_get_contents('php://input');

try {
    $event = json_decode($payload, true);
} catch(Exception $e) {
    http_response_code(400); 
    exit('Error: Payload inválido.');
}

// Validación básica de estructura
$eventType = $event['type'] ?? null;
$data = $event['data']['object'] ?? null;

if (!$eventType || !$data) {
    http_response_code(400); 
    exit('Error: Datos incompletos.');
}

$customer_email = $data['customer']['email'] ?? null; 
$customer_id = $data['customer']['customer_id'] ?? null; 

// Variables de fechas
$renewal_date_done = date('Y-m-d'); 
$next_invoice_date = null;     

// LÓGICA DE FECHAS
switch ($eventType) {
    case 'subscription.active': 
    case 'subscription.renewed':
        if (!empty($data['next_billing_date'])) {
            $next_invoice_date = date('Y-m-d', strtotime($data['next_billing_date'])); 
        } else {
            $next_invoice_date = date('Y-m-d', strtotime('+30 days'));
        }
        break;
        
    case 'subscription.failed':
    case 'subscription.cancelled':
        break;
}

// ACTUALIZACIÓN DE BASE DE DATOS
if ($customer_email && $next_invoice_date) {
    
    require_once __DIR__ . '/../core/api.php';
    global $pdo;
    
    if (!isset($pdo)) {
         http_response_code(500);
         error_log('DODO ERROR: Sin conexión a BD');
         exit;
    }

    try {
        $sql = "UPDATE users SET 
                    plan_renewal_date = ?, 
                    next_invoice_date = ?,
                    dodo_customer_id = ?,
                    plan_version = 'Booster' 
                WHERE email = ?";
                
        $stmt = $pdo->prepare($sql);
        
        $stmt->execute([
            $renewal_date_done,  // Hoy
            $next_invoice_date,  // Futuro
            $customer_id,        
            $customer_email
        ]);
        
        if ($stmt->rowCount() > 0) {
            error_log("DODO SUCCESS: Usuario actualizado a BOOSTER. Email: " . $customer_email);
        } else {
            error_log("DODO WARNING: Email no encontrado o datos idénticos: " . $customer_email);
        }
        
    } catch (PDOException $e) {
        error_log('DODO DB ERROR: ' . $e->getMessage());
        http_response_code(500);
        exit;
    }
}

http_response_code(200);
echo json_encode(["status" => "received"]);
?>