<?php



require_once __DIR__ . '/../con/config.php';

// Ruta a la clave privada RSA (ajusta según tu configuración)
$privateKeyPath = '/home/secure_keys/private_key.pem'; // Debe coincidir con la clave pública usada en el cliente

// Check if nonce and channel ID are provided
if (!isset($_POST['nonce'])) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Missing nonce']);
    exit;
}
if (!isset($_GET['id']) && !isset($_POST['id'])) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Channel ID is required']);
    exit;
}

// Get nonce and channel ID
$encryptedNonceBase64 = $_POST['nonce'];
$channel_id = isset($_GET['id']) ? (int)$_GET['id'] : (int)$_POST['id'];

// Decode Base64 nonce
$encryptedNonce = base64_decode($encryptedNonceBase64);
if ($encryptedNonce === false) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Invalid nonce format']);
    exit;
}

// Decrypt nonce with private key
$privateKey = openssl_pkey_get_private(file_get_contents($privateKeyPath));
if ($privateKey === false) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Failed to load private key: ' . openssl_error_string()]);
    exit;
}

$decrypted = '';
if (!openssl_private_decrypt($encryptedNonce, $decrypted, $privateKey, OPENSSL_PKCS1_PADDING)) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Failed to decrypt nonce: ' . openssl_error_string()]);
    exit;
}
$nonce = $decrypted;

// Query the channel
$stmt = $conn->prepare("
    SELECT drm_scheme, drm_license_uri 
    FROM channels 
    WHERE id = ? AND drm_scheme = 'clearkey'
");
$stmt->bind_param("i", $channel_id);
$stmt->execute();
$result = $stmt->get_result();
$channel = $result->fetch_assoc();
$stmt->close();

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

if (!$channel) {
    echo json_encode(['error' => 'No ClearKey channel found with ID ' . $channel_id]);
} else {
    // Decode the original JSON from the database
    $json = json_decode($channel['drm_license_uri'], true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        echo json_encode(['error' => 'Invalid ClearKey JSON for channel ID ' . $channel_id]);
        exit;
    }

    // Generate AES key from decrypted nonce (same logic as client)
    $temp_key = hash('sha256', $nonce, true); // SHA-256 en binario
    $aes_key = substr($temp_key, 0, 16); // Truncar a 16 bytes para AES-128

    // Convert JSON to string
    $clear_key_json = json_encode($json, JSON_UNESCAPED_SLASHES);

    // Encrypt with AES-128-ECB
    $encrypted = openssl_encrypt(
        $clear_key_json,
        'AES-128-ECB',
        $aes_key,
        0, // Incluye padding PKCS5 por defecto
        '' // No IV for ECB mode
    );

    if ($encrypted === false) {
        echo json_encode(['error' => 'Encryption failed: ' . openssl_error_string()]);
        exit;
    }

    // Return encrypted data as Base64
    echo json_encode(['encrypted_key' => $encrypted]);
}

$conn->close();
?>