<?php
// Secure and Refactored ck_one.php

// Load environment variables (for sensitive data like DB credentials and keys)
require_once '/var/www/html/proxy/config.php'; // Update with the actual path to env loader

// Utility functions
function decryptData($data, $key) {
    $data = base64_decode($data);
    $decrypted = '';
    for ($i = 0; $i < strlen($data); $i++) {
        $decrypted .= chr(ord($data[$i]) ^ ord($key[$i % strlen($key)]));
    }
    return $decrypted;
}

function findChannelByNumber($channelNumber, $fileData) {
    foreach ($fileData as $channel) {
        if ($channel['Channel No'] == $channelNumber) {
            return $channel;
        }
    }
    return null;
}

function validateJsonStructure($data) {
    return isset($data['kids']) && is_array($data['kids']) && count($data['kids']) === 1 && $data['kids'][0] === 'AAAAAAAAAAAAAAAAAAAAAA';
}

function hexToBase64NoPadding($hexString) {
    $binaryData = hex2bin($hexString);
    $base64Encoded = rtrim(base64_encode($binaryData), '=');
    return $base64Encoded;
}

function isRequestValid($headers, $contentType, $method, $jsonError) {
    return count($headers) > 1 && strtolower($contentType) === 'application/json' && $method === 'POST' && $jsonError === JSON_ERROR_NONE;
}

// Configuration
$deckey = DECRYPTION_KEY; // Load decryption key from environment
$channelFile = CHANNEL_FILE; // Ensure this is accessible and secure

// Database credentials (use environment variables)
$servername = DB_HOST;
$username = DB_USER;
$password = DB_PASS;
$dbname = DB_NAME;

// Decode incoming data
$id = $_GET['ab'];
$headers = getallheaders();
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
$method = $_SERVER['REQUEST_METHOD'] ?? '';
$rawData = file_get_contents("php://input");
$decodedData = json_decode($rawData, true);

// Validate request
if (!isRequestValid($headers, $contentType, $method, json_last_error())) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid request']);
    exit;
}

// Decrypt ID
$decryptedData = decryptData($id, $deckey);
$explodedData = explode('!', $decryptedData);
$chn = $explodedData[0] ?? '';
$user = $explodedData[1] ?? '';
$m_ua = $explodedData[2] ?? '';

// Fetch channel data
$fileData = json_decode(file_get_contents($channelFile), true);
if (!$fileData) {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to load channel data']);
    exit;
}

// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    http_response_code(500);
    echo json_encode(['error' => 'Database connection failed']);
    exit;
}

// Validate user
$stmt = $conn->prepare("SELECT user_id, valid FROM customers_1_dev WHERE user_id = ?");
$stmt->bind_param('s', $user);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0) {
    http_response_code(403);
    echo json_encode(['error' => 'Unauthorized user']);
    $stmt->close();
    $conn->close();
    exit;
}
$stmt->close();

// Check user login status
$stmt = $conn->prepare("SELECT * FROM logins_1_dev WHERE user_id = ? AND user_agent = ?");
$stmt->bind_param('ss', $user, $m_ua);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if ($result->num_rows === 0 || $row['status'] != '1') {
    http_response_code(403);
    echo json_encode(['error' => 'Unauthorized login']);
    $stmt->close();
    $conn->close();
    exit;
}
$stmt->close();

// Check payment status
$stmt = $conn->prepare("SELECT * FROM payments_1_dev WHERE user_id = ?");
$stmt->bind_param('s', $user);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$currentTimestamp = time();
$validUntilTimestamp = strtotime("+{$row['valid_till']} days", strtotime($row['act_time']));

if ($validUntilTimestamp <= $currentTimestamp || $row['status'] != '1') {
    // Update payment status if expired
    $stmt->close();
    $stmt = $conn->prepare("UPDATE payments_1_dev SET payment = 'unpaid', status = '0' WHERE user_id = ?");
    $stmt->bind_param('s', $user);
    $stmt->execute();
    http_response_code(403);
    echo json_encode(['error' => 'Payment required']);
    $stmt->close();
    $conn->close();
    exit;
}
$stmt->close();

// Retrieve channel key
$channelData = findChannelByNumber($chn, $fileData);
if (!$channelData) {
    http_response_code(404);
    echo json_encode(['error' => 'Channel not found']);
    $conn->close();
    exit;
}

$keyParts = explode(':', $channelData['Key']);
$kid = hexToBase64NoPadding($keyParts[0]);
$key = hexToBase64NoPadding($keyParts[1]);

// Return the JWK response
header('Content-Type: application/json');
$jsonData = '{"keys":[{"kty":"oct","kid":"' . $kid . '","k":"' . $key . '"}]}';
echo $jsonData;

$conn->close();
?>
