<?php
/**
 * Funções para manter consistência entre playlists do mesmo MAC
 * Sub-Revenda version
 */

function getMasterMacData($db, $mac, $reseller) {
    $stmt = $db->prepare("SELECT extra, expire_date, is_test FROM ibo 
                          WHERE mac_address = :mac AND seller = :reseller 
                          ORDER BY id ASC LIMIT 1");
    $stmt->bindValue(':mac', $mac, SQLITE3_TEXT);
    $stmt->bindValue(':reseller', $reseller, SQLITE3_TEXT);
    $result = $stmt->execute();
    return $result->fetchArray(SQLITE3_ASSOC);
}

function syncMacPlaylists($db, $mac, $reseller, $exclude_id = null) {
    $master = getMasterMacData($db, $mac, $reseller);
    if (!$master) return true;
    
    $extra = SQLite3::escapeString($master['extra']);
    $expire = $master['expire_date'];
    $is_test = (int)$master['is_test'];
    
    $sql = "UPDATE ibo SET extra = '$extra', expire_date = '$expire', is_test = $is_test 
            WHERE mac_address = '$mac' AND seller = '$reseller'";
    if ($exclude_id) {
        $sql .= " AND id != " . intval($exclude_id);
    }
    return $db->exec($sql);
}

function expireMacPlaylists($db, $mac, $reseller) {
    $expired_date = date('Y-m-d', strtotime('-1 day'));
    $sql = "UPDATE ibo SET expire_date = '$expired_date', is_test = 0 
            WHERE mac_address = '$mac' AND seller = '$reseller'";
    return $db->exec($sql);
}
?>