<?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_images/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'] ?? '',
    ['jpg', 'jpeg', 'png', 'gif', 'webp'],
    null
);

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

$imageId = null;
if (plupload_is_last_chunk($chunk, $chunks)) {
    plupload_finalize_part($partPath, $filePath);

    $mime = mime_content_type($filePath) ?: '';
    $imageMeta = @getimagesize($filePath);
    $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $isValidImage = in_array($mime, $allowedMimeTypes, true)
        && is_array($imageMeta)
        && (int)($imageMeta[0] ?? 0) > 0
        && (int)($imageMeta[1] ?? 0) > 0;

    if (!$isValidImage) {
        @unlink($filePath);
        plupload_send_error(400, 601, 'Plik nie jest prawidlowym obrazem.');
    }

    $mdb = plupload_create_medoo($database);
    $order = (int)$mdb->max('pp_shop_products_images', 'o');
    $productId = (int)($_POST['product_id'] ?? 0);

    $mdb->insert('pp_shop_products_images', [
        'product_id' => $productId > 0 ? $productId : null,
        'src' => substr($filePath, 5),
        'o' => $order + 1,
    ]);

    $imageId = (int)$mdb->id();
}

plupload_send_success([
    'data_link' => str_replace('../../', '', $filePath),
    'image_id' => $imageId,
]);

