<?php
session_start();
include "config.php";
include_once __DIR__ . '/../includes/whatsapp_lib.php';

header('Content-Type: application/json');

if (!isset($_SESSION['username'])) {
    echo json_encode(['ok' => false, 'message' => 'Unauthorized']);
    exit;
}
$userdata = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM users WHERE mobile = '" . mysqli_real_escape_string($conn, $_SESSION['username']) . "'"));

if (!$userdata || $userdata["role"] != 'Admin') {
    echo json_encode(['ok' => false, 'message' => 'Unauthorized']);
    exit;
}

$accountId = $_GET['account_id'] ?? '';
if ($accountId === '') {
    echo json_encode(['ok' => false, 'message' => 'account_id required']);
    exit;
}

$status = wa_check_status($conn, $accountId);

if ($status['ok'] && in_array($status['status'], ['connected', 'disconnected'], true)) {
    $conn->query("UPDATE whatsapp_accounts SET status = '" . mysqli_real_escape_string($conn, $status['status']) . "' WHERE account_id = '" . mysqli_real_escape_string($conn, $accountId) . "'");
}

echo json_encode($status);
