<?php
/**
 * External AI Monitor Management API for WHMCS Integration
 * Provides AI monitoring subscription management via API keys
 */

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

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

require_once(__DIR__ . '/../../libs/api_auth.php');

try {
    // Authenticate and check permissions
    $authData = api_authenticate('ai_monitor_management');

    $method = $_SERVER['REQUEST_METHOD'];
    $action = $_GET['action'] ?? '';

    switch ($method) {
        case 'GET':
            handleGetRequest($action);
            break;

        case 'POST':
            handlePostRequest($action);
            break;

        default:
            api_response(false, null, 'Method not allowed', 405);
    }

} catch (Exception $e) {
    error_log("External AI Monitor API Error: " . $e->getMessage());
    api_response(false, null, 'Internal server error', 500);
}

/**
 * Get a PDO database connection with whp database selected
 */
function getDbConnection() {
    require_once(__DIR__ . '/../../libs/mysqlmgmt.php');
    $mysql = new mysqlmgmt();
    $db = $mysql->getMySQLConnection();
    $db->exec("USE whp");
    return $db;
}

/**
 * Validate that a user exists
 */
function validateUserExists($db, $username) {
    $stmt = $db->prepare("SELECT COUNT(*) FROM whp.sites WHERE username = ?");
    $stmt->execute([$username]);
    return $stmt->fetchColumn() > 0;
}

/**
 * Validate that a site exists and belongs to the user
 */
function validateSiteOwnership($db, $siteId, $username) {
    $stmt = $db->prepare("SELECT id FROM whp.sites WHERE id = ? AND username = ?");
    $stmt->execute([$siteId, $username]);
    return $stmt->fetch(PDO::FETCH_ASSOC) ? true : false;
}

function handleGetRequest($action) {
    switch ($action) {
        case 'status':
            getSubscriptionStatus();
            break;

        case 'issues':
            getRecentIssues();
            break;

        case 'list_sites':
            listAvailableSites();
            break;

        default:
            api_response(false, null, 'Invalid action. Use: status, issues, list_sites', 400);
    }
}

function handlePostRequest($action) {
    $input = json_decode(file_get_contents('php://input'), true);

    if (!$input) {
        api_response(false, null, 'Invalid JSON input', 400);
    }

    switch ($action) {
        case 'activate':
            activateMonitoring($input);
            break;

        case 'deactivate':
            deactivateMonitoring($input);
            break;

        case 'update_notification_email':
            updateNotificationEmail($input);
            break;

        default:
            api_response(false, null, 'Invalid action. Use: activate, deactivate, update_notification_email', 400);
    }
}

/**
 * GET ?action=status&username=X
 * Get subscription status for all of a user's sites
 */
function getSubscriptionStatus() {
    $username = $_GET['username'] ?? '';
    if (empty($username)) {
        api_response(false, null, 'Username parameter required', 400);
    }

    $db = getDbConnection();

    if (!validateUserExists($db, $username)) {
        api_response(false, null, 'User not found', 404);
    }

    $stmt = $db->prepare("
        SELECT s.id AS site_id, s.site_name, d.domain_name AS primary_domain,
               sub.id AS subscription_id, sub.status, sub.notification_email,
               sub.daily_review_limit, sub.activated_at, sub.cancelled_at
        FROM whp.sites s
        LEFT JOIN whp.domains d ON s.primary_domain_id = d.id
        LEFT JOIN whp.ai_monitor_subscriptions sub ON s.id = sub.site_id AND sub.username = ?
        WHERE s.username = ?
        ORDER BY s.site_name ASC
    ");
    $stmt->execute([$username, $username]);
    $sites = $stmt->fetchAll(PDO::FETCH_ASSOC);

    api_response(true, $sites, 'Subscription status retrieved successfully');
}

/**
 * GET ?action=issues&username=X&site_id=N
 * Get recent issues for a site
 */
function getRecentIssues() {
    $username = $_GET['username'] ?? '';
    $siteId = $_GET['site_id'] ?? '';
    $limit = intval($_GET['limit'] ?? 20);
    $offset = intval($_GET['offset'] ?? 0);

    if (empty($username)) {
        api_response(false, null, 'Username parameter required', 400);
    }
    if (empty($siteId)) {
        api_response(false, null, 'site_id parameter required', 400);
    }

    // Clamp limit to reasonable range
    $limit = max(1, min($limit, 100));
    $offset = max(0, $offset);

    $db = getDbConnection();

    if (!validateUserExists($db, $username)) {
        api_response(false, null, 'User not found', 404);
    }

    if (!validateSiteOwnership($db, $siteId, $username)) {
        api_response(false, null, 'Site not found or does not belong to user', 403);
    }

    // Verify the user has an active subscription for this site
    $stmt = $db->prepare("
        SELECT id FROM whp.ai_monitor_subscriptions
        WHERE site_id = ? AND username = ? AND status = 'active'
    ");
    $stmt->execute([$siteId, $username]);
    if (!$stmt->fetch()) {
        api_response(false, null, 'No active monitoring subscription for this site', 403);
    }

    $stmt = $db->prepare("
        SELECT id, severity, category, title, diagnosis, recommendation,
               container_name, occurrence_count, status, auto_resolved_at,
               status_changed_by, status_changed_at,
               first_seen, last_seen
        FROM whp.ai_monitor_issues
        WHERE site_id = ? AND username = ?
        ORDER BY last_seen DESC
        LIMIT ? OFFSET ?
    ");
    $stmt->execute([$siteId, $username, $limit, $offset]);
    $issues = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Get total count for pagination
    $countStmt = $db->prepare("SELECT COUNT(*) as total FROM whp.ai_monitor_issues WHERE site_id = ? AND username = ?");
    $countStmt->execute([$siteId, $username]);
    $total = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];

    api_response(true, [
        'issues' => $issues,
        'pagination' => [
            'total' => intval($total),
            'limit' => $limit,
            'offset' => $offset
        ]
    ], 'Issues retrieved successfully');
}

/**
 * GET ?action=list_sites&username=X
 * List a user's sites that don't already have an active subscription
 */
function listAvailableSites() {
    $username = $_GET['username'] ?? '';
    if (empty($username)) {
        api_response(false, null, 'Username parameter required', 400);
    }

    $db = getDbConnection();

    if (!validateUserExists($db, $username)) {
        api_response(false, null, 'User not found', 404);
    }

    $stmt = $db->prepare("
        SELECT s.id, s.site_name, d.domain_name AS primary_domain
        FROM whp.sites s
        LEFT JOIN whp.domains d ON s.primary_domain_id = d.id
        WHERE s.username = ?
          AND s.id NOT IN (
              SELECT site_id FROM whp.ai_monitor_subscriptions
              WHERE username = ? AND status = 'active'
          )
        ORDER BY s.site_name ASC
    ");
    $stmt->execute([$username, $username]);
    $sites = $stmt->fetchAll(PDO::FETCH_ASSOC);

    api_response(true, $sites, 'Available sites retrieved successfully');
}

/**
 * POST ?action=activate
 * Enable monitoring for a site
 */
function activateMonitoring($input) {
    $username = $input['username'] ?? '';
    $siteId = $input['site_id'] ?? '';
    $notificationEmail = $input['notification_email'] ?? null;

    if (empty($username)) {
        api_response(false, null, 'username is required', 400);
    }
    if (empty($siteId)) {
        api_response(false, null, 'site_id is required', 400);
    }

    $db = getDbConnection();

    // Validate user exists
    if (!validateUserExists($db, $username)) {
        api_response(false, null, 'User not found', 404);
    }

    // Validate site exists and belongs to user
    if (!validateSiteOwnership($db, $siteId, $username)) {
        api_response(false, null, 'Site not found or does not belong to user', 403);
    }

    // Check for duplicate active subscription
    $stmt = $db->prepare("
        SELECT id FROM whp.ai_monitor_subscriptions
        WHERE site_id = ? AND username = ? AND status = 'active'
    ");
    $stmt->execute([$siteId, $username]);
    if ($stmt->fetch()) {
        api_response(false, null, 'An active monitoring subscription already exists for this site', 409);
    }

    // Create subscription
    $stmt = $db->prepare("
        INSERT INTO whp.ai_monitor_subscriptions
        (site_id, username, notification_email, status, activated_at, created_at, updated_at)
        VALUES (?, ?, ?, 'active', NOW(), NOW(), NOW())
    ");
    $stmt->execute([$siteId, $username, $notificationEmail]);
    $subscriptionId = $db->lastInsertId();

    api_response(true, [
        'subscription_id' => $subscriptionId,
        'site_id' => $siteId,
        'username' => $username,
        'status' => 'active',
        'activated_at' => date('c')
    ], 'Monitoring activated successfully');
}

/**
 * POST ?action=deactivate
 * Cancel monitoring for a site
 */
function deactivateMonitoring($input) {
    $username = $input['username'] ?? '';
    $siteId = $input['site_id'] ?? '';

    if (empty($username)) {
        api_response(false, null, 'username is required', 400);
    }
    if (empty($siteId)) {
        api_response(false, null, 'site_id is required', 400);
    }

    $db = getDbConnection();

    // Validate active subscription exists
    $stmt = $db->prepare("
        SELECT id FROM whp.ai_monitor_subscriptions
        WHERE site_id = ? AND username = ? AND status = 'active'
    ");
    $stmt->execute([$siteId, $username]);
    $sub = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$sub) {
        api_response(false, null, 'No active monitoring subscription found for this site', 404);
    }

    // Cancel subscription
    $stmt = $db->prepare("
        UPDATE whp.ai_monitor_subscriptions
        SET status = 'cancelled', cancelled_at = NOW(), updated_at = NOW()
        WHERE id = ?
    ");
    $stmt->execute([$sub['id']]);

    api_response(true, [
        'subscription_id' => $sub['id'],
        'site_id' => $siteId,
        'username' => $username,
        'status' => 'cancelled',
        'cancelled_at' => date('c')
    ], 'Monitoring deactivated successfully');
}

/**
 * POST ?action=update_notification_email
 * Update notification email for an active subscription
 */
function updateNotificationEmail($input) {
    $username = $input['username'] ?? '';
    $siteId = $input['site_id'] ?? '';
    $notificationEmail = $input['notification_email'] ?? '';

    if (empty($username)) {
        api_response(false, null, 'username is required', 400);
    }
    if (empty($siteId)) {
        api_response(false, null, 'site_id is required', 400);
    }
    if (empty($notificationEmail)) {
        api_response(false, null, 'notification_email is required', 400);
    }

    // Validate email format
    if (!filter_var($notificationEmail, FILTER_VALIDATE_EMAIL)) {
        api_response(false, null, 'Invalid email format', 400);
    }

    $db = getDbConnection();

    // Validate active subscription exists
    $stmt = $db->prepare("
        SELECT id FROM whp.ai_monitor_subscriptions
        WHERE site_id = ? AND username = ? AND status = 'active'
    ");
    $stmt->execute([$siteId, $username]);
    $sub = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$sub) {
        api_response(false, null, 'No active monitoring subscription found for this site', 404);
    }

    // Update notification email
    $stmt = $db->prepare("
        UPDATE whp.ai_monitor_subscriptions
        SET notification_email = ?, updated_at = NOW()
        WHERE id = ?
    ");
    $stmt->execute([$notificationEmail, $sub['id']]);

    api_response(true, [
        'subscription_id' => $sub['id'],
        'site_id' => $siteId,
        'username' => $username,
        'notification_email' => $notificationEmail,
        'updated_at' => date('c')
    ], 'Notification email updated successfully');
}
?>
