<?php
/**
 * Simple License Connection API
 * Endpoint for ERP instances to verify their license using the connection token
 */
require_once '../config.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(['success' => false, 'error' => 'Method not allowed'], 405);
}

$input = json_decode(file_get_contents('php://input'), true);
$token = $input['token'] ?? '';

if (empty($token)) {
    jsonResponse(['success' => false, 'error' => 'Token required'], 400);
}

// Decode the connection token
$tokenData = decodeConnectionToken($token);
if (!$tokenData) {
    jsonResponse(['success' => false, 'error' => 'Invalid token format'], 400);
}

$licenseKey = $tokenData['license_key'];

// Verify the license
try {
    // Get instance and tenant info
    $stmt = $pdo->prepare("
        SELECT 
            i.id as instance_id,
            i.tenant_id,
            i.license_key,
            t.name as tenant_name,
            t.status as tenant_status,
            s.id as subscription_id,
            s.plan_type,
            s.expires_at,
            s.max_users,
            s.max_employees,
            s.status as subscription_status
        FROM instances i
        JOIN tenants t ON i.tenant_id = t.id
        LEFT JOIN subscriptions s ON t.id = s.tenant_id AND s.status = 'active'
        WHERE i.license_key = ?
        LIMIT 1
    ");
    $stmt->execute([$licenseKey]);
    $instance = $stmt->fetch();

    if (!$instance) {
        jsonResponse(['success' => false, 'error' => 'License not found'], 404);
    }

    // Check tenant status
    if ($instance['tenant_status'] === 'suspended') {
        jsonResponse(['success' => false, 'error' => 'Account suspended', 'status' => 'suspended'], 403);
    }

    if ($instance['tenant_status'] === 'churned') {
        jsonResponse(['success' => false, 'error' => 'Account cancelled', 'status' => 'churned'], 403);
    }

    // Check subscription
    if (!$instance['subscription_id']) {
        jsonResponse(['success' => false, 'error' => 'No active subscription'], 403);
    }

    if ($instance['expires_at'] && strtotime($instance['expires_at']) < time()) {
        jsonResponse(['success' => false, 'error' => 'Subscription expired', 'expired_at' => $instance['expires_at']], 403);
    }

    // Get authorized modules (subscription + core)
    $stmt = $pdo->prepare("
        SELECT m.code, m.name, m.icon, m.category, 'active' as status, NULL as trial_expires
        FROM subscription_modules sm
        JOIN modules m ON sm.module_code = m.code
        WHERE sm.subscription_id = ?
        UNION
        SELECT code, name, icon, category, 'active' as status, NULL as trial_expires 
        FROM modules WHERE is_core = 1
    ");
    $stmt->execute([$instance['subscription_id']]);
    $activeModules = $stmt->fetchAll();
    
    // Get trial modules (not expired)
    try {
        $stmt = $pdo->prepare("
            SELECT m.code, m.name, m.icon, m.category, 'trial' as status, mt.expires_at as trial_expires
            FROM module_trials mt
            JOIN modules m ON mt.module_code = m.code
            WHERE mt.subscription_id = ? 
              AND mt.expires_at >= CURDATE()
              AND mt.starts_at <= CURDATE()
        ");
        $stmt->execute([$instance['subscription_id']]);
        $trialModules = $stmt->fetchAll();
    } catch (PDOException $e) {
        $trialModules = []; // Table doesn't exist yet
    }
    
    // Merge modules (avoid duplicates - active takes precedence)
    $activeCodes = array_column($activeModules, 'code');
    foreach ($trialModules as $trial) {
        if (!in_array($trial['code'], $activeCodes)) {
            $activeModules[] = $trial;
        }
    }
    $modules = $activeModules;

    // Update last heartbeat
    $stmt = $pdo->prepare("UPDATE instances SET last_heartbeat = NOW() WHERE id = ?");
    $stmt->execute([$instance['instance_id']]);

    // 📊 Record telemetry data
    $clientIP = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $userCount = intval($input['user_count'] ?? 0);
    $stmt = $pdo->prepare("
        INSERT INTO telemetry (instance_id, event_type, user_count, client_ip, recorded_at)
        VALUES (?, 'heartbeat', ?, ?, NOW())
    ");
    $stmt->execute([$instance['instance_id'], $userCount, $clientIP]);

    // Build response
    $response = [
        'success' => true,
        'tenant' => [
            'name' => $instance['tenant_name'],
            'status' => $instance['tenant_status'],
            'plan' => $instance['plan_type']
        ],
        'subscription' => [
            'expires_at' => $instance['expires_at'],
            'is_active' => ($instance['subscription_status'] === 'active')
        ],
        'maxUsers' => intval($instance['max_users'] ?? 5),
        'maxEmployees' => intval($instance['max_employees'] ?? 50),
        'modules' => $modules,
        'modules_details' => $modules,
        'verified_at' => date('Y-m-d H:i:s')
    ];

    // Sign the response
    $response['signature'] = signResponse($response);

    jsonResponse($response);

} catch (Exception $e) {
    jsonResponse(['success' => false, 'error' => 'Server error: ' . $e->getMessage()], 500);
}
