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

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

function syncMacPlaylists($db, $mac, $seller, $exclude_id = null) {
    $master = getMasterMacData($db, $mac, $seller);
    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 = '$seller'";
    if ($exclude_id) {
        $sql .= " AND id != " . intval($exclude_id);
    }
    return $db->exec($sql);
}

function expireMacPlaylists($db, $mac, $seller) {
    $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 = '$seller'";
    return $db->exec($sql);
}
?>