<?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', 401);
}

// Check if user is admin
if (!isAdmin($user['id'])) {
    errorResponse('Unauthorized: Admin access required', 403);
}

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

$action = $input['action'];

try {
    switch ($action) {
        case 'create':
            $subscriptionTier = isset($input['subscription_tier']) ? $input['subscription_tier'] : 'basic';
            $quantity = isset($input['quantity']) ? (int)$input['quantity'] : 1;
            
            // Get subscription tier ID
            $stmt = $pdo->prepare("SELECT id FROM subscription_tiers WHERE name = ?");
            $stmt->execute([$subscriptionTier]);
            $tier = $stmt->fetch();
            
            if (!$tier) {
                errorResponse('Invalid subscription tier', 400);
            }
            
            $licenses = [];
            for ($i = 0; $i < $quantity; $i++) {
                $licenseKey = generateLicenseKey();
                
                $id = generateUUID();
                $stmt = $pdo->prepare("INSERT INTO license_keys (id, key_value, subscription_tier_id, status_id) VALUES (?, ?, ?, 4)");
                $stmt->execute([$id, $licenseKey, $tier['id']]);
                
                $stmt = $pdo->prepare("SELECT lk.*, st.name as subscription_tier FROM license_keys lk JOIN subscription_tiers st ON lk.subscription_tier_id = st.id WHERE lk.id = ?");
                $stmt->execute([$id]);
                $license = $stmt->fetch();
                
                $licenses[] = $license;
            }
            
            // Log admin action
            $logId = generateUUID();
            $stmt = $pdo->prepare("INSERT INTO admin_logs (id, admin_id, action, target_table, details) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([
                $logId,
                $user['id'],
                'create_license_keys',
                'license_keys',
                json_encode(['subscription_tier' => $subscriptionTier, 'quantity' => $quantity, 'created_keys' => array_column($licenses, 'key_value')])
            ]);
            
            jsonResponse(['licenses' => $licenses], 200);
            break;
            
        case 'list':
            $stmt = $pdo->prepare("SELECT lk.*, st.name as subscription_tier, ls.name as status, u.email as user_email FROM license_keys lk JOIN subscription_tiers st ON lk.subscription_tier_id = st.id JOIN license_status ls ON lk.status_id = ls.id LEFT JOIN users u ON lk.user_id = u.id ORDER BY lk.created_at DESC");
            $stmt->execute();
            $licenses = $stmt->fetchAll();
            
            jsonResponse(['licenses' => $licenses], 200);
            break;
            
        case 'update':
            $id = isset($input['id']) ? $input['id'] : null;
            $status = isset($input['status']) ? $input['status'] : null;
            
            if (!$id || !$status) {
                errorResponse('ID and status are required', 400);
            }
            
            // Get status ID
            $stmt = $pdo->prepare("SELECT id FROM license_status WHERE name = ?");
            $stmt->execute([$status]);
            $statusRow = $stmt->fetch();
            
            if (!$statusRow) {
                errorResponse('Invalid status', 400);
            }
            
            $stmt = $pdo->prepare("UPDATE license_keys SET status_id = ?, updated_at = datetime('now') WHERE id = ?");
            $stmt->execute([$statusRow['id'], $id]);
            
            $stmt = $pdo->prepare("SELECT lk.*, st.name as subscription_tier, ls.name as status FROM license_keys lk JOIN subscription_tiers st ON lk.subscription_tier_id = st.id JOIN license_status ls ON lk.status_id = ls.id WHERE lk.id = ?");
            $stmt->execute([$id]);
            $license = $stmt->fetch();
            
            // Log admin action
            $logId = generateUUID();
            $stmt = $pdo->prepare("INSERT INTO admin_logs (id, admin_id, action, target_table, target_id, details) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([
                $logId,
                $user['id'],
                'update_license_key',
                'license_keys',
                $id,
                json_encode(['status' => $status])
            ]);
            
            jsonResponse(['license' => $license], 200);
            break;
            
        case 'delete':
            $id = isset($input['id']) ? $input['id'] : null;
            
            if (!$id) {
                errorResponse('ID is required', 400);
            }
            
            $stmt = $pdo->prepare("DELETE FROM license_keys WHERE id = ?");
            $stmt->execute([$id]);
            
            // Log admin action
            $logId = generateUUID();
            $stmt = $pdo->prepare("INSERT INTO admin_logs (id, admin_id, action, target_table, target_id) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([
                $logId,
                $user['id'],
                'delete_license_key',
                'license_keys',
                $id
            ]);
            
            jsonResponse(['success' => true], 200);
            break;
            
        default:
            errorResponse('Invalid action', 400);
    }
} catch (Exception $e) {
    errorResponse('Error managing licenses: ' . $e->getMessage(), 500);
}
?>