<?php

declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';

use Sethrey\SysvoteWebsite\EnvLoader;
use Sethrey\SysvoteWebsite\StripeClient;

if (class_exists(EnvLoader::class)) {
    EnvLoader::load(__DIR__ . '/../.env');
}

// This endpoint is a safety net, not the primary flow: success.php already
// verifies payment and unlocks the download in real time for the buyer.
// This webhook just gives you a durable, server-side record of completed
// payments (in case the buyer closes the tab before reaching success.php),
// logged to storage/purchases.log.
//
// Configure the webhook URL in the Stripe Dashboard as:
//   https://your-domain.com/webhook.php
// and subscribe it to the "checkout.session.completed" event.

$webhookSecret = getenv('STRIPE_WEBHOOK_SECRET') ?: '';
$payload = file_get_contents('php://input') ?: '';
$sigHeader = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';

if ($webhookSecret === '') {
    error_log('[webhook.php] STRIPE_WEBHOOK_SECRET is not configured; rejecting webhook.');
    http_response_code(500);
    exit;
}

if (!StripeClient::verifyWebhookSignature($payload, $sigHeader, $webhookSecret)) {
    http_response_code(400);
    echo 'Invalid signature.';
    exit;
}

$event = json_decode($payload, true);

if (!is_array($event) || !isset($event['type'])) {
    http_response_code(400);
    echo 'Malformed event.';
    exit;
}

if ($event['type'] === 'checkout.session.completed') {
    $session = $event['data']['object'] ?? [];
    $logDir = __DIR__ . '/../storage';

    if (!is_dir($logDir)) {
        // storage/ lives outside the web-servable public/ directory.
        @mkdir($logDir, 0755, true);
    }

    $line = sprintf(
        "%s | session=%s | payment_status=%s | plan=%s | email=%s\n",
        date('c'),
        (string) ($session['id'] ?? ''),
        (string) ($session['payment_status'] ?? ''),
        (string) ($session['metadata']['plan'] ?? ''),
        (string) ($session['customer_details']['email'] ?? '')
    );

    @file_put_contents($logDir . '/purchases.log', $line, FILE_APPEND | LOCK_EX);

    // TODO (optional): once src/SmtpMailer.php's exact send() signature is
    // confirmed, email the buyer their download link here as a backup, the
    // same way public/contact.php already emails inquiry submissions.
}

http_response_code(200);
echo 'ok';
