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

wisender_require_access_token();

$chromeStoreID = $_GET['chromeStoreID'] ?? null;
$auth = wisender_get_header('Authorization');

if (!$chromeStoreID || !$auth || stripos($auth, 'Bearer ') !== 0) {
    echo json_encode([
        "success" => false,
        "message" => "Missing bearer token",
        "msg_id"  => "missing_bearer"
    ]);
    exit;
}

$bearer = trim(substr($auth, 7));
if ($bearer === '') {
    echo json_encode([
        "success" => false,
        "message" => "Missing bearer token",
        "msg_id"  => "missing_bearer"
    ]);
    exit;
}

$conn = wisender_db();

$stmt = $conn->prepare("SELECT id, user_id, customer_name, whatsapp_number, email, plan_expiry_date, status, archive, deleted_key, created_at, token FROM users WHERE token = ? LIMIT 1");
$stmt->bind_param("s", $bearer);
$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;
}

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

echo json_encode([
    "success"     => true,
    "message"     => "Login realizado com sucesso",
    "msg_id"      => "login_success",
    "user"        => $user_obj,
    "auth_google" => null,
    "user_status" => $user_status
]);

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