<?php
$db_file = 'api/mac_users.db';

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() {
    // Formato compatibile con questa app: 4 blocchi (AA:BB:CC:DD)
    // Prefisso locale/amministrato per evitare MAC reali di produttori.
    $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]));
}

function mac_exists_for_portal($db, $mac, $portal_slot) {
    $stmt = $db->prepare('SELECT COUNT(*) FROM mac_auth WHERE mac_address = ? AND portal_slot = ?');
    $stmt->bindValue(1, $mac, SQLITE3_TEXT);
    $stmt->bindValue(2, $portal_slot, SQLITE3_INTEGER);
    return intval($stmt->execute()->fetchArray(SQLITE3_NUM)[0]) > 0;
}

function generate_unique_fake_mac($db, $portal_slot) {
    for ($i = 0; $i < 50; $i++) {
        $mac = generate_fake_mac_address();
        if (!mac_exists_for_portal($db, $mac, $portal_slot)) {
            return $mac;
        }
    }
    return '';
}

function load_portals() {
    $portals = [];
    $main_json = @file_get_contents('api/main.json');
    $main_data = json_decode($main_json, true);
    $app = isset($main_data['app']) && is_array($main_data['app']) ? $main_data['app'] : [];

    for ($i = 1; $i <= 5; $i++) {
        $portal_key = $i === 1 ? 'portal' : 'portal' . $i;
        $name_key   = $i === 1 ? 'portal_name' : 'portal' . $i . '_name';
        $url = isset($app[$portal_key]) ? trim((string)$app[$portal_key]) : '';
        $name = isset($app[$name_key]) ? trim((string)$app[$name_key]) : '';

        if ($name === '' || $name === '0') {
            $name = 'Portale ' . $i;
        }

        $portals[$i] = [
            'slot' => $i,
            'name' => $name,
            'url'  => $url,
            'active' => ($url !== '' && $url !== '0')
        ];
    }

    return $portals;
}

function ensure_mac_schema($db) {
    $exists = $db->querySingle("SELECT name FROM sqlite_master WHERE type='table' AND name='mac_auth'");
    if (!$exists) {
        $db->exec("CREATE TABLE mac_auth (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            mac_address TEXT NOT NULL,
            portal_slot INTEGER NOT NULL DEFAULT 1,
            username TEXT NOT NULL,
            password TEXT NOT NULL,
            status TEXT DEFAULT 'ACTIVE',
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            last_access DATETIME,
            notes TEXT,
            UNIQUE(mac_address, portal_slot)
        )");
        $db->exec("CREATE INDEX IF NOT EXISTS idx_mac_auth_mac ON mac_auth(mac_address)");
        $db->exec("CREATE INDEX IF NOT EXISTS idx_mac_auth_status ON mac_auth(status)");
        $db->exec("CREATE INDEX IF NOT EXISTS idx_mac_auth_portal_slot ON mac_auth(portal_slot)");
        return;
    }

    $columns = [];
    $res = $db->query("PRAGMA table_info(mac_auth)");
    while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
        $columns[] = $row['name'];
    }

    if (!in_array('portal_slot', $columns)) {
        $db->exec('ALTER TABLE mac_auth ADD COLUMN portal_slot INTEGER NOT NULL DEFAULT 1');
    }

    $create = $db->querySingle("SELECT sql FROM sqlite_master WHERE type='table' AND name='mac_auth'");
    if (stripos((string)$create, 'mac_address TEXT UNIQUE') !== false || stripos((string)$create, 'UNIQUE(mac_address, portal_slot)') === false) {
        $db->exec('BEGIN TRANSACTION');
        $db->exec('ALTER TABLE mac_auth RENAME TO mac_auth_old');
        $db->exec("CREATE TABLE mac_auth (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            mac_address TEXT NOT NULL,
            portal_slot INTEGER NOT NULL DEFAULT 1,
            username TEXT NOT NULL,
            password TEXT NOT NULL,
            status TEXT DEFAULT 'ACTIVE',
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            last_access DATETIME,
            notes TEXT,
            UNIQUE(mac_address, portal_slot)
        )");
        $db->exec("INSERT OR IGNORE INTO mac_auth (id, mac_address, portal_slot, username, password, status, created_at, last_access, notes)
                   SELECT id, mac_address, COALESCE(portal_slot, 1), username, password, COALESCE(status, 'ACTIVE'), created_at, last_access, notes
                   FROM mac_auth_old");
        $db->exec('DROP TABLE mac_auth_old');
        $db->exec('COMMIT');
    }

    $db->exec("CREATE INDEX IF NOT EXISTS idx_mac_auth_mac ON mac_auth(mac_address)");
    $db->exec("CREATE INDEX IF NOT EXISTS idx_mac_auth_status ON mac_auth(status)");
    $db->exec("CREATE INDEX IF NOT EXISTS idx_mac_auth_portal_slot ON mac_auth(portal_slot)");
}

$portals = load_portals();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $db = new SQLite3($db_file);
    ensure_mac_schema($db);

    if (isset($_POST['action'])) {
        if ($_POST['action'] == 'add') {
            $mac = normalize_mac_address(isset($_POST['mac_address']) ? $_POST['mac_address'] : '');
            $portal_slot = isset($_POST['portal_slot']) ? max(1, min(5, intval($_POST['portal_slot']))) : 1;
            if ($mac === '' && isset($_POST['auto_generate_mac'])) {
                $mac = generate_unique_fake_mac($db, $portal_slot);
            }
            $username = trim($_POST['username']);
            $password = trim($_POST['password']);
            $notes = trim($_POST['notes']);

            if ($mac === '') {
                $error = 'MAC address non valido. Usa formato AA:BB:CC:DD';
            } else {
                $stmt = $db->prepare('INSERT INTO mac_auth (mac_address, portal_slot, username, password, notes, status) VALUES (?, ?, ?, ?, ?, "ACTIVE")');
                $stmt->bindValue(1, $mac, SQLITE3_TEXT);
                $stmt->bindValue(2, $portal_slot, SQLITE3_INTEGER);
                $stmt->bindValue(3, $username, SQLITE3_TEXT);
                $stmt->bindValue(4, $password, SQLITE3_TEXT);
                $stmt->bindValue(5, $notes, SQLITE3_TEXT);

                try {
                    $stmt->execute();
                    $success = 'Servizio aggiunto al ' . $portals[$portal_slot]['name'] . ' con MAC ' . $mac . ' correttamente!';
                } catch (Exception $e) {
                    $error = 'Questo MAC esiste già su questo portale. Puoi usare lo stesso MAC scegliendo un portale diverso.';
                }
            }
        }

        if ($_POST['action'] == 'delete') {
            $id = intval($_POST['id']);
            $stmt = $db->prepare('DELETE FROM mac_auth WHERE id = ?');
            $stmt->bindValue(1, $id, SQLITE3_INTEGER);
            $stmt->execute();
            $success = 'MAC eliminato!';
        }

        if ($_POST['action'] == 'toggle') {
            $id = intval($_POST['id']);
            $status = $_POST['status'] == 'ACTIVE' ? 'INACTIVE' : 'ACTIVE';
            $stmt = $db->prepare('UPDATE mac_auth SET status = ? WHERE id = ?');
            $stmt->bindValue(1, $status, SQLITE3_TEXT);
            $stmt->bindValue(2, $id, SQLITE3_INTEGER);
            $stmt->execute();
            $success = 'Stato aggiornato!';
        }

        if ($_POST['action'] == 'edit') {
            $id = intval($_POST['id']);
            $portal_slot = isset($_POST['portal_slot']) ? max(1, min(5, intval($_POST['portal_slot']))) : 1;
            $username = trim($_POST['username']);
            $password = trim($_POST['password']);
            $notes = trim($_POST['notes']);

            $stmt = $db->prepare('UPDATE mac_auth SET portal_slot = ?, username = ?, password = ?, notes = ? WHERE id = ?');
            $stmt->bindValue(1, $portal_slot, SQLITE3_INTEGER);
            $stmt->bindValue(2, $username, SQLITE3_TEXT);
            $stmt->bindValue(3, $password, SQLITE3_TEXT);
            $stmt->bindValue(4, $notes, SQLITE3_TEXT);
            $stmt->bindValue(5, $id, SQLITE3_INTEGER);

            try {
                $stmt->execute();
                $success = 'MAC aggiornato!';
            } catch (Exception $e) {
                $error = 'Impossibile aggiornare: esiste già lo stesso MAC su questo portale.';
            }
        }
    }

    $db->close();
}

$db = new SQLite3($db_file);
ensure_mac_schema($db);
$result = $db->query('SELECT * FROM mac_auth ORDER BY created_at DESC, id DESC');
$mac_list = [];
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    if (!isset($row['portal_slot']) || intval($row['portal_slot']) < 1) {
        $row['portal_slot'] = 1;
    }
    $mac_list[] = $row;
}
$install_list = [];
$db->exec("CREATE TABLE IF NOT EXISTS mac_installations (id INTEGER PRIMARY KEY AUTOINCREMENT, install_key TEXT NOT NULL UNIQUE, mac_address TEXT NOT NULL UNIQUE, userid TEXT, did TEXT, appid TEXT, package_name TEXT, app_name TEXT, device_type TEXT, ip_address TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, last_seen DATETIME DEFAULT CURRENT_TIMESTAMP)");
$inst = $db->query('SELECT * FROM mac_installations ORDER BY last_seen DESC, id DESC LIMIT 200');
if ($inst) { while ($r = $inst->fetchArray(SQLITE3_ASSOC)) { $install_list[] = $r; } }
$db->close();

include 'includes/header.php';
?>

<style>
div.dataTables_length label, div.dataTables_length select, div.dataTables_filter label, #table_id_info { color: #fff; }
div.dataTables_length select option { background: #000; }
#table_id tbody tr { background-color: #000 !important; color: #fff !important; }
#table_id.table-striped tbody tr:nth-of-type(odd), #table_id.table-striped tbody tr:nth-of-type(even) { background-color: #000 !important; }
#table_id td, #table_id th { color: #fff !important; vertical-align: middle; }
#table_id tbody tr:hover { background-color: #111 !important; }
.portal-badge { display:inline-block; padding:4px 8px; border-radius:8px; background:#222; color:#fff; font-weight:bold; }
</style>

<div class="col-md-12 mx-auto">
    <div class="card-body">
        <div class="card bg-primary text-white">
            <div class="card-header card-header-warning text-center">
                <h2><i class="fa fa-mobile"></i> MAC Address Management Multi-Portale</h2>
            </div>
            <div class="card-body">
                <div class="col-12 text-center">
                    <h4 class="h4 mb-1 text-gray-800"><strong>Portali disponibili:</strong></h4>
                    <?php foreach ($portals as $p): ?>
                        <div><?php echo htmlspecialchars($p['name']); ?>: <?php echo htmlspecialchars($p['url']); ?> <?php echo $p['active'] ? '' : '<strong>(non configurato)</strong>'; ?></div>
                    <?php endforeach; ?>
                    <small>Ora puoi usare lo stesso MAC su portali diversi oppure generare un MAC fittizio nuovo per ogni servizio.</small>
                    <hr>
                </div>

                <?php if (isset($success)): ?><div class="alert alert-success text-center"><?php echo htmlspecialchars($success); ?></div><?php endif; ?>
                <?php if (isset($error)): ?><div class="alert alert-danger text-center"><?php echo htmlspecialchars($error); ?></div><?php endif; ?>

                <div class="col-12">
                    <div class="panel panel-primary">
                        <div class="panel-heading"><h3 class="panel-title"><i class="fa fa-plus"></i> Aggiungi nuovo MAC / Servizio</h3></div>
                        <div class="panel-body">
                            <form method="POST">
                                <input type="hidden" name="action" value="add">
                                <div class="row">
                                    <div class="col-md-2">
                                        <div class="form-group">
                                            <label>Portale *</label>
                                            <select name="portal_slot" class="form-control" required>
                                                <?php foreach ($portals as $slot => $p): ?>
                                                    <option value="<?php echo $slot; ?>"><?php echo htmlspecialchars($p['name']); ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>MAC Address / Nuovo MAC fittizio</label>
                                            <div class="input-group">
                                                <input type="text" name="mac_address" id="mac_address" class="form-control" placeholder="AA:BB:CC:DD" maxlength="11" pattern="[A-Fa-f0-9]{2}(:[A-Fa-f0-9]{2}){3}">
                                                <span class="input-group-btn"><button type="button" class="btn btn-info" onclick="generateMacInPanel()">Genera</button></span>
                                            </div>
                                            <label style="margin-top:6px;font-size:12px"><input type="checkbox" name="auto_generate_mac" value="1" checked> genera automaticamente se vuoto</label>
                                            <small>Ogni portale può avere un MAC fittizio diverso.</small>
                                        </div>
                                    </div>
                                    <div class="col-md-2"><div class="form-group"><label>Username *</label><input type="text" name="username" class="form-control" required></div></div>
                                    <div class="col-md-2"><div class="form-group"><label>Password *</label><input type="text" name="password" class="form-control" required></div></div>
                                    <div class="col-md-2"><div class="form-group"><label>Note</label><input type="text" name="notes" class="form-control" placeholder="Nome cliente / servizio"></div></div>
                                    <div class="col-md-1"><div class="form-group"><label>&nbsp;</label><button type="submit" class="btn btn-success btn-block">Add</button></div></div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>


                <div class="alert alert-info" style="background:#111;color:#fff;border-color:#555">
                    <strong>MAC per ogni app installata:</strong> attivo. Ogni installazione può ricevere un MAC diverso tramite API
                    <code>api/ApiIPTV.php?tag=getInstallMac</code> oppure <code>auto_install_mac=1</code>.
                </div>

                <?php if (!empty($install_list)): ?>
                <div class="table-responsive" style="margin-bottom:20px">
                    <h4>App installate con MAC unico</h4>
                    <table class="table table-striped table-bordered" style="background:#000;color:#fff">
                        <thead><tr><th>ID</th><th>MAC assegnato</th><th>UserID</th><th>Device ID</th><th>App</th><th>Pacchetto</th><th>Ultima vista</th></tr></thead>
                        <tbody>
                        <?php foreach ($install_list as $inst): ?>
                            <tr>
                                <td><?php echo intval($inst['id']); ?></td>
                                <td><strong><?php echo htmlspecialchars($inst['mac_address']); ?></strong></td>
                                <td><?php echo htmlspecialchars($inst['userid']); ?></td>
                                <td><?php echo htmlspecialchars($inst['did']); ?></td>
                                <td><?php echo htmlspecialchars($inst['app_name']); ?></td>
                                <td><?php echo htmlspecialchars($inst['package_name']); ?></td>
                                <td><?php echo htmlspecialchars($inst['last_seen']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>

                <div class="table-responsive">
                    <table id="table_id" class="table table-striped table-bordered">
                        <thead>
                            <tr>
                                <th>ID</th><th>MAC</th><th>Portale</th><th>Username</th><th>Password</th><th>Stato</th><th>Ultimo accesso</th><th>Note</th><th>Azioni</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($mac_list as $mac): $slot = intval($mac['portal_slot']); if ($slot < 1 || $slot > 5) { $slot = 1; } ?>
                            <tr>
                                <td><?php echo intval($mac['id']); ?></td>
                                <td><strong><?php echo htmlspecialchars($mac['mac_address']); ?></strong></td>
                                <td><span class="portal-badge"><?php echo htmlspecialchars($portals[$slot]['name']); ?></span></td>
                                <td><?php echo htmlspecialchars($mac['username']); ?></td>
                                <td>
                                    <span id="pass-hidden-<?php echo intval($mac['id']); ?>">••••••••</span>
                                    <span id="pass-visible-<?php echo intval($mac['id']); ?>" style="display:none"><?php echo htmlspecialchars($mac['password']); ?></span>
                                    <button class="btn btn-sm btn-info" onclick="togglePassword(<?php echo intval($mac['id']); ?>)"><i class="fa fa-eye"></i></button>
                                </td>
                                <td><?php echo htmlspecialchars($mac['status']); ?></td>
                                <td><?php echo htmlspecialchars($mac['last_access']); ?></td>
                                <td><?php echo htmlspecialchars($mac['notes']); ?></td>
                                <td>
                                    <button class="btn btn-sm btn-warning" onclick='editMAC(<?php echo json_encode($mac, JSON_HEX_APOS | JSON_HEX_QUOT); ?>)'>Edit</button>
                                    <button class="btn btn-sm btn-info" onclick='copyMACToNewService(<?php echo json_encode($mac, JSON_HEX_APOS | JSON_HEX_QUOT); ?>)'>Nuovo servizio</button>
                                    <form method="POST" style="display:inline">
                                        <input type="hidden" name="action" value="toggle"><input type="hidden" name="id" value="<?php echo intval($mac['id']); ?>"><input type="hidden" name="status" value="<?php echo htmlspecialchars($mac['status']); ?>">
                                        <button type="submit" class="btn btn-sm btn-secondary"><?php echo $mac['status'] == 'ACTIVE' ? 'Disattiva' : 'Attiva'; ?></button>
                                    </form>
                                    <form method="POST" style="display:inline" onsubmit="return confirm('Eliminare questo MAC?')">
                                        <input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?php echo intval($mac['id']); ?>">
                                        <button type="submit" class="btn btn-sm btn-danger">Delete</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="editModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content bg-dark text-white">
            <form method="POST">
                <div class="modal-header"><h5 class="modal-title">Modifica MAC</h5><button type="button" class="close text-white" data-dismiss="modal">&times;</button></div>
                <div class="modal-body">
                    <input type="hidden" name="action" value="edit"><input type="hidden" name="id" id="edit_id">
                    <div class="form-group"><label>MAC</label><input type="text" id="edit_mac" class="form-control" readonly></div>
                    <div class="form-group"><label>Portale</label><select name="portal_slot" id="edit_portal_slot" class="form-control"><?php foreach ($portals as $slot => $p): ?><option value="<?php echo $slot; ?>"><?php echo htmlspecialchars($p['name']); ?></option><?php endforeach; ?></select></div>
                    <div class="form-group"><label>Username</label><input type="text" name="username" id="edit_username" class="form-control" required></div>
                    <div class="form-group"><label>Password</label><input type="text" name="password" id="edit_password" class="form-control" required></div>
                    <div class="form-group"><label>Note</label><input type="text" name="notes" id="edit_notes" class="form-control"></div>
                </div>
                <div class="modal-footer"><button type="submit" class="btn btn-success">Salva</button><button type="button" class="btn btn-secondary" data-dismiss="modal">Annulla</button></div>
            </form>
        </div>
    </div>
</div>

<?php include ('includes/footer.php'); ?>

<script>
function togglePassword(id) {
    var hidden = document.getElementById('pass-hidden-' + id);
    var visible = document.getElementById('pass-visible-' + id);
    if (hidden.style.display === 'none') { hidden.style.display = 'inline'; visible.style.display = 'none'; } else { hidden.style.display = 'none'; visible.style.display = 'inline'; }
}
function editMAC(mac) {
    $('#edit_id').val(mac.id);
    $('#edit_mac').val(mac.mac_address);
    $('#edit_portal_slot').val(mac.portal_slot || 1);
    $('#edit_username').val(mac.username);
    $('#edit_password').val(mac.password);
    $('#edit_notes').val(mac.notes);
    $('#editModal').modal('show');
}

function randomHexByte() {
    return Math.floor(Math.random() * 256).toString(16).padStart(2, '0').toUpperCase();
}
function generateFakeMac4() {
    return ['02', randomHexByte(), randomHexByte(), randomHexByte()].join(':');
}
function generateMacInPanel() {
    var input = document.getElementById('mac_address');
    if (input) { input.value = generateFakeMac4(); }
}
function copyMACToNewService(mac) {
    var macInput = document.getElementById('mac_address');
    var userInput = document.querySelector('input[name="username"]');
    var passInput = document.querySelector('input[name="password"]');
    var notesInput = document.querySelector('input[name="notes"]');
    if (macInput) { macInput.value = generateFakeMac4(); }
    if (userInput) { userInput.value = mac.username || ''; }
    if (passInput) { passInput.value = mac.password || ''; }
    if (notesInput) { notesInput.value = 'Nuovo servizio da MAC ' + (mac.mac_address || ''); }
    window.scrollTo({top: 0, behavior: 'smooth'});
}
var macInput = document.getElementById('mac_address');
if (macInput) {
    macInput.addEventListener('input', function(e) {
        let value = e.target.value.replace(/[^A-Fa-f0-9]/g, '').toUpperCase();
        value = value.match(/.{1,2}/g)?.join(':') || '';
        value = value.substring(0, 11);
        e.target.value = value;
    });
}
$(document).ready(function () { $('#table_id').DataTable({ "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]], "filter": true, "paging": true, "ordering": false }); });
</script>
</body>
</html>
