<?php
// Genera un MAC fittizio compatibile con il pannello: AA:BB:CC:DD
// Non modifica account esistenti: serve solo a dare all'app/pannello un MAC nuovo.
header('Content-Type: application/json; charset=utf-8');

function normalize_mac_address($value) {
    $mac = preg_replace('/[^A-Fa-f0-9]/', '', (string)$value);
    $mac = strtoupper(substr($mac, 0, 8));
    if (strlen($mac) < 8) { return ''; }
    return implode(':', str_split($mac, 2));
}

function generate_fake_mac_address() {
    $bytes = [0x02, random_int(0x00, 0xFF), random_int(0x00, 0xFF), random_int(0x00, 0xFF)];
    return strtoupper(sprintf('%02X:%02X:%02X:%02X', $bytes[0], $bytes[1], $bytes[2], $bytes[3]));
}

$portal_slot = isset($_GET['portal_slot']) ? intval($_GET['portal_slot']) : (isset($_GET['portal']) ? intval($_GET['portal']) : 1);
if ($portal_slot < 1 || $portal_slot > 5) { $portal_slot = 1; }

try {
    if (!class_exists('SQLite3')) {
        throw new Exception('SQLite3 non attivo');
    }
    $db = new SQLite3(__DIR__ . '/mac_users.db');
    $db->exec("CREATE TABLE IF NOT EXISTS mac_auth (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        mac_address TEXT NOT NULL,
        portal_slot INTEGER NOT NULL DEFAULT 1,
        username TEXT NOT NULL DEFAULT '',
        password TEXT NOT NULL DEFAULT '',
        status TEXT DEFAULT 'ACTIVE',
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        last_access DATETIME,
        notes TEXT,
        UNIQUE(mac_address, portal_slot)
    )");
    $cols = [];
    $r = $db->query('PRAGMA table_info(mac_auth)');
    while ($c = $r->fetchArray(SQLITE3_ASSOC)) { $cols[] = $c['name']; }
    if (!in_array('portal_slot', $cols)) {
        $db->exec('ALTER TABLE mac_auth ADD COLUMN portal_slot INTEGER NOT NULL DEFAULT 1');
    }

    $mac = '';
    for ($i=0; $i<50; $i++) {
        $candidate = generate_fake_mac_address();
        $stmt = $db->prepare('SELECT COUNT(*) AS c FROM mac_auth WHERE mac_address = ? AND portal_slot = ?');
        $stmt->bindValue(1, $candidate, SQLITE3_TEXT);
        $stmt->bindValue(2, $portal_slot, SQLITE3_INTEGER);
        $row = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
        if (intval($row['c']) === 0) { $mac = $candidate; break; }
    }
    if ($mac === '') { throw new Exception('Impossibile generare MAC'); }
    echo json_encode(['success'=>'1','mac'=>$mac,'portal_slot'=>(string)$portal_slot]);
} catch (Throwable $e) {
    echo json_encode(['success'=>'0','message'=>'Errore generazione MAC']);
}
