<?php
header("Content-Type: application/json");
session_start();

$input = json_decode(file_get_contents("php://input"), true);

include "../config/connect.php"; // pastikan $pdo sudah tersedia

$token = $input['token'] ?? '';
$handphone = $input['handphone'] ?? '';

$response = ['valid' => false];

if ($token && $handphone) {
    $stmt = $pdo->prepare("SELECT id FROM agen_voucher WHERE nomor_whatsapp = :handphone AND token = :token");
    $stmt->bindParam(':handphone', $handphone, PDO::PARAM_STR);
    $stmt->bindParam(':token', $token, PDO::PARAM_STR);
    $stmt->execute();

    if ($user = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $_SESSION['agen'] = $user['id'];
        $response['valid'] = true;
        $response['userId'] = $user['id'];
    } else {
        session_destroy();
    }
}

echo json_encode($response);
