<?php
require_once __DIR__ . '/security.php';

$tenant = enrep_tenant_segment();
if ($tenant !== '' && file_exists('../../' . $tenant . '/config.php')) {
    require_once('../../' . $tenant . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

enrep_require_user();

$clientnumber = enrep_request_int('clientnumber');
$wsno = preg_replace('/[^A-Za-z0-9_-]/', '', enrep_request_string('wsno', '', 80));

if ($tenant === '' || $clientnumber < 1 || $wsno === '' || empty($_FILES['file'])) {
    echo 0;
    exit;
}

if (!isset($_FILES['file']['error']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK || !is_uploaded_file($_FILES['file']['tmp_name'])) {
    echo 0;
    exit;
}

$filename = enrep_safe_filename((string)($_FILES['file']['name'] ?? ''));
$pathParts = pathinfo($filename);
$ext = strtolower((string)($pathParts['extension'] ?? ''));

if ($ext !== 'pdf') {
    echo 0;
    exit;
}

$path = "../../" . $tenant . "/output/wsfiles/" . $clientnumber;
if (!is_dir($path) && !mkdir($path, 0775, true) && !is_dir($path)) {
    echo 0;
    exit;
}

$base = realpath($path);
if ($base === false) {
    echo 0;
    exit;
}

$location = $base . DIRECTORY_SEPARATOR . "WS" . $wsno . "." . $ext;

if (move_uploaded_file($_FILES['file']['tmp_name'], $location)) {
    @chmod($location, 0644);
    echo "s";
} else {
    echo 0;
}
