<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

if (!isset($_GET['wl_id'])) {
    echo json_encode([
        "success" => false,
        "message" => "Missing wl_id",
        "wl" => null
    ]);
    exit;
}

$wl_id = $_GET['wl_id'];

// DB config
$host = 'localhost';
$db = 'vdojgvrn_14598';
$user = 'vdojgvrn_14598';
$pass = 'vdojgvrn_14598';

$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
    echo json_encode([
        "success" => false,
        "message" => "Database connection failed",
        "wl" => null
    ]);
    exit;
}

// Check if device exists in user_devices table
$stmt = $conn->prepare("SELECT id FROM user_devices WHERE chrome_store_id = ?");
$stmt->bind_param("s", $wl_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode([
        "success" => false,
        "message" => "Device not found",
        "wl" => null
    ]);
    exit;
}

// If found, respond with wl object
$response = [
    "success" => true,
    "message" => "WL capturada",
    "wl" => [
        "id" => $wl_id,
        "checkout" => "https://wa.me/k43?text=Hello%2C%20I%20want%20to%20Buy%20WaBaCRM%20License%20Version",
        "tutorial" => "https://www.youtube.com/",
        "webhook" => "https://n8n.waspeed.com.br/webhook/instalaouBackEnd",
        "cor_primaria" => 0,
        "banner" => null,
        "status" => "ACTIVE",
        "install" => "https://yourportal.com",
        "uninstall" => "https://yourportal.com",
        "rewards" => "https://yourportal.com/"
    ]
];

echo json_encode($response);

$stmt->close();
$conn->close();
?>
