<?php
/* Mobile-Upload-Page für Bericht.
 * KEIN Dolibarr-Login nötig — Authentifizierung über Token in der URL.
 *
 * GET: token
 * POST: token, file (multipart)
 */

if (!defined('NOLOGIN'))     define('NOLOGIN', '1');
if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1');
if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1');
if (!defined('NOREQUIREMENU'))  define('NOREQUIREMENU', '1');
if (!defined('NOREQUIREHTML'))  define('NOREQUIREHTML', '1');
if (!defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX', '1');

$res = 0;
if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; }
if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php";
if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php";
if (!$res) die("Include of main fails");

require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once __DIR__.'/class/bericht.class.php';
require_once __DIR__.'/class/upload_token.class.php';

$token = (string) ($_REQUEST['token'] ?? '');
$tok = BerichtUploadToken::fetchValid($db, $token);

// POST = Datei-Upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_FILES['file']['tmp_name'])) {
    header('Content-Type: application/json; charset=utf-8');
    if (!$tok) {
        http_response_code(403);
        echo json_encode(array('success' => false, 'error' => 'Token ungültig oder abgelaufen'));
        exit;
    }

    $bericht = new Bericht($db);
    if ($bericht->fetch($tok->fk_bericht) <= 0) {
        http_response_code(404);
        echo json_encode(array('success' => false, 'error' => 'Bericht nicht gefunden'));
        exit;
    }

    $orig = dol_sanitizeFileName($_FILES['file']['name']);
    $ext = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
    $allowed = array('jpg', 'jpeg', 'png');
    if (!in_array($ext, $allowed)) {
        echo json_encode(array('success' => false, 'error' => 'Nur JPG/PNG erlaubt'));
        exit;
    }

    $workdir = DOL_DATA_ROOT.'/bericht/work/'.$tok->fk_bericht;
    if (!is_dir($workdir)) dol_mkdir($workdir);

    $target = $workdir.'/mobile_'.dol_print_date(dol_now(), '%Y%m%d_%H%M%S').'_'.uniqid().'.'.$ext;
    if (!move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
        echo json_encode(array('success' => false, 'error' => 'Upload fehlgeschlagen'));
        exit;
    }
    $relpath = str_replace(DOL_DATA_ROOT.'/', '', $target);

    // Als neue Bericht-Page einfügen
    $res = $db->query("SELECT COALESCE(MAX(page_order),0) AS m FROM ".$db->prefix()."bericht_page WHERE fk_bericht = ".((int) $tok->fk_bericht));
    $next_order = ($res && ($o = $db->fetch_object($res))) ? ((int) $o->m) + 1 : 1;

    $page = new BerichtPage($db);
    $page->fk_bericht  = $tok->fk_bericht;
    $page->page_order  = $next_order;
    $page->source_type = 'upload';
    $page->source_path = $relpath;
    if ($page->create() <= 0) {
        echo json_encode(array('success' => false, 'error' => 'DB-Insert fehlgeschlagen'));
        exit;
    }

    $tok->incrementCount();
    echo json_encode(array('success' => true, 'pageid' => $page->id, 'filename' => basename($target)));
    exit;
}

// GET = Mobile-Upload-Seite anzeigen
if (!$tok) {
    http_response_code(403);
    ?>
    <!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Bericht — Token ungültig</title>
    <style>
    body { font-family: -apple-system, BlinkMacSystemFont, sans-serif; background:#1a1a1f; color:#fff; padding: 40px 20px; text-align:center; }
    h1 { color: #d9534f; }
    </style>
    </head><body>
    <h1>⚠️ Token ungültig</h1>
    <p>Dieser Upload-Link ist abgelaufen oder ungültig.</p>
    <p>Bitte im Bericht-Editor einen neuen QR-Code generieren.</p>
    </body></html>
    <?php
    exit;
}

// Bericht-Daten für die Anzeige
$bericht = new Bericht($db);
$bericht->fetch($tok->fk_bericht);
$auftragsnr = $bericht->auftragsnummer ?: $bericht->ref;
$valid_min = max(1, round(($tok->expires_at - dol_now()) / 60));

?>
<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<meta name="theme-color" content="#1a1a1f">
<title>Bericht Upload — <?php print htmlspecialchars($auftragsnr); ?></title>
<style>
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
    background: #1a1a1f;
    color: #f0f0f0;
    margin: 0;
    padding: 16px;
    min-height: 100vh;
    -webkit-font-smoothing: antialiased;
}
.header {
    text-align: center;
    padding: 16px 0 24px;
    border-bottom: 1px solid #333;
}
.header h1 { margin: 0 0 4px; font-size: 18px; color: #f0f0f0; }
.header .ref { color: #7aa2f7; font-size: 14px; }
.header .info { font-size: 11px; opacity: 0.6; margin-top: 8px; }

.action-buttons {
    display: flex;
    flex-direction: column;
    gap: 12px;
    margin: 24px 0;
}
.btn {
    display: block;
    width: 100%;
    padding: 18px 24px;
    font-size: 17px;
    font-weight: 600;
    border-radius: 12px;
    border: none;
    cursor: pointer;
    background: #337ab7;
    color: #fff;
    text-align: center;
    -webkit-appearance: none;
    transition: transform 0.1s, background 0.15s;
}
.btn:active { transform: scale(0.97); background: #2868a0; }
.btn-secondary {
    background: #2a2a30;
    border: 1px solid #555;
}
.btn-secondary:active { background: #3a3a40; }

.hidden-input { display: none; }

.uploaded-list {
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid #333;
}
.uploaded-list h2 { font-size: 14px; opacity: 0.7; margin: 0 0 12px; text-transform: uppercase; }
.uploaded-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 0;
    border-bottom: 1px solid #2a2a30;
    font-size: 13px;
}
.uploaded-item .check { color: #5cb85c; }
.uploaded-item .name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.uploaded-item .size { opacity: 0.5; font-size: 11px; }

.uploading {
    padding: 12px;
    background: #2a2a30;
    border-radius: 6px;
    margin: 12px 0;
    text-align: center;
    color: #7aa2f7;
}

.toast {
    position: fixed;
    top: 16px;
    left: 16px;
    right: 16px;
    background: #5cb85c;
    color: #fff;
    padding: 14px 16px;
    border-radius: 8px;
    text-align: center;
    z-index: 100;
    box-shadow: 0 4px 16px rgba(0,0,0,0.4);
    animation: slideDown 0.2s;
}
.toast.error { background: #d9534f; }
@keyframes slideDown { from { opacity: 0; transform: translateY(-20px); } to { opacity: 1; } }
</style>
</head>
<body>

<div class="header">
    <h1>📷 Bericht Upload</h1>
    <div class="ref"><?php print htmlspecialchars($auftragsnr); ?></div>
    <div class="info">Token gültig noch <?php print $valid_min; ?> Min · <?php print $tok->max_uploads - $tok->uploads_count; ?> Uploads übrig</div>
</div>

<div class="action-buttons">
    <label class="btn" for="camera-input">📸 Foto aufnehmen</label>
    <input type="file" id="camera-input" class="hidden-input" accept="image/*" capture="environment" multiple>

    <label class="btn btn-secondary" for="gallery-input">📂 Aus Galerie wählen</label>
    <input type="file" id="gallery-input" class="hidden-input" accept="image/*" multiple>
</div>

<div id="uploading-area"></div>

<div class="uploaded-list">
    <h2>Hochgeladen <span id="uploaded-count">(0)</span></h2>
    <div id="uploaded-list"></div>
</div>

<script>
const TOKEN = <?php print json_encode($token); ?>;
const URL_UPLOAD = window.location.pathname + '?token=' + encodeURIComponent(TOKEN);
let uploadedCount = 0;

const cameraInput = document.getElementById('camera-input');
const galleryInput = document.getElementById('gallery-input');
const uploadingArea = document.getElementById('uploading-area');
const uploadedList = document.getElementById('uploaded-list');
const uploadedCountEl = document.getElementById('uploaded-count');

[cameraInput, galleryInput].forEach(inp => {
    inp.addEventListener('change', async () => {
        if (!inp.files || !inp.files.length) return;
        for (const file of inp.files) {
            await uploadFile(file);
        }
        inp.value = '';
    });
});

async function uploadFile(file) {
    // Optional: clientseitig auf max 2000px resizen
    const blob = await resizeImage(file, 2000);
    const fname = file.name || 'photo.jpg';

    const status = document.createElement('div');
    status.className = 'uploading';
    status.textContent = '⬆ ' + fname + ' wird hochgeladen…';
    uploadingArea.appendChild(status);

    const fd = new FormData();
    fd.append('token', TOKEN);
    fd.append('file', blob, fname);

    try {
        const r = await fetch(URL_UPLOAD, { method: 'POST', body: fd });
        const data = await r.json();
        status.remove();
        if (data.success) {
            uploadedCount++;
            uploadedCountEl.textContent = '(' + uploadedCount + ')';
            const item = document.createElement('div');
            item.className = 'uploaded-item';
            item.innerHTML = '<span class="check">✓</span><span class="name">' + escapeHtml(data.filename) + '</span>';
            uploadedList.prepend(item);
            toast('Hochgeladen: ' + fname);
        } else {
            toast('Fehler: ' + (data.error || 'unbekannt'), true);
        }
    } catch (e) {
        status.remove();
        toast('Netzwerkfehler', true);
    }
}

async function resizeImage(file, maxSide) {
    return new Promise((resolve) => {
        const img = new Image();
        const url = URL.createObjectURL(file);
        img.onload = () => {
            URL.revokeObjectURL(url);
            const scale = Math.min(1, maxSide / Math.max(img.width, img.height));
            if (scale === 1) {
                resolve(file);
                return;
            }
            const c = document.createElement('canvas');
            c.width  = Math.round(img.width * scale);
            c.height = Math.round(img.height * scale);
            c.getContext('2d').drawImage(img, 0, 0, c.width, c.height);
            c.toBlob((blob) => resolve(blob || file), 'image/jpeg', 0.85);
        };
        img.onerror = () => { URL.revokeObjectURL(url); resolve(file); };
        img.src = url;
    });
}

function toast(msg, isError) {
    const t = document.createElement('div');
    t.className = 'toast' + (isError ? ' error' : '');
    t.textContent = msg;
    document.body.appendChild(t);
    setTimeout(() => t.remove(), 2500);
}

function escapeHtml(s) {
    return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}
</script>

</body>
</html>
