<?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');
}

if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    enrep_fail(400, 'Tenant config not found');
}
enrep_require_user();

$tenantDir = defined('TENANT_URL') ? trim((string)TENANT_URL, "/\\") : $tenant;
$client = enrep_request_int('client');
$reps = enrep_request_string('reps', '', 1000000);
$fcn = enrep_request_enum('FCN', ['save', 'delete', 'rename'], '');

if ($client < 1) {
    enrep_fail(400, 'Invalid client');
}

function delivery_save_base_path(string $tenantDir, int $client): string
{
    return '../../../' . $tenantDir . '/output/reports/' . $client . '/';
}

function delivery_save_rel_prefix(int $client): string
{
    return 'output/reports/' . $client . '/';
}

function delivery_save_record_exists(int $client, string $file, string $reps): bool
{
    $stmt = $GLOBALS['con']->prepare("SELECT `id` FROM `delivery_save` WHERE `cid`=? AND `files`=? AND `reps`=? LIMIT 1");
    if (!$stmt) {
        enrep_fail(500, 'Unable to save delivery file');
    }
    $stmt->bind_param('iss', $client, $file, $reps);
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();
    return $res && $res->num_rows > 0;
}

function delivery_save_insert_record(int $client, string $file, string $reps): void
{
    if (delivery_save_record_exists($client, $file, $reps)) {
        return;
    }

    $stmt = $GLOBALS['con']->prepare("INSERT INTO `delivery_save` VALUES('',?,?,?)");
    if (!$stmt) {
        enrep_fail(500, 'Unable to save delivery file');
    }
    $stmt->bind_param('iss', $client, $file, $reps);
    if (!$stmt->execute()) {
        $stmt->close();
        enrep_fail(500, 'Unable to save delivery file');
    }
    $stmt->close();
}

switch ($fcn) {
    default:
        break;

    case 'save':
        $files = json_decode(enrep_request_string('files', '[]', 1000000), true);
        if (!is_array($files)) {
            enrep_fail(400, 'Invalid files');
        }

        $base = delivery_save_base_path($tenantDir, $client);
        $savedDir = $base . 'saved/';
        $savedRelDir = delivery_save_rel_prefix($client) . 'saved/';
        if (!is_dir($savedDir)) {
            mkdir($savedDir, 0775, true);
        }

        foreach ($files as $file) {
            $file = enrep_safe_filename((string)$file);
            $pathParts = pathinfo($file);
            $ext = enrep_safe_filename((string)($pathParts['extension'] ?? ''));
            $source = $base . $file;
            $dest = $savedDir . $file;

            if (!is_file($source)) {
                continue;
            }

            copy($source, $dest);

            $customName = enrep_request_string('name', '', 120);
            if ($customName !== '') {
                $customName = enrep_safe_filename(str_replace(' ', '_', $customName));
                $targetFile = $customName . '.' . $ext;
                $target = $savedDir . $targetFile;
                rename($dest, $target);
                $savedRel = $savedRelDir . $targetFile;
                delivery_save_insert_record($client, $savedRel, $reps);
                echo "saved|" . $customName . "|" . $savedRel . "|" . $savedRelDir;
            } else {
                $savedRel = $savedRelDir . $file;
                delivery_save_insert_record($client, $savedRel, $reps);
                echo "saved|" . $file . "|" . $savedRel . "|" . $savedRelDir;
            }
        }
        break;

    case 'delete':
        $fileRel = enrep_safe_relative_path(enrep_request_string('files', '', 500), false);
        $allowedPrefix = delivery_save_rel_prefix($client);
        if (strpos($fileRel, $allowedPrefix) !== 0) {
            enrep_fail(400, 'Invalid file');
        }

        $stmt = $GLOBALS['con']->prepare("DELETE FROM `delivery_save` WHERE `cid`=? AND `files`=? AND `reps`=?");
        if (!$stmt) {
            enrep_fail(500, 'Unable to delete delivery file');
        }
        $stmt->bind_param('iss', $client, $fileRel, $reps);
        $stmt->execute();
        $stmt->close();

        $path = '../../../' . $tenantDir . '/' . $fileRel;
        if (is_file($path)) {
            unlink($path);
        }
        echo "removed";
        break;

    case 'rename':
        $file = enrep_safe_filename(enrep_request_string('file', '', 255));
        $newName = enrep_safe_filename(str_replace(' ', '_', enrep_request_string('newName', '', 120)));
        $base = delivery_save_base_path($tenantDir, $client);
        $source = $base . $file;
        $newPath = $base . $newName . '.zip';
        $link = delivery_save_rel_prefix($client) . $newName;

        if (!is_file($source)) {
            enrep_fail(400, 'Invalid file');
        }

        rename($source, $newPath);
        echo "renamed|" . $newName . "|" . $link;
        break;
}
