<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: X-Deploy-Key, Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

$sharedConfig = [];
$sharedConfigPath = '/usr/home/dombek92/private/daako-config.php';
if (@is_readable($sharedConfigPath)) {
    $loadedSharedConfig = require $sharedConfigPath;
    if (is_array($loadedSharedConfig)) $sharedConfig = $loadedSharedConfig;
}
$DEPLOY_KEY = trim((string)($sharedConfig['DAAKO_FLOW_DEPLOY_KEY'] ?? '')) ?: (getenv('DAAKO_FLOW_DEPLOY_KEY') ?: '');
$privateConfig = __DIR__ . '/.htaccess';
if ($DEPLOY_KEY === '' && is_readable($privateConfig)) {
    $config = file_get_contents($privateConfig);
    if (preg_match('/^\s*SetEnv\s+DAAKO_FLOW_DEPLOY_KEY\s+(?:"([^"]*)"|\'([^\']*)\'|(\S+))/im', $config, $m)) {
        $DEPLOY_KEY = trim($m[1] !== '' ? $m[1] : ($m[2] !== '' ? $m[2] : $m[3]));
    }
}
// Optional subdirectory for the upload (e.g. "360studio" -> releases/360studio/).
// Validated strictly to [a-z0-9_-]+ so it can never escape the releases folder.
$SUBDIR = '';
$subdirRaw = basename(trim((string)($_POST['subdir'] ?? $_GET['subdir'] ?? '')));
if ($subdirRaw !== '' && preg_match('/^[a-z0-9_-]{1,32}$/', $subdirRaw)) {
    $SUBDIR = '/' . $subdirRaw;
}

$UPLOAD_DIR = __DIR__ . '/releases' . $SUBDIR . '/';
$BASE_URL = 'https://files.daako.pl/releases' . $SUBDIR . '/';
$MAX_SIZE = 150 * 1024 * 1024;

$INSTALLER_PREFIXES = ['Daako Flow Setup ', 'Daako 360 Studio Setup '];

function cleanupOldInstallers($uploadDir, $currentInstaller)
{
    $result = [
        'enabled' => true,
        'currentInstaller' => $currentInstaller,
        'deleted' => [],
        'skipped' => [],
        'failed' => [],
    ];

    $valid = false;
    foreach ($GLOBALS['INSTALLER_PREFIXES'] as $prefix) {
        if (strpos($currentInstaller, $prefix) === 0 && substr($currentInstaller, -4) === '.exe') {
            $valid = true;
            break;
        }
    }
    if (!$valid) {
        $result['failed'][] = 'Invalid current installer name';
        return $result;
    }

    $keep = [
        $currentInstaller => true,
        $currentInstaller . '.blockmap' => true,
    ];

    $patterns = [];
    foreach ($GLOBALS['INSTALLER_PREFIXES'] as $prefix) {
        $escaped = preg_quote($prefix, '/');
        $patterns[] = $uploadDir . $escaped . '*.exe';
        $patterns[] = $uploadDir . $escaped . '*.exe.blockmap';
    }

    foreach ($patterns as $pattern) {
        foreach (glob($pattern) ?: [] as $path) {
            if (!is_file($path)) {
                continue;
            }

            $name = basename($path);
            if (isset($keep[$name])) {
                $result['skipped'][] = $name;
                continue;
            }

            if (unlink($path)) {
                $result['deleted'][] = $name;
            } else {
                $result['failed'][] = $name;
            }
        }
    }

    return $result;
}

$headers = getallheaders();
$key = $headers['X-Deploy-Key'] ?? $headers['x-deploy-key'] ?? '';
if ($DEPLOY_KEY === '' || !hash_equals($DEPLOY_KEY, $key)) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'Invalid API key']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'Method not allowed']);
    exit;
}

if (!isset($_FILES['file'])) {
    echo json_encode(['ok' => false, 'error' => 'No file uploaded']);
    exit;
}

$f = $_FILES['file'];
if ($f['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['ok' => false, 'error' => 'Upload error code: ' . $f['error']]);
    exit;
}
if ($f['size'] > $MAX_SIZE) {
    echo json_encode(['ok' => false, 'error' => 'File too large (max 150 MB)']);
    exit;
}

if (!is_dir($UPLOAD_DIR)) {
    mkdir($UPLOAD_DIR, 0755, true);
}

$storedName = basename($f['name']);
$dest = $UPLOAD_DIR . $storedName;

if (file_exists($dest) && is_file($dest)) {
    unlink($dest);
}

if (!move_uploaded_file($f['tmp_name'], $dest)) {
    echo json_encode(['ok' => false, 'error' => 'Failed to save file']);
    exit;
}

$cleanup = null;
if (($_POST['cleanupOldInstallers'] ?? '') === '1') {
    $currentInstaller = basename($_POST['currentInstaller'] ?? '');
    $cleanup = cleanupOldInstallers($UPLOAD_DIR, $currentInstaller);
}

echo json_encode([
    'ok' => true,
    'url' => $BASE_URL . rawurlencode($storedName),
    'storedName' => $storedName,
    'size' => $f['size'],
    'cleanup' => $cleanup,
]);
