<?php
if (session_status() === PHP_SESSION_NONE) session_start();

if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: index.php");
    exit;
}

function cfg() { 
    static $c=null; 
    if($c===null) { $c=require __DIR__.'/config.php'; } 
    return $c; 
}

function checkAuth() {
    $cfg = cfg();
    $ip = $_SERVER['REMOTE_ADDR'];
    $authFile = __DIR__ . '/data/auth.json';
    if (!is_dir(__DIR__ . '/data')) mkdir(__DIR__ . '/data', 0777, true);
    
    $authDb = file_exists($authFile) ? json_decode(file_get_contents($authFile), true) : [];
    
    if (isset($authDb[$ip]) && isset($authDb[$ip]['locked_until']) && $authDb[$ip]['locked_until'] < time()) {
        unset($authDb[$ip]);
        file_put_contents($authFile, json_encode($authDb));
    }

    if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
        session_write_close(); 
        return;
    }
    
    $isLocked = isset($authDb[$ip]['locked_until']) && $authDb[$ip]['locked_until'] > time();
    $lockTimeLeft = $isLocked ? ceil(($authDb[$ip]['locked_until'] - time()) / 60) : 0;
    
    if (isset($_POST['pin'])) {
        if ($isLocked) {
            $error = "Zbyt wiele prób! Spróbuj ponownie za $lockTimeLeft min.";
        } else {
            $pin = (string)$_POST['pin'];
            $isUser = in_array($pin, $cfg['pins'] ?? []);
            $isAdmin = in_array($pin, $cfg['admin_pins'] ?? []);
            
            if ($isUser || $isAdmin) {
                $_SESSION['logged_in'] = true;
                $_SESSION['role'] = $isAdmin ? 'admin' : 'user';
                
                // Twarde ciasteczko z PINEM na potrzeby zapisywania czasu wideo (ważne rok)
                setcookie('user_pin', $pin, time() + 31536000, '/');
                
                unset($authDb[$ip]);
                file_put_contents($authFile, json_encode($authDb));
                header("Location: " . $_SERVER['REQUEST_URI']);
                exit;
            } else {
                $authDb[$ip]['attempts'] = ($authDb[$ip]['attempts'] ?? 0) + 1;
                if ($authDb[$ip]['attempts'] >= 5) {
                    $authDb[$ip]['locked_until'] = time() + 900; 
                }
                file_put_contents($authFile, json_encode($authDb));
                $error = "Nieprawidłowy PIN!";
                $isLocked = isset($authDb[$ip]['locked_until']);
            }
        }
    }
    
    echo "<!doctype html><html lang='pl'><head><meta charset='utf-8'><title>Logowanie</title><link rel='stylesheet' href='assets/style.css'></head>";
    echo "<body class='pin-body'><div class='pin-box'><h2>🔒 Autoryzacja</h2>";
    if (isset($error)) echo "<p style='color:#ff4d4d; margin-bottom:15px;'>$error</p>";
    if ($isLocked) {
        echo "<p style='color:#ffc107;'>Dostęp zablokowany. Odczekaj czas kary.</p>";
    } else {
        echo "<form method='post'><input type='password' name='pin' pattern='[0-9]{4}' placeholder='****' maxlength='4' autofocus><br><button type='submit' class='btn btn-blue'>Odblokuj</button></form>";
    }
    echo "</div></body></html>";
    exit;
}

function sanitizePath($path) {
    $parts = explode('/', $path);
    $safe = [];
    foreach ($parts as $p) {
        if ($p === '' || $p === '.' || $p === '..') continue;
        $safe[] = $p;
    }
    return implode('/', $safe);
}

function formatSize($bytes) {
    if ($bytes === 0) return '0 B';
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $pow = floor(log($bytes) / log(1024));
    $pow = min($pow, count($units) - 1);
    return round($bytes / pow(1024, $pow), 2) . ' ' . $units[$pow];
}

function getDbPath() {
    $dir = __DIR__ . '/data';
    if (!is_dir($dir)) mkdir($dir, 0777, true); 
    return $dir . '/db.json';
}

function getDb() {
    $file = getDbPath();
    if(!file_exists($file)) return ['downloads'=>[], 'shares'=>[]];
    $db = json_decode(file_get_contents($file), true) ?: ['downloads'=>[], 'shares'=>[]];
    
    $changed = false;
    $now = time();

    // ŚMIECIARKA 1: Kasowanie wygasłych linków 24H
    if(isset($db['shares'])) {
        foreach($db['shares'] as $hash => $data) {
            if($now > $data['expires']) { unset($db['shares'][$hash]); $changed = true; }
        }
    }
    if($changed) file_put_contents($file, json_encode($db, JSON_PRETTY_PRINT), LOCK_EX);

    // ŚMIECIARKA 2: Kasowanie starych śmieci z yt_temp (starsze niż 30 min)
    $tempDir = __DIR__ . '/data/yt_temp';
    if (is_dir($tempDir)) {
        foreach(glob($tempDir . '/*') as $f) {
            if($now - filemtime($f) > 1800) { is_dir($f) ? @exec("rm -rf " . escapeshellarg($f)) : @unlink($f); }
        }
    }

    // ŚMIECIARKA 3: Kasowanie niepotrzebnych miniaturek sprite-sheet (starsze niż 24h)
    $thumbDir = __DIR__ . '/data/thumbnails';
    if (is_dir($thumbDir)) {
        foreach(glob($thumbDir . '/*.jpg') as $f) {
            if($now - filemtime($f) > 86400) { @unlink($f); }
        }
    }

    return $db;
}

function saveDb($data) {
    file_put_contents(getDbPath(), json_encode($data, JSON_PRETTY_PRINT), LOCK_EX);
}

function recordDownload($megaPath) {
    $db = getDb();
    $db['downloads'][$megaPath] = ($db['downloads'][$megaPath] ?? 0) + 1;
    saveDb($db);
}

function listMegaFolder($basePath, $subPath = '', $sort = 'name_asc') {
    $fullPath = rtrim('/mnt/mega' . $basePath . '/' . $subPath, '/');
    $items = ['folders' => [], 'files' => []];
    $db = getDb();
    
    if (is_dir($fullPath)) {
        $files = scandir($fullPath);
        foreach ($files as $file) {
            if ($file === '.' || $file === '..') continue;
            if (strpos($file, '.') === 0) continue; 
            
            $physicalPath = $fullPath . '/' . $file;
            $megaPath = rtrim($basePath . '/' . $subPath, '/') . '/' . $file;
            $stat = stat($physicalPath);
            
            $itemData = [
                'name' => $file,
                'ext' => strtolower(pathinfo($file, PATHINFO_EXTENSION)),
                'size' => $stat ? formatSize($stat['size']) : '-',
                'bytes' => $stat ? $stat['size'] : 0,
                'date' => $stat ? date('d.m.Y H:i', $stat['mtime']) : '-',
                'timestamp' => $stat ? $stat['mtime'] : 0,
                'downloads' => $db['downloads'][$megaPath] ?? 0
            ];
            
            if (is_dir($physicalPath)) $items['folders'][] = $itemData;
            else $items['files'][] = $itemData;
        }
    }

    $sortFunc = function($key, $dir, $isNumeric = false) {
        return function($a, $b) use ($key, $dir, $isNumeric) {
            if ($isNumeric) {
                $valA = $a[$key];
                $valB = $b[$key];
            } else {
                $valA = mb_strtolower($a[$key], 'UTF-8');
                $valB = mb_strtolower($b[$key], 'UTF-8');
            }
            if ($valA == $valB) return 0;
            $res = ($valA < $valB) ? -1 : 1;
            return $dir === 'asc' ? $res : -$res;
        };
    };

    switch($sort) {
        case 'name_desc': usort($items['folders'], $sortFunc('name', 'desc')); usort($items['files'], $sortFunc('name', 'desc')); break;
        case 'type_asc': usort($items['folders'], $sortFunc('name', 'asc')); usort($items['files'], $sortFunc('ext', 'asc')); break;
        case 'type_desc': usort($items['folders'], $sortFunc('name', 'asc')); usort($items['files'], $sortFunc('ext', 'desc')); break;
        case 'date_asc': usort($items['folders'], $sortFunc('timestamp', 'asc', true)); usort($items['files'], $sortFunc('timestamp', 'asc', true)); break;
        case 'date_desc': usort($items['folders'], $sortFunc('timestamp', 'desc', true)); usort($items['files'], $sortFunc('timestamp', 'desc', true)); break;
        case 'size_asc': usort($items['folders'], $sortFunc('name', 'asc')); usort($items['files'], $sortFunc('bytes', 'asc', true)); break;
        case 'size_desc': usort($items['folders'], $sortFunc('name', 'asc')); usort($items['files'], $sortFunc('bytes', 'desc', true)); break;
        case 'name_asc': default: usort($items['folders'], $sortFunc('name', 'asc')); usort($items['files'], $sortFunc('name', 'asc')); break;
    }
    return $items;
}

function searchAllMegaFolders($query) {
    $cfg = cfg(); $results = []; $query = mb_strtolower($query, 'UTF-8');
    foreach ($cfg['allowedFolders'] as $folderKey => $basePath) { scanDirRecursive('/mnt/mega' . $basePath, $folderKey, '', $query, $results); }
    return $results;
}

function scanDirRecursive($physicalBasePath, $folderKey, $currentSubPath, $query, &$results) {
    $dirToScan = rtrim($physicalBasePath . '/' . $currentSubPath, '/');
    if (!is_dir($dirToScan)) return;
    $items = scandir($dirToScan);
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        if (strpos($item, '.') === 0) continue; 
        $itemPath = ltrim($currentSubPath . '/' . $item, '/');
        if (mb_strpos(mb_strtolower($item, 'UTF-8'), $query) !== false) {
            $results[] = ['name' => $item, 'folder' => $folderKey, 'path' => $currentSubPath, 'is_dir' => is_dir($dirToScan . '/' . $item)];
        }
        if (is_dir($dirToScan . '/' . $item)) scanDirRecursive($physicalBasePath, $folderKey, $itemPath, $query, $results);
    }
}
