<?php
require_once __DIR__ . '/../_bootstrap.php';

wisender_require_access_token();

$chromeStoreID = $_GET['chromeStoreID'] ?? null;
$data = wisender_json();

$email = $data['email'] ?? null;
$access_token_plugin = $data['access_token_plugin'] ?? null;

if (!$chromeStoreID || !$email || !$access_token_plugin) {
    echo json_encode([
        "success" => false,
        "message" => "Campos obrigatórios",
        "msg_id"  => "missing_fields"
    ]);
    exit;
}

$conn = wisender_db();

$stmt = $conn->prepare("SELECT id, user_id, customer_name, whatsapp_number, email, plan_expiry_date, max_devices, status, archive, deleted_key, created_at, token FROM users WHERE email = ? AND token = ? LIMIT 1");
$stmt->bind_param("ss", $email, $access_token_plugin);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows !== 1) {
    echo json_encode([
        "success" => false,
        "message" => "Sessão inválida",
        "msg_id"  => "invalid_token_in_validation"
    ]);
    exit;
}

$user = $res->fetch_assoc();

if (!wisender_is_enabled($user) || !wisender_plan_is_valid($user)) {
    echo json_encode([
        "success" => false,
        "message" => "Sessão inválida",
        "msg_id"  => "invalid_token_in_validation"
    ]);
    exit;
}

// Optional: ensure device/extension is registered (same logic as validate.php).
try {
    $tableCheck = $conn->query("SHOW TABLES LIKE 'user_devices'");
    if ($tableCheck && $tableCheck->num_rows === 1) {
        $dev = $conn->prepare("SELECT id FROM user_devices WHERE user_id = ? AND chrome_store_id = ?");
        $dev->bind_param("is", $user['id'], $chromeStoreID);
        $dev->execute();
        $devRes = $dev->get_result();
        if ($devRes->num_rows === 0) {
            echo json_encode([
                "success" => false,
                "message" => "Dispositivo não autorizado",
                "msg_id"  => "invalid_token_in_validation"
            ]);
            exit;
        }
        $dev->close();
    }
} catch (Throwable $e) { }

$user_status = wisender_user_status($user);
$user_obj = wisender_build_user($user, $user['token']);

echo json_encode([
    "success"     => true,
    "message"     => "Token válido",
    "msg_id"      => "login_success",
    "user"        => $user_obj,
    "auth_google" => null,
    "user_status" => $user_status
]);

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