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


$privateKeyPath = $_SERVER['DOCUMENT_ROOT'] . '/panel_api/private_key.pem';

$cipher = 'AES-128-ECB';

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

if (!isset($_POST['nonce'])) {
    echo json_encode(['error' => 'Missing nonce']);
    exit;
}

$channel_id = isset($_GET['id']) ? (int)$_GET['id'] : (isset($_POST['id']) ? (int)$_POST['id'] : 0);
if ($channel_id <= 0) {
    echo json_encode(['error' => 'Channel ID is required']);
    exit;
}

$encryptedNonceBase64 = $_POST['nonce'];
$encryptedNonce = base64_decode($encryptedNonceBase64);
if ($encryptedNonce === false) {
    echo json_encode(['error' => 'Invalid nonce format']);
    exit;
}

$privateKeyContent = file_get_contents($privateKeyPath);
if ($privateKeyContent === false) {
    echo json_encode(['error' => 'Private key file not found']);
    exit;
}

$privateKey = openssl_pkey_get_private($privateKeyContent);
if ($privateKey === false) {
    echo json_encode(['error' => 'Failed to load private key: ' . openssl_error_string()]);
    exit;
}

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

$nonce = $decrypted;

$stmt = $conn->prepare("
    SELECT drm_license_uri 
    FROM channels 
    WHERE id = ? AND drm_scheme = 'clearkey'
    LIMIT 1
");

if (!$stmt) {
    echo json_encode(['error' => 'Database query preparation failed: ' . $conn->error]);
    exit;
}

$stmt->bind_param("i", $channel_id);
$stmt->execute();
$result = $stmt->get_result();
$channel = $result->fetch_assoc();
$stmt->close();

if (!$channel || empty($channel['drm_license_uri'])) {
    echo json_encode(['error' => 'No ClearKey channel found with ID ' . $channel_id]);
    $conn->close();
    exit;
}

$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]);
    $conn->close();
    exit;
}

$conn->close();

$temp_key = hash('sha256', $nonce, true);
$aes_key = substr($temp_key, 0, 16);

$clear_key_json = json_encode($json, JSON_UNESCAPED_SLASHES);

$encrypted = openssl_encrypt(
    $clear_key_json,
    $cipher,
    $aes_key,
    0,
    ''
);

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

echo json_encode(['encrypted_key' => $encrypted]);
?>
