<?php
// verify.php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(403);
    exit;
}

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

try {
    $db_config = [
        'host' => 'localhost',
        'dbname' => 'everplex_n92dh1lic1',
        'user' => 'everplex_n98zd3lic1u',
        'pass' => 'yIG#b9sDt1oOqikCY%'
    ];

    $pdo = new PDO(
        "mysql:host={$db_config['host']};dbname={$db_config['dbname']}",
        $db_config['user'],
        $db_config['pass']
    );
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $license_key = trim($_POST['license_key'] ?? '');
    $domain = trim($_POST['domain'] ?? '');
    $feature = trim($_POST['feature'] ?? '');

    if (empty($license_key) || empty($domain) || empty($feature)) {
        throw new Exception('Missing required fields');
    }

    // Get IDs with error checking
    $domain_stmt = $pdo->prepare("SELECT id FROM license_domains WHERE domain = ?");
    $domain_stmt->execute([$domain]);
    $domain_id = $domain_stmt->fetchColumn();
    if (!$domain_id) {
        throw new Exception('Domain not found');
    }

    $feature_stmt = $pdo->prepare("SELECT id FROM license_features WHERE name = ?");
    $feature_stmt->execute([$feature]);
    $feature_id = $feature_stmt->fetchColumn();
    if (!$feature_id) {
        throw new Exception('Feature not found');
    }

    $stmt = $pdo->prepare("
        SELECT * FROM license_keys 
        WHERE domain_id = ? 
        AND feature_id = ?
        AND key_value = ?
        AND status = 'active'
        AND (expires_at > NOW() OR expires_at IS NULL)
    ");
    $stmt->execute([$domain_id, $feature_id, $license_key]);
    $license = $stmt->fetch(PDO::FETCH_ASSOC);

    echo json_encode([
        'valid' => !empty($license),
        'debug' => [
            'domain_id' => $domain_id,
            'feature_id' => $feature_id,
            'found' => !empty($license)
        ]
    ]);

} catch (Exception $e) {
    echo json_encode([
        'valid' => false,
        'error' => $e->getMessage(),
        'details' => $e->getTraceAsString()
    ]);
}