<?php
error_reporting(0);

$query = "SELECT * FROM ads WHERE owner = 'ADM'";

// === PEGA O MAC ===
if (isset($_GET['mac'])) {
    if ($_GET['mac'] != "undefined") {
        $mac_address = $_GET['mac'];
        $mac_address = chunk_split($mac_address, 2, ':');
        $mac_address = rtrim($mac_address, ':');
        $usuario_mac = strtoupper($mac_address);
        $data_hj = date("Y/m/d H:i");
        file_put_contents(__DIR__ . "/example.txt", "ads.php -> $data_hj -> $usuario_mac\n", FILE_APPEND);
    } else {
        $usuario_mac = strtoupper(trim(file_get_contents(__DIR__ . '/../a/last_mac.txt')));
    }
} else {
    $usuario_mac = strtoupper(trim(file_get_contents(__DIR__ . '/../a/last_mac.txt')));
}

// === CONECTA NO BANCO LOCAL (NA MESMA PASTA DO SCRIPT)
$db1 = new SQLite3(__DIR__ . '/.adb.db');

// === VERIFICA SE O MAC EXISTE NA BASE DE USUÁRIOS
$db_users = new SQLite3(__DIR__ . '/../a/.eggziedb.db');
$result = $db_users->query("SELECT COUNT(id) AS total FROM ibo WHERE mac_address = '$usuario_mac' AND seller <> 'ADM'");
$rownew = $result->fetchArray();
$count = $rownew['total'];

// === SE FOR CLIENTE DE ALGUM VENDEDOR, MOSTRA ANÚNCIOS DO VENDEDOR
if ($count > 0) {
    $res1 = $db_users->query("SELECT * FROM ibo WHERE mac_address = '$usuario_mac'");
    while ($row1 = $res1->fetchArray()) {
        $user_seller = $row1['seller'];
    }
    $query = "SELECT * FROM ads WHERE owner = '$user_seller'";
}

// === LÊ OS ANÚNCIOS DO BANCO LOCAL
$res = $db1->query($query);
$json_response = [];

while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
    $json_response[] = [
        "AdName" => $row['title'],
        "AdUrl"  => $row['url']
    ];
}

// === RETORNA JSON COMPATÍVEL COM O APP
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($json_response, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
?>
