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

// Read raw body (Mercado Pago sends JSON)
$payload = file_get_contents('php://input');
$event = json_decode($payload, true);

// Accept both new (JSON) and legacy (querystring) notification formats
$preapprovalId = null;
if (isset($event['data']['id']) && ($event['type'] ?? '') === 'preapproval') {
    $preapprovalId = $event['data']['id'];
} elseif (isset($_GET['type']) && $_GET['type'] === 'preapproval' && isset($_GET['id'])) {
    $preapprovalId = $_GET['id'];
} elseif (isset($event['id']) && ($event['action'] ?? '') === 'preapproval.created') {
    $preapprovalId = $event['id'];
}
 
if (!$preapprovalId) {
    http_response_code(200);
    echo json_encode(['ignored' => true]);
    exit;
}  
 
function mpRequest($method, $path, $payload = null) {
    $token = getenv('MP_ACCESS_TOKEN');
    $url = 'https://api.mercadopago.com' . $path;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
    $headers = [
        'Authorization: Bearer ' . $token,
        'Content-Type: application/json'
    ];
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    if ($payload !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    }
    $resp = curl_exec($ch);
    if ($resp === false) {
        $err = curl_error($ch);
        curl_close($ch);
        throw new Exception('MP request failed: ' . $err);
    }
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    $data = json_decode($resp, true);
    if ($status >= 400) {
        $msg = isset($data['message']) ? $data['message'] : ('HTTP ' . $status);
        throw new Exception('Mercado Pago API error: ' . $msg);
    }
    return $data;
}

function upsertSubscriptionMP($db, $userId, $customerRef, $preapprovalId, $status, $nextPaymentDate) {
    $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, $preapprovalId, $status, $nextPaymentDate, $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, $preapprovalId, $status, $nextPaymentDate);
        $stmt->execute();
    }
}

try {
    // Fetch full preapproval details and map into our schema
    $pre = mpRequest('GET', '/preapproval/' . urlencode($preapprovalId));
    $status = $pre['status'] ?? null; // authorized | paused | cancelled
    $userRef = $pre['external_reference'] ?? null; // we set this to our user id|plan
    if ($userRef && strpos($userRef, '|') !== false) {
        $parts = explode('|', $userRef, 2);
        $userRef = $parts[0];
    }
    $customerRef = $pre['payer_email'] ?? null; // store email as reference
    $next = $pre['auto_recurring']['next_payment_date'] ?? null;
    $periodEnd = $next ? date('Y-m-d H:i:s', strtotime($next)) : null; 

    if ($userRef && $status) {
        $db = getDatabaseConnection();
        upsertSubscriptionMP($db, (int)$userRef, $customerRef, $preapprovalId, $status, $periodEnd);
    }
} catch (Throwable $e) {
    error_log('MP webhook error: ' . $e->getMessage());
}

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