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

try {
    // Ensure the path to the database is correct relative to this script
    // Assumes .keys.db is in the 'api' subdirectory relative to the script
    $dbPath = __DIR__ . "/api/.keys.db";
    $db = new PDO("sqlite:" . $dbPath);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Get parameters from the request
    $domainKey = $_GET['key'] ?? '';
    $subKey = $_GET['subkey'] ?? '';
    $folderKey = $_GET['folderkey'] ?? ''; // Optional, for backward compatibility

    // New keys for app validation
    $appNameKey = $_GET['app_name_key'] ?? '';
    $packageNameKey = $_GET['package_name_key'] ?? ''; // This is the KEY for the package name

    // Normalize app name and package name immediately upon retrieval from GET
    $appName = trim(strtolower($_GET['app_name'] ?? '')); // Actual app name, NOW NORMALIZED
    $packageName = trim(strtolower($_GET['package_name'] ?? '')); // Actual package name, NOW NORMALIZED

    $row = null; // Initialize row to null

    // Prioritize app/package name validation if their keys AND names are provided
    if (!empty($appNameKey) && !empty($packageNameKey) && !empty($appName) && !empty($packageName)) {
        // Look up by app_name, package_name, and their respective keys
        // IMPORTANT: The column in DB for the PACKAGE API KEY is 'package_api_key'
        // And the column for the actual PACKAGE NAME is 'package_name'
        $stmt = $db->prepare("SELECT * FROM api_keys WHERE app_name = :app_name AND package_name = :package_name AND app_name_api_key = :app_name_api_key AND package_api_key = :package_api_key");
        $stmt->bindParam(':app_name', $appName, PDO::PARAM_STR);
        $stmt->bindParam(':package_name', $packageName, PDO::PARAM_STR); // This uses the 'package_name' column for the actual package name
        $stmt->bindParam(':app_name_api_key', $appNameKey, PDO::PARAM_STR);
        $stmt->bindParam(':package_api_key', $packageNameKey, PDO::PARAM_STR); // This uses the 'package_api_key' column for the package's API key
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        // If no match found for app/package keys, fall back to domain keys
        if (!$row) {
            // Log this for debugging if necessary, but don't expose to user
            error_log("API Validation: No app/package key match found for app_name: '$appName', package_name: '$packageName' with provided keys.");
        }
    }

    // If app/package keys didn't yield a result, or weren't provided, try domain/subdomain/folder keys (for backward compatibility)
    if (!$row && (!empty($domainKey) && !empty($subKey))) {
        if (!empty($folderKey)) {
            $stmt = $db->prepare("SELECT * FROM api_keys WHERE domain_api_key = :domain_key AND subdomain_api_key = :sub_key AND folder_api_key = :folder_key");
            $stmt->bindParam(':domain_key', $domainKey, PDO::PARAM_STR);
            $stmt->bindParam(':sub_key', $subKey, PDO::PARAM_STR);
            $stmt->bindParam(':folder_key', $folderKey, PDO::PARAM_STR);
            $stmt->execute();
        } else {
            $stmt = $db->prepare("SELECT * FROM api_keys WHERE domain_api_key = :domain_key AND subdomain_api_key = :sub_key");
            $stmt->bindParam(':domain_key', $domainKey, PDO::PARAM_STR);
            $stmt->bindParam(':sub_key', $subKey, PDO::PARAM_STR);
            $stmt->execute();
        }
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$row) {
            error_log("API Validation: No domain/subdomain key match found for domain_key: '$domainKey', sub_key: '$subKey'.");
        }
    }

    // If no keys were provided at all (neither app/package nor domain/subdomain)
    // or if no match was found after trying both
    if (!$row) { // This condition now correctly handles all 'no match' scenarios
        echo json_encode(['status' => 'invalida', 'mensagem' => 'Chaves não encontradas ou inválidas.']);
        exit;
    }

    // Process the validation result if a row was found
    if ($row['status'] === 'blocked') {
        echo json_encode(['status' => 'bloqueada', 'mensagem' => 'Aplicativo Vencido ou Não Válido. Entre em Contato Conosco.']);
    } elseif (strtotime($row['expires_at']) < time()) {
        // Optional: Update status to 'expired' in DB if not already
        if ($row['status'] !== 'expired') {
            $updateStmt = $db->prepare("UPDATE api_keys SET status = 'expired' WHERE id = ?");
            $updateStmt->execute([$row['id']]);
        }
        echo json_encode(['status' => 'expirada', 'mensagem' => 'Chave expirada.']);
    } else {
        echo json_encode(['status' => 'valida', 'mensagem' => 'Chave válida.']);
    }

} catch (Exception $e) {
    // Log the error for debugging, but provide a generic message to the client
    error_log("API Validation Error: " . $e->getMessage());
    echo json_encode(['status' => 'erro', 'mensagem' => 'Erro interno do servidor. Por favor, tente novamente mais tarde.']);
}
?>