<?php
/**
 * AI Monitor — request on-demand traffic analysis.
 *
 * POST endpoint. Enqueues a `review_type='traffic'` row in
 * whp.ai_monitor_log_reviews; the existing process-log-review.php worker
 * picks it up. Mirrors the 'request_review' action in
 * api/ai-monitor-customer.php — same auth model, same idempotency check.
 *
 * Auth + CSRF: enforced upstream by auto-prepend.php (AUTH_USER constant
 * for session auth; CSRF token validated on every authenticated POST).
 *
 * Response shape always JSON with `ok` boolean and either `queued_review_id`
 * or `error`. Errors use HTTP 200 to match WHP's existing API convention
 * (the customer endpoint returns 200 + {success: false} for business
 * errors). True auth/method failures still set 4xx.
 */

header('Content-Type: application/json');

if (!defined('AUTH_USER')) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Authentication required']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'Method not allowed']);
    exit;
}

$username = AUTH_USER;
$is_root = (AUTH_USER === 'root');

$raw = file_get_contents('php://input');
$input = json_decode($raw, true);
if (!is_array($input)) {
    $input = $_POST;
}

$subscriptionId = (int)($input['subscription_id'] ?? 0);
if ($subscriptionId <= 0) {
    echo json_encode(['ok' => false, 'error' => 'Missing subscription_id']);
    exit;
}

try {
    require_once('/docker/whp/web/libs/mysqlmgmt.php');
    $mysql = new mysqlmgmt();
    $db = $mysql->getMySQLConnection();
    if (!$db) {
        echo json_encode(['ok' => false, 'error' => 'Database connection failed']);
        exit;
    }
    $db->exec("USE whp");

    if ($is_root) {
        $stmt = $db->prepare("
            SELECT id, site_id, username
            FROM whp.ai_monitor_subscriptions
            WHERE id = ? AND status = 'active'
        ");
        $stmt->execute([$subscriptionId]);
    } else {
        $stmt = $db->prepare("
            SELECT id, site_id, username
            FROM whp.ai_monitor_subscriptions
            WHERE id = ? AND username = ? AND status = 'active'
        ");
        $stmt->execute([$subscriptionId, $username]);
    }
    $sub = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$sub) {
        echo json_encode(['ok' => false, 'error' => 'Subscription not found or access denied']);
        exit;
    }

    $siteId = (int)$sub['site_id'];

    // Don't enqueue twice: an existing pending/processing traffic review
    // for the same subscription is the canonical "already in progress"
    // signal. (A separate 'log' review may legitimately be running in
    // parallel, so we filter on review_type explicitly.)
    $existsStmt = $db->prepare("
        SELECT id FROM whp.ai_monitor_log_reviews
        WHERE subscription_id = ?
          AND review_type = 'traffic'
          AND status IN ('pending', 'processing')
        LIMIT 1
    ");
    $existsStmt->execute([$subscriptionId]);
    $existing = $existsStmt->fetch(PDO::FETCH_ASSOC);
    if ($existing) {
        echo json_encode([
            'ok' => false,
            'error' => 'A traffic analysis is already in progress.',
            'queued_review_id' => (int)$existing['id'],
        ]);
        exit;
    }

    $reviewUsername = $is_root ? 'root' : $username;
    $insertStmt = $db->prepare("
        INSERT INTO whp.ai_monitor_log_reviews
            (subscription_id, site_id, username, status, review_type, requested_at)
        VALUES (?, ?, ?, 'pending', 'traffic', NOW())
    ");
    $insertStmt->execute([$subscriptionId, $siteId, $reviewUsername]);
    $reviewId = (int)$db->lastInsertId();

    echo json_encode(['ok' => true, 'queued_review_id' => $reviewId]);
} catch (Throwable $e) {
    error_log('ai-monitor-request-traffic-analysis: ' . $e->getMessage());
    echo json_encode(['ok' => false, 'error' => 'Internal error']);
}
