<?php
/**
 * WHMCS Invoice-Paid Webhook Handler
 *
 * Called by WHMCS when an invoice is paid. Auto-reenables any hosting sites
 * that were disabled with whp.disabled_reason=unpaid for the given customer.
 *
 * Payload (JSON POST body):
 *   username   string  WHP username for the customer (required)
 *   invoice_id string  WHMCS invoice ID for audit/logging (required)
 *   paid_at    string  ISO-8601 timestamp of payment (optional, informational)
 *
 * Auth: X-API-Key + X-API-Secret headers (same as all other external API endpoints).
 * Permission required: whmcs_webhook
 *
 * Response:
 *   200 { ok: true, results: { <site_id>: { ok: bool, ... } } }
 *   400 { ok: false, error: "missing_fields" }
 *   401/403 handled by api_authenticate()
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-API-Key, X-API-Secret, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// Auth FIRST — before any DB query or logic.
require_once(__DIR__ . '/../../libs/api_auth.php');
$authData = api_authenticate('whmcs_webhook');

// Disable PHP's default execution timeout. This handler calls enable_site()
// per site, which blocks up to ~20 s per container waiting for port 80.
// A customer with many sites could exceed the default 30 s limit mid-loop.
// Running as root inside the WHP container makes this safe.
@set_time_limit(0);
ignore_user_abort(true);

// Only accept POST.
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    api_response(false, null, 'Method not allowed', 405);
}

// Parse and validate payload.
$payload    = json_decode(file_get_contents('php://input'), true) ?? [];
$username   = trim((string)($payload['username']   ?? ''));
$invoice_id = trim((string)($payload['invoice_id'] ?? ''));

if ($username === '' || $invoice_id === '') {
    api_response(false, null, 'missing_fields: username and invoice_id are required', 400);
}

// Require site_disable (which itself requires docker.php, mysqlmgmt.php, customer_state.php).
require_once(__DIR__ . '/../../libs/site_disable.php');

// Look up all sites owned by this username.
require_once(__DIR__ . '/../../libs/mysqlmgmt.php');
$db = (new mysqlmgmt())->getMySQLConnection();

$stmt = $db->prepare(
    "SELECT s.id, s.username, u.email
     FROM whp.sites s
     LEFT JOIN whp.users u ON u.username = s.username
     WHERE s.username = :uname"
);
$stmt->execute(['uname' => $username]);
$sites = $stmt->fetchAll(PDO::FETCH_ASSOC);

$results = [];

foreach ($sites as $site) {
    $site_id        = (int)$site['id'];
    $container_name = (string)$site['username'];   // container name == username (Phase 5 confirmed)
    $owner_email    = (string)($site['email'] ?? '');

    // Read the disabled_reason from the state file; skip if not 'unpaid'.
    $entry  = whp_state_get($container_name);
    $reason = $entry['disabled_reason'] ?? '';
    if ($reason !== 'unpaid') {
        // Not unpaid — skip silently (idempotent on duplicate delivery too).
        continue;
    }

    // Re-enable the site (synchronous; may block up to ~20 s waiting for port 80).
    $r = enable_site($site_id, 'whmcs_webhook');
    $results[$site_id] = $r;

    // Send reactivation email — failure must NOT fail the webhook response.
    if (($r['ok'] ?? false) && $owner_email !== '') {
        try {
            require_once(__DIR__ . '/../../libs/smtp_mailer.php');
            require_once(__DIR__ . '/../../includes/email-templates/site-reactivated.php');

            $smtp_config = SmtpMailer::loadConfig();
            if ($smtp_config) {
                $mailer = new SmtpMailer($smtp_config);

                $site_url = 'https://' . $container_name . '/index.php';

                $html = render_site_reactivated([
                    'username'   => $container_name,
                    'site_url'   => $site_url,
                    'invoice_id' => $invoice_id,
                ]);
                $text = strip_tags(str_replace(['<br>', '<br/>', '<br />'], "\n", $html));

                $send_result = $mailer->send(
                    $owner_email,
                    'Your hosting site has been reactivated',
                    $html,
                    $text
                );

                if (!$send_result['success']) {
                    error_log(
                        "whmcs-invoice-paid: email send failed for site {$site_id} "
                        . "({$owner_email}): " . ($send_result['error'] ?? 'unknown')
                    );
                }
            }
        } catch (Throwable $e) {
            // Never let an email failure abort the webhook.
            error_log(
                "whmcs-invoice-paid: email exception for site {$site_id}: " . $e->getMessage()
            );
        }
    }
}

api_response(true, ['results' => $results], 'Invoice-paid webhook processed');
