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

wisender_require_access_token();

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

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

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

$conn = wisender_db();

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

if ($res->num_rows !== 1) {
    echo json_encode([
        "success" => false,
        "message" => "Usuário não encontrado",
        "msg_id"  => "login_userNotFind"
    ]);
    exit;
}

$user = $res->fetch_assoc();

// password check (your panel stores plain text in `password`)
if ($senha !== $user['password']) {
    echo json_encode([
        "success" => false,
        "message" => "Senha inválida",
        "msg_id"  => "login_senha"
    ]);
    exit;
}

if (!wisender_is_enabled($user)) {
    echo json_encode([
        "success" => false,
        "message" => "Acesso desabilitado",
        "msg_id"  => "login_desabilitado"
    ]);
    exit;
}

if (!wisender_plan_is_valid($user)) {
    echo json_encode([
        "success" => false,
        "message" => "Plano expirado",
        "msg_id"  => "login_desabilitado"
    ]);
    exit;
}

// Optional: device limit logic (kept compatible with your old login.php).
// If user_devices table doesn't exist, it will be skipped.
try {
    $tableCheck = $conn->query("SHOW TABLES LIKE 'user_devices'");
    if ($tableCheck && $tableCheck->num_rows === 1) {
        $deviceCheck = $conn->prepare("SELECT id FROM user_devices WHERE user_id = ? AND chrome_store_id = ?");
        $deviceCheck->bind_param("is", $user['id'], $chromeStoreID);
        $deviceCheck->execute();
        $deviceRes = $deviceCheck->get_result();

        if ($deviceRes->num_rows === 0) {
            $countStmt = $conn->prepare("SELECT COUNT(*) as total FROM user_devices WHERE user_id = ?");
            $countStmt->bind_param("i", $user['id']);
            $countStmt->execute();
            $countRes = $countStmt->get_result()->fetch_assoc();
            $total = (int)($countRes['total'] ?? 0);

            $max = (int)($user['max_devices'] ?? 1);
            if ($total >= $max) {
                echo json_encode([
                    "success" => false,
                    "message" => "Limite de dispositivos atingido",
                    "msg_id"  => "device_limit_reached"
                ]);
                exit;
            }

            $reg = $conn->prepare("INSERT INTO user_devices (user_id, chrome_store_id) VALUES (?, ?)");
            $reg->bind_param("is", $user['id'], $chromeStoreID);
            $reg->execute();
            $reg->close();
        }
        $deviceCheck->close();
    }
} catch (Throwable $e) {
    // ignore device table issues
}

// generate token for extension session
$newToken = bin2hex(random_bytes(16));
$upd = $conn->prepare("UPDATE users SET token = ? WHERE id = ?");
$upd->bind_param("si", $newToken, $user['id']);
$upd->execute();
$upd->close();

$user_status = wisender_user_status($user);
$user_obj = wisender_build_user($user, $newToken);

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();
?>
