<?php
// upload_helpers.php
// Upload slika/video za naloge (consumption_orders)
// Slike: pokušaj konverzije u WebP preko GD (imagewebp). Ako nema podrške -> spremi original.

function ensure_dir(string $dir): void {
    if (!is_dir($dir)) {
        if (!mkdir($dir, 0775, true) && !is_dir($dir)) {
            throw new RuntimeException("Ne mogu kreirati direktorij: {$dir}");
        }
    }
}

function ext_from_mime(string $mime, string $origName): string {
    $mime = strtolower(trim($mime));
    $map = [
        'image/jpeg' => 'jpg',
        'image/jpg'  => 'jpg',
        'image/png'  => 'png',
        'image/gif'  => 'gif',
        'image/webp' => 'webp',
        'video/mp4'  => 'mp4',
        'video/webm' => 'webm',
        'video/quicktime' => 'mov',
        'video/x-matroska' => 'mkv',
    ];
    if (isset($map[$mime])) return $map[$mime];

    $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
    $ext = preg_replace('~[^a-z0-9]+~', '', $ext);
    return $ext ?: 'bin';
}

function is_image_mime(string $mime): bool { return str_starts_with(strtolower($mime), 'image/'); }
function is_video_mime(string $mime): bool { return str_starts_with(strtolower($mime), 'video/'); }

function try_convert_to_webp(string $tmpPath, string $destDirAbs, string $baseName): array {
    if (!function_exists('imagecreatefromstring') || !function_exists('imagewebp')) {
        return [false, null, null];
    }
    $data = @file_get_contents($tmpPath);
    if ($data === false) return [false, null, null];

    $im = @imagecreatefromstring($data);
    if (!$im) return [false, null, null];

    if (function_exists('imagepalettetotruecolor')) { @imagepalettetotruecolor($im); }
    if (function_exists('imagealphablending')) { @imagealphablending($im, true); }
    if (function_exists('imagesavealpha')) { @imagesavealpha($im, true); }

    $abs = rtrim($destDirAbs, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $baseName . '.webp';
    $ok = @imagewebp($im, $abs, 82);
    @imagedestroy($im);

    if (!$ok || !file_exists($abs)) return [false, null, null];
    return [true, $abs, 'image/webp'];
}

/**
 * Upload više datoteka za nalog.
 * Očekuje input name="media_files[]"
 */
function handle_order_media_uploads(mysqli $mysqli, int $order_id, array $files, ?int $uploaded_by = null): void {
    if (empty($files) || empty($files['name'])) return;

    $baseAbs = __DIR__ . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'orders' . DIRECTORY_SEPARATOR . $order_id;
    $baseRel = 'uploads/orders/' . $order_id;
    ensure_dir($baseAbs);

    $finfo = new finfo(FILEINFO_MIME_TYPE);

    $maxImageBytes = 12 * 1024 * 1024;   // 12MB po slici
    $maxVideoBytes = 250 * 1024 * 1024;  // 250MB po videu

    $stmt = $mysqli->prepare(
        "INSERT INTO consumption_order_media (order_id, type, path, original_name, mime, size, uploaded_by)
         VALUES (?,?,?,?,?,?,?)"
    );

    $count = is_array($files['name']) ? count($files['name']) : 0;

    for ($i=0; $i<$count; $i++) {
        if (($files['error'][$i] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) continue;

        $tmp  = $files['tmp_name'][$i];
        $orig = $files['name'][$i] ?? 'file';
        $size = (int)($files['size'][$i] ?? 0);

        if (!is_uploaded_file($tmp)) continue;

        $mime = $finfo->file($tmp) ?: 'application/octet-stream';

        $isImg = is_image_mime($mime);
        $isVid = is_video_mime($mime);

        if (!$isImg && !$isVid) continue;
        if ($isImg && $size > $maxImageBytes) continue;
        if ($isVid && $size > $maxVideoBytes) continue;

        $type = $isImg ? 'image' : 'video';
        $baseName = $type . '_' . date('Ymd_His') . '_' . bin2hex(random_bytes(6));

        $finalAbs = null;
        $finalRel = null;
        $finalMime = $mime;

        if ($isImg) {
            [$ok, $abs, $webpMime] = try_convert_to_webp($tmp, $baseAbs, $baseName);
            if ($ok) {
                $finalAbs = $abs;
                $finalRel = $baseRel . '/' . basename($finalAbs);
                $finalMime = $webpMime;
            } else {
                $ext = ext_from_mime($mime, $orig);
                $finalAbs = $baseAbs . DIRECTORY_SEPARATOR . $baseName . '.' . $ext;
                if (!move_uploaded_file($tmp, $finalAbs)) continue;
                $finalRel = $baseRel . '/' . basename($finalAbs);
            }
        } else {
            $ext = ext_from_mime($mime, $orig);
            $finalAbs = $baseAbs . DIRECTORY_SEPARATOR . $baseName . '.' . $ext;
            if (!move_uploaded_file($tmp, $finalAbs)) continue;
            $finalRel = $baseRel . '/' . basename($finalAbs);
        }

        $origSafe = mb_substr($orig, 0, 255);
        $mimeSafe = mb_substr($finalMime, 0, 100);

        $stmt->bind_param('issssii', $order_id, $type, $finalRel, $origSafe, $mimeSafe, $size, $uploaded_by);
        $stmt->execute();
    }

    $stmt->close();
}

/**
 * Obriši medije po ID-evima (i datoteke i DB).
 */
function delete_order_media(mysqli $mysqli, int $order_id, array $media_ids): void {
    $ids = array_values(array_filter(array_map('intval', $media_ids), fn($v)=>$v>0));
    if (!$ids) return;

    $in = implode(',', array_fill(0, count($ids), '?'));
    $types = str_repeat('i', count($ids) + 1);

    $sql = "SELECT id, path FROM consumption_order_media WHERE order_id=? AND id IN ($in)";
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param($types, $order_id, ...$ids);
    $stmt->execute();
    $res = $stmt->get_result();

    $paths = [];
    while($r=$res->fetch_assoc()){
        $paths[] = $r['path'];
    }
    $stmt->close();

    $sql2 = "DELETE FROM consumption_order_media WHERE order_id=? AND id IN ($in)";
    $stmt2 = $mysqli->prepare($sql2);
    $stmt2->bind_param($types, $order_id, ...$ids);
    $stmt2->execute();
    $stmt2->close();

    foreach($paths as $rel){
        $rel = str_replace(['..','\\'], ['','/'], $rel);
        $abs = __DIR__ . DIRECTORY_SEPARATOR . $rel;
        if (is_file($abs)) @unlink($abs);
    }
}
