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

/// Read raw body
$payload = file_get_contents('php://input');
$sig = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';

if (!STRIPE_WEBHOOK_SECRET) {
    http_response_code(500);
    echo 'Webhook secret not configured';
    exit;
}

if (!verifyStripeSignature($payload, $sig, STRIPE_WEBHOOK_SECRET)) {
    http_response_code(400);
    echo 'Invalid signature';
    exit;
}

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

$type = $event['type'] ?? '';
$data = $event['data']['object'] ?? [];
$db = getDatabaseConnection(); 

function upsertSubscription($db, $userId, $customerId, $subId, $status, $periodEnd, $cancelAtPeriodEnd = 0) {
    // Try update existing
    $stmt = $db->prepare("UPDATE suscripciones SET stripe_customer_id=?, stripe_subscription_id=?, status=?, current_period_end=?, cancel_at_period_end=?, actualizado_el=NOW() WHERE id_de_usuario=?");
    $stmt->bind_param('ssssii', $customerId, $subId, $status, $periodEnd, $cancelAtPeriodEnd, $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 (?, ?, ?, ?, ?, ?, NOW(), NOW())");
        $stmt->bind_param('issssi', $userId, $customerId, $subId, $status, $periodEnd, $cancelAtPeriodEnd);
        $stmt->execute();
    }
}

try {
    switch ($type) {
        case 'checkout.session.completed':
            // Occurs after successful Checkout
            $clientRef = $data['client_reference_id'] ?? null; // our user_id
            $customerId = $data['customer'] ?? null;
            $subscriptionId = $data['subscription'] ?? null;
            if ($clientRef && $customerId && $subscriptionId) {
                // Fetch subscription to read status and period
                $sub = stripeRequest('GET', '/subscriptions/' . urlencode($subscriptionId));
                $status = $sub['status'] ?? 'active';
                $periodEnd = isset($sub['current_period_end']) ? date('Y-m-d H:i:s', $sub['current_period_end']) : null;
                $cancelAtPeriodEnd = !empty($sub['cancel_at_period_end']) ? 1 : 0;
                upsertSubscription($db, (int)$clientRef, $customerId, $subscriptionId, $status, $periodEnd, $cancelAtPeriodEnd);
            }
            break;
        case 'customer.subscription.created':
        case 'customer.subscription.updated':
        case 'customer.subscription.deleted':
            $subscriptionId = $data['id'] ?? null;
            $customerId = $data['customer'] ?? null;
            $status = $data['status'] ?? null;
            $periodEnd = isset($data['current_period_end']) ? date('Y-m-d H:i:s', $data['current_period_end']) : null;
            $cancelAtPeriodEnd = !empty($data['cancel_at_period_end']) ? 1 : 0;
            // If we have metadata with our user id, prefer it; else try to link by email is not reliable.
            $userId = null;
            if (!empty($data['metadata']['user_id'])) {
                $userId = (int)$data['metadata']['user_id'];
            }
            // Try find by existing subscription record
            if (!$userId && $subscriptionId) {
                $find = $db->prepare("SELECT id_de_usuario FROM suscripciones WHERE stripe_subscription_id = ? LIMIT 1");
                $find->bind_param('s', $subscriptionId);
                $find->execute();
                $res = $find->get_result()->fetch_assoc();
                if ($res) $userId = (int)$res['id_de_usuario'];
            }
            if ($userId) {
                upsertSubscription($db, $userId, $customerId, $subscriptionId, $status, $periodEnd, $cancelAtPeriodEnd);
            }
            break;
        default:
            // ignore others
            break;
    }
} catch (Throwable $e) {
    error_log('Webhook error: ' . $e->getMessage());
}

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