<?php
// API Tracking - Mac Tracking & M3U IPTV Management
// Compatible: PHP 7.0+ (including 8.0, 8.1, 8.2, 8.3, 8.4)
// cPanel Ready

declare(strict_types=1);

// Error handling for different PHP versions
if (!function_exists('error_handler')) {
    function error_handler($errno, $errstr, $errfile, $errline) {
        error_log("[$errno] $errstr in $errfile:$errline");
        return true;
    }
    set_error_handler('error_handler');
}

// Include files with error handling
try {
    include(__DIR__ . '/../includes/functions.php');
} catch (Throwable $e) {
    http_response_code(500);
    exit(json_encode(['status' => 'error', 'message' => 'Sistema indisponível']));
}

// Verificar session status antes de iniciar
if (session_status() === PHP_SESSION_NONE) {
    @session_start();
}

header('Content-Type: application/json; charset=utf-8');

// ========== MAC TRACKING ==========
// Função para registrar acesso de clientes Mac - PHP 8.4 Compatible

function trackMacAccess(string $mac_address, array $device_info = []): bool {
    global $db;
    
    try {
        // Criar tabela se não existir
        $createTableSQL = "CREATE TABLE IF NOT EXISTS mac_tracking (
            id INTEGER PRIMARY KEY,
            mac_address TEXT NOT NULL UNIQUE,
            device_name TEXT,
            app_version TEXT,
            last_access TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            access_count INTEGER DEFAULT 1,
            first_access TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            ip_address TEXT,
            status TEXT DEFAULT 'active'
        )";
        
        $db->db->exec($createTableSQL);
        
        // Verificar se MAC já existe
        $existing = $db->select('mac_tracking', '*', 'mac_address = :mac', '', [':mac' => $mac_address]);
        
        if (!empty($existing)) {
            // Atualizar registro existente
            $access_count = intval($existing[0]['access_count'] ?? 0) + 1;
            $updateData = [
                'last_access' => date('Y-m-d H:i:s'),
                'access_count' => $access_count,
                'device_name' => $device_info['device_name'] ?? $existing[0]['device_name'] ?? 'Unknown Device',
                'app_version' => $device_info['app_version'] ?? $existing[0]['app_version'] ?? '1.0',
                'ip_address' => $device_info['ip_address'] ?? $existing[0]['ip_address'] ?? real_ip(),
                'status' => 'active'
            ];
            
            $db->update('mac_tracking', $updateData, 'mac_address = :mac', [':mac' => $mac_address]);
        } else {
            // Inserir novo registro
            $insertData = [
                'mac_address' => $mac_address,
                'device_name' => $device_info['device_name'] ?? 'Unknown Device',
                'app_version' => $device_info['app_version'] ?? '1.0',
                'first_access' => date('Y-m-d H:i:s'),
                'last_access' => date('Y-m-d H:i:s'),
                'access_count' => 1,
                'ip_address' => $device_info['ip_address'] ?? real_ip(),
                'status' => 'active'
            ];
            
            $db->insert('mac_tracking', $insertData);
        }
        
        return true;
    } catch (Throwable $e) {
        error_log("trackMacAccess error: " . $e->getMessage());
        return false;
    }
}

// ========== END MAC TRACKING ==========

// Detectar se é uma requisição de Mac
$mac_address = isset($_GET['mac']) ? sanitize_input($_GET['mac']) : null;

if($mac_address) {
    $device_info = [
        'device_name' => $_GET['device_name'] ?? 'Mac Device',
        'app_version' => $_GET['app_version'] ?? '1.0',
        'ip_address' => real_ip()
    ];
    
    // Register access
    trackMacAccess($mac_address, $device_info);
}

// Função para sanitizar entrada - PHP 8.4 Compatible
function sanitize_input(mixed $input): string {
    if (!is_string($input)) {
        $input = strval($input);
    }
    return htmlspecialchars(strip_tags(trim($input)), ENT_QUOTES, 'UTF-8');
}

// Criar tabela M3U Lists se não existir
function createM3UTable(): bool {
    global $db;
    try {
        $sql = "CREATE TABLE IF NOT EXISTS m3u_lists (
            id INTEGER PRIMARY KEY,
            title TEXT NOT NULL,
            url TEXT NOT NULL,
            dns_primary TEXT DEFAULT '8.8.8.8',
            dns_secondary TEXT DEFAULT '8.8.4.4',
            mac_address TEXT,
            device_name TEXT,
            import_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            status TEXT DEFAULT 'active',
            playlist_count INTEGER DEFAULT 0
        )";
        $db->db->exec($sql);
        return true;
    } catch (Throwable $e) {
        error_log("createM3UTable error: " . $e->getMessage());
        return false;
    }
}

// Adicionar lista M3U via API - PHP 8.4 Compatible
function addM3UList(string $title, string $url, string $mac_address = '', string $device_name = '', 
                    string $dns_primary = '8.8.8.8', string $dns_secondary = '8.8.4.4'): array {
    global $db;
    
    try {
        createM3UTable();
        
        $insertData = [
            'title' => sanitize_input($title),
            'url' => filter_var($url, FILTER_VALIDATE_URL) ? $url : '',
            'dns_primary' => sanitize_input($dns_primary),
            'dns_secondary' => sanitize_input($dns_secondary),
            'mac_address' => sanitize_input($mac_address),
            'device_name' => sanitize_input($device_name),
            'import_date' => date('Y-m-d H:i:s'),
            'status' => 'active'
        ];
        
        if (empty($insertData['title']) || empty($insertData['url'])) {
            return ['status' => 'error', 'message' => 'Título e URL são obrigatórios'];
        }
        
        $db->insert('m3u_lists', $insertData);
        return ['status' => 'success', 'message' => 'Lista M3U adicionada com sucesso', 'id' => $db->getLastInsertId()];
    } catch (Throwable $e) {
        error_log("addM3UList error: " . $e->getMessage());
        return ['status' => 'error', 'message' => 'Erro ao adicionar lista'];
    }
}

// Atualizar DNS em massa - PHP 8.4 Compatible
function bulkUpdateDNS(array $list_ids, string $dns_primary, string $dns_secondary): array {
    global $db;
    
    try {
        createM3UTable();
        
        $dns_primary = sanitize_input($dns_primary);
        $dns_secondary = sanitize_input($dns_secondary);
        
        if (empty($list_ids)) {
            return ['status' => 'error', 'message' => 'Nenhuma lista selecionada'];
        }
        
        $updated_count = 0;
        foreach ($list_ids as $list_id) {
            $list_id = intval($list_id);
            $updateData = [
                'dns_primary' => $dns_primary,
                'dns_secondary' => $dns_secondary,
                'import_date' => date('Y-m-d H:i:s')
            ];
            
            $db->update('m3u_lists', $updateData, 'id = :id', [':id' => $list_id]);
            $updated_count++;
        }
        
        return [
            'status' => 'success', 
            'message' => "DNS atualizado para {$updated_count} lista(s)",
            'count' => $updated_count
        ];
    } catch (Throwable $e) {
        error_log("bulkUpdateDNS error: " . $e->getMessage());
        return ['status' => 'error', 'message' => 'Erro ao atualizar DNS'];
    }
}

// Get DNS and API data
$res = $db->select('dns', '*', '', '');   
$sp_api = $db->select('spapi', '*', 'id = :id', '', [':id' => 1]);
$ctheme = $db->select('themes', '*', 'id = :id', '', [':id' => 1]);
$int = $db->select('int', '*', 'id = :id', '', [':id' => 1]);
$nammes = $db->select('name', '*', 'id = :id', '', [':id' => 1]);

// Get M3U lists if they exist
$m3u_lists = [];
try {
    $m3u_lists = $db->select('m3u_lists', '*', 'status = :status', '', [':status' => 'active']);
} catch (Exception $e) {
    // M3U table doesn't exist, that's fine
}

$keysp = !empty($sp_api[0]['apikey']) ? $sp_api[0]['apikey'] : '492939';
$colortheme = !empty($ctheme[0]['themeid']) ? $ctheme[0]['themeid'] : '0';
$intro = !empty($int[0]['intro']) ? $int[0]['intro'] : 'enable';
$fullname = !empty($nammes[0]['fname']) ? $nammes[0]['fname'] : 'IPTV Rebrand';
$partone = !empty($nammes[0]['parto']) ? $nammes[0]['parto'] : 'IPTV ';
$parttow = !empty($nammes[0]['partt']) ? $nammes[0]['partt'] : 'Rebrand';

$rowsJson = array();      
$idCounter = 1; 

// Add DNS portals
foreach ($res as $row) {      
    $row_array = array(
        'id' => $idCounter++,  
        'name' => $row['title'],    
        'url' => $row['url'],
        'type' => 'dns'
    );
    $rowsJson[] = $row_array;    
}

// Add M3U lists
foreach ($m3u_lists as $m3u) {
    $row_array = array(
        'id' => $idCounter++,
        'name' => $m3u['title'],
        'url' => $m3u['url'],
        'type' => 'm3u',
        'playlist_count' => $m3u['playlist_count'],
        'dns_id' => $m3u['dns_id']
    );
    $rowsJson[] = $row_array;
}

function generateSingleNumberWithSum45() {
    $numbers = [];
    $targetSum = 45;
    $currentSum = 0;
    
    while ($currentSum < $targetSum) {
        $remaining = $targetSum - $currentSum;
        if ($remaining > 9) {
            $num = rand(0, 9);
        } else {
            $num = $remaining;
        }
        
        $numbers[] = $num;
        $currentSum += $num;
    }
    
    if (array_sum($numbers) == 45) {
        $letterMap = [
            9 => 'a',
            8 => 'b',
            7 => 'c',
            6 => 'd',
            5 => 'e',
            4 => 'f',
            3 => 'g',
            2 => 'h',
            1 => 'i',
            0 => 'j'
        ];
        
        $letterSequence = '';
        foreach ($numbers as $num) {
            $letterSequence .= $letterMap[$num];
        }
        
        return $letterSequence;
    } else {
        return generateSingleNumberWithSum45();
    }
}

function insertRandomLettersIntoText($originalText) {
    $letterSequence = generateSingleNumberWithSum45();
    $textArray = str_split($originalText);
    $textLength = strlen($originalText);
    
    $letterArray = str_split($letterSequence);
    $letterCount = count($letterArray);
    
    $randomIndexes = [];
    while (count($randomIndexes) < $letterCount) {
        $index = rand(0, $textLength);
        if (!in_array($index, $randomIndexes)) {
            $randomIndexes[] = $index;
        }
    }
    sort($randomIndexes); 
    
    $resultArray = $textArray;
    $offset = 0;
    foreach ($randomIndexes as $i => $index) {
        array_splice($resultArray, $index + $offset, 0, $letterArray[$i]);
        $offset++; 
    }
    
    return implode('', $resultArray);
}

function generateStrictRandomString($length = 50) {
    $excluded = str_split('ABCDEFGHIJabcdefghij');
    $allCharacters = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789');
    $allowedCharacters = array_diff($allCharacters, $excluded);
    $characters = implode('', $allowedCharacters);
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[random_int(0, $charactersLength - 1)];
    }
    return $randomString;
}

function extractLettersWithSum45($inputString) {
    $letterMap = [
        'a' => 9,
        'b' => 8,
        'c' => 7,
        'd' => 6,
        'e' => 5,
        'f' => 4,
        'g' => 3,
        'h' => 2,
        'i' => 1,
        'j' => 0
    ];
    
    $extractedLetters = '';
    $sum = 0;
    
    foreach (str_split($inputString) as $char) {
        $charLower = strtolower($char);
        if (array_key_exists($charLower, $letterMap)) {
            $extractedLetters .= $charLower;
            $sum += $letterMap[$charLower];
        }
    }
    
    if ($sum == 45) {
        return $sum;
    } else {
        return "Error: Extracted letters do not sum to 45. Sum is $sum.";
    }
}

$randomtext = generateStrictRandomString();
$finalText = insertRandomLettersIntoText($randomtext);
$text45 = extractLettersWithSum45($finalText);

header('Content-Type: application/json');

// Build response
$response = [
    'uuid' => $finalText,
    'portals' => $rowsJson,
    'intro' => $intro,
    'themes' => $colortheme,
    'textlogoo' => $partone,
    'textlogot' => $parttow,
    'appname' => $fullname,
    'sport_api' => $keysp,
    'total_items' => count($rowsJson),
    'dns_count' => count($res),
    'm3u_count' => count($m3u_lists)
];

// Add tracking info if Mac address was provided
if($mac_address) {
    $response['tracking'] = [
        'status' => 'registered',
        'message' => 'Dispositivo Mac registrado com sucesso no painel de rastreamento',
        'timestamp' => date('Y-m-d H:i:s')
    ];
}

$finalgood = json_encode($response);

echo $finalgood;
?>
