<?php
require_once '../../config.php';
require_once '../medoo/medoo.php';
require_once 'upload-common.php';

plupload_bootstrap();
plupload_require_post();
$userId = plupload_require_admin_user();
plupload_validate_token($userId);

$fileDir = '/upload/product_files/tmp';
$targetDir = '../..' . $fileDir;
plupload_ensure_target_dir($targetDir);

list($chunk, $chunks) = plupload_get_chunks();
list($fileName, $extension, $filePath, $partPath) = plupload_build_target_paths(
    $targetDir,
    $_REQUEST['name'] ?? '',
    null,
    [
        'php', 'php3', 'php4', 'php5', 'php7', 'php8', 'phtml', 'phar',
        'cgi', 'pl', 'py', 'rb',
        'asp', 'aspx', 'jsp',
        'js', 'mjs', 'vbs', 'wsf', 'hta',
        'sh', 'bash', 'zsh', 'ps1', 'bat', 'cmd', 'com',
        'exe', 'msi', 'scr', 'dll', 'jar',
    ]
);

plupload_cleanup_stale_parts($targetDir, $partPath, 5 * 3600);
plupload_write_chunk_to_part($partPath, $chunk);
plupload_assert_size_limit($partPath, 50 * 1024 * 1024, 'Plik przekracza dozwolony rozmiar (50 MB).');

$fileId = null;
$responseFileName = $fileName;
if (plupload_is_last_chunk($chunk, $chunks)) {
    plupload_finalize_part($partPath, $filePath);

    $mdb = plupload_create_medoo($database);
    $mdb->insert('pp_shop_products_files', [
        'product_id' => null,
        'src' => substr($filePath, 5),
    ]);

    $fileId = (int)$mdb->id();
    $responseFileName = basename($filePath);
}

plupload_send_success([
    'file_name' => $responseFileName,
    'file_id' => $fileId,
]);

