Laptop Ministry

Open Source Software & Tools Repository

pagetelegram's Repository

Title: Laptop Ministry Founder

Description: Creator of the Laptop Ministry, in Uptown / Edgewater Chicago.

................................................................................
................................................................................
..............................:-=+*#%%%%##*+-:..................................
...........................:+#%@@@@@@@@@@@@@@@%*-...............................
.........................-#@@@@@@@@@@@@@@@@@@@@@@%+:............................
.......................=%@@@@@@@@@@@@@@@@@@@@@@@@@@@+:..........................
.....................:#@@@@@@@@@%*=-::.::=+#@@@@@@@@@%=.........................
....................=%@@@@@@@@#=:...........:+%@@@@@@@@*:.......................
...................+@@@@@@@@#-................:+@@@@@@@@#:......................
..................+@@@@@@@@+:...................-%@@@@@@@%:.....................
.................+@@@@@@@%=......................:#@@@@@@@#:....................
................=%@@@@@@@=........................:#@@@@@@@*....................
...............:#@@@@@@@+..........................-%@@@@@@@=...................
...............+@@@@@@@#........:::-------:::.......=@@@@@@@#:..................
..............:#@@@@@@@-.:-=*#%%@@@@@@@@@@@@@%%#*=-.:#@@@@@@%=..................
..............=@@@@@@@@#%@@@@@@@@@@@@@@@@@@@@@@@@@@@%%@@@@@@@*..................
..............+@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#:.................
.............:*@@@@@@@@@@@@@@@@%#**+++++++*##%@@@@@@@@@@@@@@@%-.................
.............-%@@@@@@@@@@@#*=-:...............:-=*%@@@@@@@@@@@*-................
...........:*@@@@@@@@@%*-:.........................:=*@@@@@@@@@@*:..............
..........+@@@@@@@@@#-.........:-=:.......:--..........=#@@@@@@@@@+.............
........-#@@@@@@@@*-............:+%#-...=##+:............-#@@@@@@@@#:...........
.......=%@@@@@@@#-................:*@%%%%+.................-#@@@@@@@%-..........
......=%@@@@@@%=......::::........-@@@@@@#:.................:+@@@@@@@%=.........
.....=%@@@@@@%-..:=*#%@@@@@#+:....:%@@@@@#:....:=*#%%%#*+-....=%@@@@@@%-........
....-%@@@@@@%-:+%@@@@@@@@@@@@@*-...:+##*=:...:#@@@@@@@@@@@@#+:.=%@@@@@@#:.......
...:*@@@@@@@==@@@@@@@@@@@@@@@@@%=...:#%+....=@@@@@@@@@@@@@@@@@*-+@@@@@@@+.......
...-%@@@@@@*.:#@@@@@@@@@@@@@@@@@@-.:*@@@=..+@@@@@@@@@@@@@@@@@@*::*@@@@@@#-......
...+@@@@@@@-..-%@@@@@@@@@@@@@@@@@%.-@@@@#:-%@@@@@@@@@@@@@@@@@#-..=@@@@@@@=......
..:#@@@@@@#....=@@@@@@@@@@@@@@@@@@++@@@@%=*@@@@@@@@@@@@@@@@@%-...:%@@@@@@*......
..:#@@@@@@*.....=%@@@@@@@@@@@@@@@#:%@@@@@*+@@@@@@@@@@@@@@@@%-.....#@@@@@@#:.....
..:%@@@@@@*......-#@@@@@@@@@@@@@*.:%@@@@@*:=%@@@@@@@@@@@@@#-......#@@@@@@#:.....
..:#@@@@@@*.......:*@@@@@@@@@@%=..-@@@@@@*:.-#@@@@@@@@@@@*:......:#@@@@@@*......
...*@@@@@@%:........-*%@@@@@#=:...-@@@@@@*:...=#@@@@@@@*-........-%@@@@@@+......
...=@@@@@@@=...........-=+=-:.....-@@@@@@*:.....-+##*-:..........+@@@@@@%-......
...:#@@@@@@%:........-#@@@@@@@#+-.:@@@@@@*::=*%@@@@@@%+:........-%@@@@@@*:......
....=@@@@@@@#:......=@@@@@@@@@@@@-.%@@@@@+:*@@@@@@@@@@@#:......:#@@@@@@%-.......
....:*@@@@@@@*:....:#@@@@@@@@@@@@:.#@@@@@=.+@@@@@@@@@@@@+.....:#@@@@@@@+........
.....:*@@@@@@@*:....+%@@@@@@@@@@*..=@@@@%-.-%@@@@@@@@@@#-....-#@@@@@@@*.........
......:*@@@@@@@%=.....-*%@@@@@@#:..:%@@@+...=@@@@@@@#+:.....=%@@@@@@@*..........
........+@@@@@@@@#-......:-=+=-.....-%@#:.....-=+=-.......-#@@@@@@@@=...........
.........=%@@@@@@@@#-................:-:................=#@@@@@@@@#-............
..........:+@@@@@@@@@%+-.............................-+%@@@@@@@@%+:.............
............:*@@@@@@@@@@%*=:.....................-=*%@@@@@@@@@%+:...............
..............:+%@@@@@@@@@@@%#*+=-::....:::-=+*%@@@@@@@@@@@@%+:.................
.................-*%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%*-....................
...................:-+%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#+-.......................
.......................:-+#%@@@@@@@@@@@@@@@@@@@@%%*+-:..........................
............................::-==+***##****+==-::...............................
................................................................................

Available Projects & Tools

📄 Viewing: index.php

💾 Download
<?php
// index.php

// Enable error reporting for debugging (remove in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Custom error logging
function logError($message) {
    $logFile = 'uploads/error.log';
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}

// Site domain
$siteDomain = 'https://doc.laptopministry.org/';

// Directories and data files
$uploadDir = 'uploads/';
$dataFileDocs = 'uploads/documents.json';
$dataFileCode = 'uploads/code.json';
$settingsFile = 'uploads/settings.json';
$logFile = 'uploads/error.log';

// Check and create uploads directory
if (!file_exists($uploadDir)) {
    if (!mkdir($uploadDir, 0755, true)) {
        logError("Failed to create uploads directory");
        die("Server error: Unable to create uploads directory.");
    }
}
if (!is_writable($uploadDir)) {
    logError("Uploads directory is not writable");
    die("Server error: Uploads directory is not writable.");
}

// Default settings
$defaultSettings = [
    'title' => 'DOC Post Services for Laptop Ministries',
    'description' => 'A platform for sharing documents and code for Laptop Ministries.',
    'logo' => '',
    'password_hash' => password_hash('changeme', PASSWORD_DEFAULT)
];

// Function to initialize or reset JSON file
function initializeJsonFile($file, $defaultData = []) {
    $jsonData = json_encode($defaultData, JSON_PRETTY_PRINT);
    if (!file_exists($file) || filesize($file) === 0 || json_decode(@file_get_contents($file), true) === null) {
        if (file_put_contents($file, $jsonData) === false) {
            logError("Failed to initialize/reset JSON file: $file");
            die("Server error: Unable to initialize JSON file.");
        }
    }
}

// Initialize JSON files
initializeJsonFile($dataFileDocs, []);
initializeJsonFile($dataFileCode, []);
initializeJsonFile($settingsFile, $defaultSettings);

// Load settings
$settings = $defaultSettings;
$settingsContent = @file_get_contents($settingsFile);
if ($settingsContent === false) {
    logError("Failed to read settings file: $settingsFile");
    die("Server error: Unable to read settings file.");
}
$settingsData = json_decode($settingsContent, true);
if ($settingsData === null) {
    logError("JSON decode error for settings: " . json_last_error_msg());
    file_put_contents($settingsFile, json_encode($defaultSettings, JSON_PRETTY_PRINT));
    $settingsData = $defaultSettings;
}
$settings = array_merge($defaultSettings, $settingsData);

// Load documents
$documents = [];
$docContent = @file_get_contents($dataFileDocs);
if ($docContent === false) {
    logError("Failed to read documents file: $dataFileDocs");
    die("Server error: Unable to read documents file.");
}
$docData = json_decode($docContent, true);
if ($docData === null) {
    logError("JSON decode error for documents: " . json_last_error_msg());
    file_put_contents($dataFileDocs, json_encode([], JSON_PRETTY_PRINT));
    $docData = [];
}
$documents = $docData;

// Load code files
$codeFiles = [];
$codeContent = @file_get_contents($dataFileCode);
if ($codeContent === false) {
    logError("Failed to read code file: $dataFileCode");
    die("Server error: Unable to read code file.");
}
$codeData = json_decode($codeContent, true);
if ($codeData === null) {
    logError("JSON decode error for code: " . json_last_error_msg());
    file_put_contents($dataFileCode, json_encode([], JSON_PRETTY_PRINT));
    $codeData = [];
}
$codeFiles = $codeData;

$error = '';
$success = '';
$adminLoggedIn = false;

// Check session save path
if (!is_writable(session_save_path())) {
    logError("Session save path is not writable: " . session_save_path());
    die("Server error: Session configuration issue.");
}

// Check admin login
session_start();
if (isset($_POST['admin_login']) && isset($_POST['admin_passcode']) && password_verify($_POST['admin_passcode'], $settings['password_hash'])) {
    $_SESSION['admin_logged_in'] = true;
}
if (isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in']) {
    $adminLoggedIn = true;
}
if (isset($_POST['logout'])) {
    session_destroy();
    header("Location: index.php");
    exit;
}

// Handle file upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'upload') {
    $passcode = $_POST['passcode'] ?? '';
    $description = $_POST['description'] ?? '';
    $type = $_POST['type'] ?? 'document';
    
    if (password_verify($passcode, $settings['password_hash'])) {
        if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
            $file = $_FILES['file'];
            $fileName = time() . '_' . preg_replace("/[^A-Za-z0-9\.\-_]/", '', basename($file['name']));
            $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
            $allowedExts = $type === 'document' ? ['pdf', 'txt', 'html'] : ['sh', 'c', 'bas', 'py'];
            
            if (in_array($fileExt, $allowedExts)) {
                $targetPath = $uploadDir . $fileName;
                if (move_uploaded_file($file['tmp_name'], $targetPath)) {
                    $entry = [
                        'name' => $fileName,
                        'date' => date('Y-m-d H:i:s'),
                        'ext' => $fileExt,
                        'description' => $description
                    ];
                    if ($type === 'document' && $fileExt === 'pdf' && isset($_FILES['tex_file']) && $_FILES['tex_file']['error'] === UPLOAD_ERR_OK) {
                        $texFile = $_FILES['tex_file'];
                        $texFileName = time() . '_tex_' . preg_replace("/[^A-Za-z0-9\.\-_]/", '', basename($texFile['name']));
                        $texExt = strtolower(pathinfo($texFileName, PATHINFO_EXTENSION));
                        if (in_array($texExt, ['tex'])) {
                            $texTargetPath = $uploadDir . $texFileName;
                            if (move_uploaded_file($texFile['tmp_name'], $texTargetPath)) {
                                $entry['tex_file'] = $texFileName;
                            } else {
                                logError("Failed to move TeX file to $texTargetPath");
                            }
                        }
                    }
                    if ($type === 'document') {
                        $documents[] = $entry;
                        if (!file_put_contents($dataFileDocs, json_encode($documents, JSON_PRETTY_PRINT))) {
                            logError("Failed to write to documents file: $dataFileDocs");
                            $error = "Failed to save document metadata.";
                        } else {
                            $success = "File uploaded successfully!";
                        }
                    } else {
                        $codeFiles[] = $entry;
                        if (!file_put_contents($dataFileCode, json_encode($codeFiles, JSON_PRETTY_PRINT))) {
                            logError("Failed to write to code file: $dataFileCode");
                            $error = "Failed to save code metadata.";
                        } else {
                            $success = "File uploaded successfully!";
                        }
                    }
                } else {
                    logError("Failed to move uploaded file to $targetPath");
                    $error = "Failed to upload file.";
                }
            } else {
                $error = "Invalid file type. Allowed: " . implode(', ', $allowedExts);
            }
        } else {
            $error = "No file uploaded or upload error.";
            if (isset($_FILES['file']['error'])) {
                logError("File upload error: " . $_FILES['file']['error']);
            }
        }
    } else {
        $error = "Incorrect passcode.";
    }
}

// Handle file deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete' && $adminLoggedIn) {
    $fileToDelete = $_POST['filename'] ?? '';
    $type = $_POST['type'] ?? 'document';
    $dataFile = $type === 'document' ? $dataFileDocs : $dataFileCode;
    
    if ($type === 'document') {
        $targetArray = &$documents;
    } else {
        $targetArray = &$codeFiles;
    }
    
    foreach ($targetArray as $index => $item) {
        if ($item['name'] === $fileToDelete) {
            if (file_exists($uploadDir . $fileToDelete)) {
                if (!unlink($uploadDir . $fileToDelete)) {
                    logError("Failed to delete file: $uploadDir$fileToDelete");
                }
            }
            if (isset($item['tex_file']) && file_exists($uploadDir . $item['tex_file'])) {
                if (!unlink($uploadDir . $item['tex_file'])) {
                    logError("Failed to delete TeX file: $uploadDir{$item['tex_file']}");
                }
            }
            unset($targetArray[$index]);
            $targetArray = array_values($targetArray);
            if (!file_put_contents($dataFile, json_encode($targetArray, JSON_PRETTY_PRINT))) {
                logError("Failed to write to $dataFile");
                $error = "Failed to update metadata.";
            } else {
                $success = "File deleted successfully!";
            }
            break;
        }
    }
}

// Handle file editing
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'edit' && $adminLoggedIn) {
    $fileToEdit = $_POST['filename'] ?? '';
    $type = $_POST['type'] ?? 'document';
    $description = $_POST['description'] ?? '';
    $dataFile = $type === 'document' ? $dataFileDocs : $dataFileCode;
    
    if ($type === 'document') {
        $targetArray = &$documents;
        $allowedExts = ['pdf', 'txt', 'html'];
    } else {
        $targetArray = &$codeFiles;
        $allowedExts = ['sh', 'c', 'bas', 'py'];
    }
    
    foreach ($targetArray as $index => &$item) {
        if ($item['name'] === $fileToEdit) {
            // Update description
            $item['description'] = $description;
            
            // Handle file replacement
            if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
                $file = $_FILES['file'];
                $newFileName = time() . '_' . preg_replace("/[^A-Za-z0-9\.\-_]/", '', basename($file['name']));
                $newFileExt = strtolower(pathinfo($newFileName, PATHINFO_EXTENSION));
                
                if (in_array($newFileExt, $allowedExts)) {
                    $newTargetPath = $uploadDir . $newFileName;
                    if (move_uploaded_file($file['tmp_name'], $newTargetPath)) {
                        // Delete old file
                        if (file_exists($uploadDir . $item['name'])) {
                            unlink($uploadDir . $item['name']);
                        }
                        $item['name'] = $newFileName;
                        $item['ext'] = $newFileExt;
                        $item['date'] = date('Y-m-d H:i:s');
                    } else {
                        logError("Failed to move new file to $newTargetPath");
                        $error = "Failed to update file.";
                    }
                } else {
                    $error = "Invalid file type for replacement. Allowed: " . implode(', ', $allowedExts);
                }
            }
            
            // Handle TeX file for PDFs
            if ($type === 'document' && $item['ext'] === 'pdf' && isset($_FILES['tex_file']) && $_FILES['tex_file']['error'] === UPLOAD_ERR_OK) {
                $texFile = $_FILES['tex_file'];
                $texFileName = time() . '_tex_' . preg_replace("/[^A-Za-z0-9\.\-_]/", '', basename($texFile['name']));
                $texExt = strtolower(pathinfo($texFileName, PATHINFO_EXTENSION));
                if (in_array($texExt, ['tex'])) {
                    $texTargetPath = $uploadDir . $texFileName;
                    if (move_uploaded_file($texFile['tmp_name'], $texTargetPath)) {
                        // Delete old TeX file if exists
                        if (isset($item['tex_file']) && file_exists($uploadDir . $item['tex_file'])) {
                            unlink($uploadDir . $item['tex_file']);
                        }
                        $item['tex_file'] = $texFileName;
                    } else {
                        logError("Failed to move TeX file to $texTargetPath");
                        $error = "Failed to update TeX file.";
                    }
                } else {
                    $error = "Invalid TeX file type. Allowed: tex";
                }
            }
            
            // Save updated array
            if (!file_put_contents($dataFile, json_encode($targetArray, JSON_PRETTY_PRINT))) {
                logError("Failed to write to $dataFile");
                $error = "Failed to save updated metadata.";
            } else {
                $success = "File updated successfully!";
            }
            break;
        }
    }
}

// Handle settings update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_settings' && $adminLoggedIn) {
    $settings['title'] = $_POST['site_title'] ?? $settings['title'];
    $settings['description'] = $_POST['site_description'] ?? $settings['description'];
    if (isset($_POST['new_password']) && !empty($_POST['new_password'])) {
        $settings['password_hash'] = password_hash($_POST['new_password'], PASSWORD_DEFAULT);
    }
    if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
        $logoFile = $_FILES['logo'];
        $logoExt = strtolower(pathinfo($logoFile['name'], PATHINFO_EXTENSION));
        if (in_array($logoExt, ['png', 'jpg', 'jpeg'])) {
            $imageInfo = @getimagesize($logoFile['tmp_name']);
            if ($imageInfo !== false && $imageInfo[0] <= 128) {
                $logoName = 'logo_' . time() . '.' . $logoExt;
                if (move_uploaded_file($logoFile['tmp_name'], $uploadDir . $logoName)) {
                    $settings['logo'] = $logoName;
                } else {
                    logError("Failed to move logo file to $uploadDir$logoName");
                }
            } else {
                $error = "Logo must be 128px or smaller.";
                logError("Invalid logo dimensions or corrupted image");
            }
        } else {
            $error = "Invalid logo file type. Allowed: png, jpg, jpeg";
        }
    }
    if (!file_put_contents($settingsFile, json_encode($settings, JSON_PRETTY_PRINT))) {
        logError("Failed to write to settings file: $settingsFile");
        $error = "Failed to update settings.";
    } else {
        $success = "Settings updated successfully!";
    }
}

// Handle file viewing and editing
$fileToView = isset($_GET['view']) ? $_GET['view'] : null;
$fileToEdit = isset($_GET['edit']) ? $_GET['edit'] : null;
$viewType = isset($_GET['type']) ? $_GET['type'] : 'document';
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title><?php echo htmlspecialchars($settings['title']); ?></title>
    <meta name="description" content="<?php echo htmlspecialchars($settings['description']); ?>">
    <meta property="og:title" content="<?php echo htmlspecialchars($settings['title']); ?>">
    <meta property="og:description" content="<?php echo htmlspecialchars($settings['description']); ?>">
    <?php if ($settings['logo']): ?>
        <meta property="og:image" content="<?php echo htmlspecialchars($siteDomain . 'uploads/' . $settings['logo']); ?>">
    <?php endif; ?>
    <style>
        body {
            font-family: 'Courier New', Courier, monospace;
            background-color: #000000;
            color: #FFC107; /* Amber */
            margin: 0;
            padding: 0;
        }
        header {
            background-color: #4CAF50; /* Green */
            padding: 1em;
            text-align: center;
        }
        h1, h2 {
            color: #FFC107;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .tabs {
            margin-bottom: 20px;
        }
        .tabs a {
            display: inline-block;
            padding: 10px 20px;
            background: #4CAF50;
            color: #000000;
            text-decoration: none;
            margin-right: 5px;
            border-radius: 5px;
        }
        .tabs a:hover {
            background: #000000;
            color: #4CAF50;
        }
        .tabs a.active {
            background: #8B4513; /* Brown */
            color: #FFFFFF;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            color: #FFC107;
        }
        th, td {
            padding: 10px;
            border: 1px solid #4CAF50;
            text-align: left;
        }
        a, button, input[type="submit"] {
            background: #4CAF50;
            color: #000000;
            padding: 5px 10px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
        }
        a:hover, button:hover, input[type="submit"]:hover {
            background: #000000;
            color: #4CAF50;
        }
        .error {
            color: #FF4444;
        }
        .success {
            color: #4CAF50;
        }
        pre, iframe {
            background: #1C2526;
            padding: 10px;
            border-radius: 5px;
            color: #FFC107;
        }
        footer {
            text-align: center;
            padding: 1em;
            background: #8B4513;
            color: #FFFFFF;
            position: fixed;
            bottom: 0;
            width: 100%;
        }
        .admin-section {
            border: 1px solid #4CAF50;
            padding: 20px;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <header>
        <h1><?php echo htmlspecialchars($settings['title']); ?></h1>
        <?php if ($settings['logo']): ?>
            <img src="<?php echo htmlspecialchars('uploads/' . $settings['logo']); ?>" alt="Site Logo" style="max-width: 128px;">
        <?php endif; ?>
    </header>

    <div class="container">
        <div class="tabs">
            <a href="?tab=documents" class="<?php echo (!isset($_GET['tab']) || $_GET['tab'] === 'documents') ? 'active' : ''; ?>">Documents</a>
            <a href="?tab=code" class="<?php echo (isset($_GET['tab']) && $_GET['tab'] === 'code') ? 'active' : ''; ?>">Code</a>
            <?php if ($adminLoggedIn): ?>
                <a href="?tab=admin" class="<?php echo (isset($_GET['tab']) && $_GET['tab'] === 'admin') ? 'active' : ''; ?>">Admin</a>
                <form method="post" style="display: inline;">
                    <input type="hidden" name="logout" value="1">
                    <input type="submit" value="Logout">
                </form>
            <?php else: ?>
                <a href="?tab=admin_login" class="<?php echo (isset($_GET['tab']) && $_GET['tab'] === 'admin_login') ? 'active' : ''; ?>">Admin Login</a>
            <?php endif; ?>
        </div>

        <?php if ($error): ?>
            <p class="error"><?php echo htmlspecialchars($error); ?></p>
        <?php endif; ?>
        <?php if ($success): ?>
            <p class="success"><?php echo htmlspecialchars($success); ?></p>
        <?php endif; ?>

        <!-- File viewing section -->
        <?php if ($fileToView && file_exists($uploadDir . $fileToView)): ?>
            <?php 
            $ext = strtolower(pathinfo($fileToView, PATHINFO_EXTENSION));
            $rawUrl = 'uploads/' . urlencode($fileToView);
            $wgetCommand = "wget " . $siteDomain . $rawUrl;
            $item = null;
            $items = $viewType === 'document' ? $documents : $codeFiles;
            foreach ($items as $i) {
                if ($i['name'] === $fileToView) {
                    $item = $i;
                    break;
                }
            }
            ?>
            <h2><?php echo htmlspecialchars($fileToView); ?></h2>
            <meta property="og:title" content="<?php echo htmlspecialchars($fileToView); ?>">
            <meta property="og:description" content="<?php echo htmlspecialchars($item['description'] ?? ''); ?>">
            <?php if ($settings['logo']): ?>
                <meta property="og:image" content="<?php echo htmlspecialchars($siteDomain . 'uploads/' . $settings['logo']); ?>">
            <?php endif; ?>
            <p>Description: <?php echo htmlspecialchars($item['description'] ?? 'No description'); ?></p>
            <p><a href="<?php echo htmlspecialchars($siteDomain . $rawUrl); ?>" download>Download File</a></p>
            <?php if ($viewType === 'document'): ?>
                <?php if ($ext === 'pdf'): ?>
                    <embed src="<?php echo htmlspecialchars($rawUrl); ?>" width="100%" height="600px" type="application/pdf">
                    <?php if (isset($item['tex_file'])): ?>
                        <p><a href="<?php echo htmlspecialchars($siteDomain . 'uploads/' . urlencode($item['tex_file'])); ?>" download>Download TeX File</a></p>
                    <?php endif; ?>
                <?php elseif ($ext === 'html'): ?>
                    <iframe src="<?php echo htmlspecialchars($rawUrl); ?>" width="100%" height="600px"></iframe>
                <?php else: ?>
                    <pre><?php echo htmlspecialchars(file_get_contents($uploadDir . $fileToView)); ?></pre>
                <?php endif; ?>
            <?php else: ?>
                <p>Try <code><?php echo htmlspecialchars($wgetCommand); ?></code> from the console
                <button onclick="copyToClipboard('<?php echo htmlspecialchars($wgetCommand, ENT_QUOTES); ?>')">Copy wget</button></p>
                <pre><?php echo htmlspecialchars(file_get_contents($uploadDir . $fileToView)); ?></pre>
            <?php endif; ?>
            <a href="?tab=<?php echo $viewType; ?>">Back to <?php echo ucfirst($viewType); ?>s</a>
        <?php elseif ($fileToEdit && $adminLoggedIn): ?>
            <!-- Edit file section -->
            <?php 
            $editItem = null;
            $editItems = $viewType === 'document' ? $documents : $codeFiles;
            foreach ($editItems as $i) {
                if ($i['name'] === $fileToEdit) {
                    $editItem = $i;
                    break;
                }
            }
            if ($editItem): ?>
                <h2>Edit: <?php echo htmlspecialchars($fileToEdit); ?></h2>
                <form method="post" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="edit">
                    <input type="hidden" name="type" value="<?php echo htmlspecialchars($viewType); ?>">
                    <input type="hidden" name="filename" value="<?php echo htmlspecialchars($fileToEdit); ?>">
                    <label>Description:</label>
                    <textarea name="description" rows="4" style="width: 100%;"><?php echo htmlspecialchars($editItem['description'] ?? ''); ?></textarea>
                    <label>Replace File (optional):</label>
                    <input type="file" name="file" accept="<?php echo $viewType === 'document' ? '.pdf,.txt,.html' : '.sh,.c,.bas,.py'; ?>">
                    <?php if ($viewType === 'document' && $editItem['ext'] === 'pdf'): ?>
                        <label>Replace TeX File (optional):</label>
                        <input type="file" name="tex_file" accept=".tex">
                    <?php endif; ?>
                    <input type="submit" value="Update Item">
                </form>
                <a href="?tab=<?php echo $viewType; ?>">Cancel</a>
            <?php else: ?>
                <p class="error">Item not found.</p>
                <a href="?tab=<?php echo $viewType; ?>">Back to <?php echo ucfirst($viewType); ?>s</a>
            <?php endif; ?>
        <?php else: ?>
            <!-- Tabbed content section -->
            <?php if (!isset($_GET['tab']) || $_GET['tab'] === 'documents'): ?>
                <h2>Upload Document</h2>
                <form method="post" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="upload">
                    <input type="hidden" name="type" value="document">
                    <input type="password" name="passcode" placeholder="Enter Passcode" required>
                    <input type="file" name="file" accept=".pdf,.txt,.html" required>
                    <input type="file" name="tex_file" accept=".tex" style="display: none;" id="tex_file">
                    <textarea name="description" placeholder="Description" rows="4" style="width: 100%;"></textarea>
                    <input type="submit" value="Upload Document">
                </form>
                <script>
                    document.querySelector('input[name="file"]').addEventListener('change', function() {
                        let texInput = document.getElementById('tex_file');
                        texInput.style.display = this.files[0].name.endsWith('.pdf') ? 'block' : 'none';
                    });
                </script>

                <h2>Latest Documents</h2>
                <table>
                    <tr>
                        <th>Document Name</th>
                        <th>Date</th>
                        <th>Description</th>
                        <th>Action</th>
                    </tr>
                    <?php foreach (array_reverse($documents) as $doc): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($doc['name']); ?></td>
                            <td><?php echo htmlspecialchars($doc['date']); ?></td>
                            <td><?php echo htmlspecialchars($doc['description'] ?? 'No description'); ?></td>
                            <td>
                                <a href="?view=<?php echo urlencode($doc['name']); ?>&type=document">View</a>
                                <?php if ($adminLoggedIn): ?>
                                    | <a href="?edit=<?php echo urlencode($doc['name']); ?>&type=document">Edit</a>
                                    | <form method="post" style="display: inline;">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="type" value="document">
                                        <input type="hidden" name="filename" value="<?php echo htmlspecialchars($doc['name']); ?>">
                                        <input type="submit" value="Delete">
                                    </form>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </table>
            <?php elseif ($_GET['tab'] === 'code'): ?>
                <h2>Upload Code</h2>
                <form method="post" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="upload">
                    <input type="hidden" name="type" value="code">
                    <input type="password" name="passcode" placeholder="Enter Passcode" required>
                    <input type="file" name="file" accept=".sh,.c,.bas,.py" required>
                    <textarea name="description" placeholder="Description" rows="4" style="width: 100%;"></textarea>
                    <input type="submit" value="Upload Code">
                </form>

                <h2>Latest Code</h2>
                <table>
                    <tr>
                        <th>Code Name</th>
                        <th>Date</th>
                        <th>Description</th>
                        <th>Action</th>
                    </tr>
                    <?php foreach (array_reverse($codeFiles) as $code): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($code['name']); ?></td>
                            <td><?php echo htmlspecialchars($code['date']); ?></td>
                            <td><?php echo htmlspecialchars($code['description'] ?? 'No description'); ?></td>
                            <td>
                                <a href="?view=<?php echo urlencode($code['name']); ?>&type=code">View</a>
                                <?php if ($adminLoggedIn): ?>
                                    | <a href="?edit=<?php echo urlencode($code['name']); ?>&type=code">Edit</a>
                                    | <form method="post" style="display: inline;">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="type" value="code">
                                        <input type="hidden" name="filename" value="<?php echo htmlspecialchars($code['name']); ?>">
                                        <input type="submit" value="Delete">
                                    </form>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </table>
            <?php elseif ($_GET['tab'] === 'admin' && $adminLoggedIn): ?>
                <h2>Admin Settings</h2>
                <form method="post" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="update_settings">
                    <label>Site Title:</label>
                    <input type="text" name="site_title" value="<?php echo htmlspecialchars($settings['title']); ?>">
                    <label>Site Description:</label>
                    <textarea name="site_description" rows="4" style="width: 100%;"><?php echo htmlspecialchars($settings['description']); ?></textarea>
                    <label>New Password (leave blank to keep current):</label>
                    <input type="password" name="new_password">
                    <label>Site Logo (max 128px):</label>
                    <input type="file" name="logo" accept=".png,.jpg,.jpeg">
                    <input type="submit" value="Update Settings">
                </form>
            <?php elseif ($_GET['tab'] === 'admin_login'): ?>
                <h2>Admin Login</h2>
                <form method="post">
                    <input type="password" name="admin_passcode" placeholder="Enter Admin Passcode" required>
                    <input type="hidden" name="admin_login" value="1">
                    <input type="submit" value="Login">
                </form>
            <?php endif; ?>
            <!-- End tabbed content section -->
        <?php endif; ?>
        <!-- End container -->
    </div>
<br><br>
    <footer>
        A Page Telegram Volunteer Service for Laptop Ministry: DOC Post, Started in 2025.
    </footer>

    <script>
        function copyToClipboard(text) {
            navigator.clipboard.writeText(text).then(() => {
                alert('Copied to clipboard: ' + text);
            }).catch(err => {
                console.error('Failed to copy: ', err);
            });
        }
    </script>
</body>
</html>