<?php
require_once '../config/cors.php';
require_once '../config/database.php';
require_once '../utils/helpers.php';

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

// Extract authorization token
$token = getAuthToken();

// Validate token
$user = getUserFromToken($token);
if (!$user) {
    errorResponse('User not authenticated or email not available', 401);
}

// Validate input
if (!isset($input['license_key'])) {
    errorResponse('License key is required', 400);
}

$licenseKey = $input['license_key'];

try {
    // Start transaction
    $pdo->beginTransaction();

    // 1. Find the license key
    // Status ID 4 = pending (available)
    $stmt = $pdo->prepare("SELECT id, subscription_tier_id FROM license_keys WHERE key_value = ? AND status_id = 4 LIMIT 1");
    $stmt->execute([$licenseKey]);
    $license = $stmt->fetch();

    if (!$license) {
        $pdo->rollBack();
        errorResponse('Invalid or already activated license key', 400);
    }

    $licenseId = $license['id'];
    $tierId = $license['subscription_tier_id'];
    $userId = $user['id'];
    $email = $user['email'];

    // 2. Update license key
    // Status ID 1 = active
    $expiresAt = date('Y-m-d H:i:s', strtotime('+1 year'));
    $now = date('Y-m-d H:i:s');

    $stmt = $pdo->prepare("UPDATE license_keys SET user_id = ?, status_id = 1, activated_at = ?, expires_at = ? WHERE id = ?");
    $stmt->execute([$userId, $now, $expiresAt, $licenseId]);

    // 3. Get subscription tier name
    $stmt = $pdo->prepare("SELECT name FROM subscription_tiers WHERE id = ?");
    $stmt->execute([$tierId]);
    $tier = $stmt->fetch();
    $tierName = $tier ? $tier['name'] : 'Unknown';

    // 4. Upsert subscriber record
    // Check if user is already a subscriber
    $stmt = $pdo->prepare("SELECT id FROM subscribers WHERE user_id = ? OR email = ?");
    $stmt->execute([$userId, $email]);
    $existingSubscriber = $stmt->fetch();

    if ($existingSubscriber) {
        // Update existing
        $stmt = $pdo->prepare("UPDATE subscribers SET subscribed = 1, subscription_tier_id = ?, subscription_end = ?, updated_at = ? WHERE id = ?");
        $stmt->execute([$tierId, $expiresAt, $now, $existingSubscriber['id']]);
    } else {
        // Insert new
        $subId = generateUUID();
        $stmt = $pdo->prepare("INSERT INTO subscribers (id, user_id, email, subscribed, subscription_tier_id, subscription_end, created_at, updated_at) VALUES (?, ?, ?, 1, ?, ?, ?, ?)");
        $stmt->execute([$subId, $userId, $email, $tierId, $expiresAt, $now, $now]);
    }

    // 5. Log admin/user action (optional but good for consistency)
    // Using dashboard_logs for now as it is user initiated
    $logId = generateUUID();
    $stmt = $pdo->prepare("INSERT INTO dashboard_logs (id, user_id, action, details) VALUES (?, ?, ?, ?)");
    $stmt->execute([$logId, $userId, 'activate_license', json_encode(['license_key' => $licenseKey, 'tier' => $tierName])]);

    $pdo->commit();

    jsonResponse([
        'success' => true,
        'message' => 'License activated successfully',
        'tier' => $tierName
    ], 200);

} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    errorResponse('Error activating license: ' . $e->getMessage(), 500);
}
?>