<?php
require_once __DIR__ . '/db.php';

// Helper function to log reporter activity
function logReporterAction($pdo, $action, $uniqueKey = null, $details = null) {
    try {
        $stmt = $pdo->prepare("
            INSERT INTO reporter_log (action, unique_key, details)
            VALUES (:action, :unique_key, :details)
        ");
        $stmt->execute([
            'action' => $action,
            'unique_key' => $uniqueKey,
            'details' => $details
        ]);
    } catch (Exception $e) {
        // Silently fail - logging should not break upload
    }
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_FILES['zipfile'])) {
    http_response_code(400);
    echo "ERROR: No file uploaded";
    exit;
}

$file = $_FILES['zipfile'];
if ($file['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo "ERROR: Upload error code " . $file['error'];
    exit;
}

$filename = basename($file['name']);

// Ověř, že jde o ZIP soubor
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);

if ($mimeType !== 'application/zip' && !preg_match('/\.zip$/i', $filename)) {
    http_response_code(400);
    echo "ERROR: File must be a ZIP archive";
    exit;
}

// Vytvoř dočasný adresář pro rozbalení
$tempDir = sys_get_temp_dir() . '/upload_ctrader_' . uniqid();
if (!mkdir($tempDir, 0777, true)) {
    http_response_code(500);
    echo "ERROR: Failed to create temp directory";
    exit;
}

// Rozbal ZIP
$zip = new ZipArchive();
if ($zip->open($file['tmp_name']) !== true) {
    http_response_code(400);
    echo "ERROR: Failed to open ZIP file";
    rmdir($tempDir);
    exit;
}

$zip->extractTo($tempDir);
$zip->close();

// Připojení k databázi
try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
    http_response_code(500);
    echo "ERROR: DB connection failed - " . $e->getMessage();
    cleanupTempDir($tempDir);
    exit;
}

// Zpracuj všechny soubory v ZIPu
$results = [];
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($tempDir, RecursiveDirectoryIterator::SKIP_DOTS),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $fileInfo) {
    if ($fileInfo->isFile()) {
        $result = processFile($fileInfo->getPathname(), $fileInfo->getFilename(), $pdo);
        $results[] = $result;
    }
}

// Vyčisti dočasný adresář
cleanupTempDir($tempDir);

// Zkontroluj výsledky
$successCount = 0;
$errorCount = 0;
$errorMessages = [];

foreach ($results as $result) {
    if (strpos(strtolower($result), 'ok') !== false) {
        $successCount++;
    } else {
        $errorCount++;
        $errorMessages[] = $result;
    }
}

if ($errorCount > 0) {
    http_response_code(207); // Multi-Status
    echo "Processed: $successCount OK, $errorCount errors\n";
    echo "Errors:\n" . implode("\n", $errorMessages);
} else {
    echo "ok - processed $successCount files";
}

// ========================================
// Funkce pro zpracování jednoho souboru
// ========================================
function processFile($filePath, $filename, $pdo) {
    // Parsování názvu souboru - podporuje dva formáty (pouze CSV):
    //
    // Formát 1: {account_id}_{label}_{type}.csv[.gz]
    //   10573284_MRDCA_EURJPY_Hour_LongOnly_ping.csv.gz
    //   10573284_MRDCA_EURJPY_Hour_LongOnly_log_backtest.csv
    //   10573284_MRDCA_EURJPY_Hour_LongOnly_trades_20251029_153805.csv.gz
    //   → account_number = "10573284", label = "MRDCA_EURJPY_Hour_LongOnly"
    //
    // Formát 2: {account_id}_{label}_{timestamp}_{type}.csv[.gz]
    //   10573284_MRDCA_NZDUSD_Hour_LongOnly_20251121_081003_log_backtest.csv
    //   10573284_MRDCA_NZDUSD_Hour_LongOnly_20251121_081003_ping.csv.gz
    //   → account_number = "10573284", label = "MRDCA_NZDUSD_Hour_LongOnly" (timestamp odstraněn)

    $account_number = null;
    $label = null;
    $type = null;
    $log_type = null;

    // Zkus formát 2 první (s timestampem před typem): {account_id}_{label}_{timestamp}_{type}.csv
    if (preg_match('/^([a-zA-Z0-9]+)_(.+?)_(\d{8}_\d{6})_(ping|log_backtest|log_live|trades|equity)\.csv(?:\.gz)?$/i', $filename, $matches)) {
        $account_number = $matches[1]; // Account/wallet ID
        $label = $matches[2];
        // $matches[3] je timestamp - přeskočíme
        $type_keyword = $matches[4];
    }
    // Zkus formát 1: {account_id}_{label}_{type}.csv (bez timestampu, nebo s timestampem za typem)
    elseif (preg_match('/^([a-zA-Z0-9]+)_(.+?)_(ping|log_backtest|log_live|trades|equity)(?:_\d+_\d+)?\.csv(?:\.gz)?$/i', $filename, $matches)) {
        $account_number = $matches[1]; // Account/wallet ID
        $label = $matches[2];
        $type_keyword = $matches[3];
    }
    else {
        return "SKIP: Invalid filename format (only CSV supported): $filename";
    }

    // Odstranění timestampu z konce labelu (formát YYYYMMDD_HHMMSS)
    $label = preg_replace('/_\d{8}_\d{6}$/', '', $label);

    // Určení typu (společné pro oba formáty)
    $type_keyword = strtolower($type_keyword);

    // Určení typu
    if ($type_keyword === 'ping') {
        $type = 'ping';
    } elseif ($type_keyword === 'log_backtest' || $type_keyword === 'log_live') {
        $type = 'log';
        $log_type = str_replace('log_', '', $type_keyword); // Extrahuj "backtest" nebo "live"
    } elseif ($type_keyword === 'trades') {
        $type = 'trades';
    } elseif ($type_keyword === 'equity') {
        $type = 'equity';
    } else {
        return "ERROR: Unknown type in filename: $filename";
    }

    // Dekomprese (pokud je .gz)
    $content = file_get_contents($filePath);
    if (substr($filename, -3) === '.gz') {
        $decompressed = @gzdecode($content);
        if ($decompressed === false) {
            return "ERROR: Failed to decompress: $filename";
        }
        $content = $decompressed;
    }

    try {
        if ($type === 'ping') {
            // Ping: použij serverový čas (jako watchdog v reporter.php)
            // Jeden záznam per account_number+label, aktualizuje se při každém pingu
            $serverTime = date('Y-m-d H:i:s');
            $stmt = $pdo->prepare("
                INSERT INTO strategy_ping (account_number, label, time_ping)
                VALUES (?, ?, ?)
                ON DUPLICATE KEY UPDATE time_ping = VALUES(time_ping)
            ");
            $stmt->execute([$account_number, $label, $serverTime]);
            logReporterAction($pdo, 'strategy_ping', $account_number, "label=$label");
            return "ok - ping updated ($filename)";

        } elseif ($type === 'log') {
            // Log: batch INSERT pro lepší výkon
            $lines = explode("\n", trim($content));
            $validLines = [];
            foreach ($lines as $line) {
                $line = trim($line);
                if (!empty($line)) {
                    $validLines[] = $line;
                }
            }

            if (empty($validLines)) {
                return "ok - log: 0 lines ($filename)";
            }

            // Batch INSERT - max 500 řádků najednou
            $batchSize = 500;
            $inserted = 0;

            foreach (array_chunk($validLines, $batchSize) as $batch) {
                $placeholders = [];
                $values = [];
                foreach ($batch as $line) {
                    $placeholders[] = "(?, ?, ?, ?)";
                    $values[] = $account_number;
                    $values[] = $label;
                    $values[] = $log_type;
                    $values[] = $line;
                }

                $sql = "INSERT INTO strategy_logs (account_number, label, log_type, log_content) VALUES " . implode(", ", $placeholders);
                $stmt = $pdo->prepare($sql);
                $stmt->execute($values);
                $inserted += count($batch);
            }

            return "ok - log: $inserted lines ($filename)";

        } elseif ($type === 'trades' || $type === 'equity') {
            // Trades/Equity: uložit jako soubor (dekomprimovaný obsah)
            $uploadDir = __DIR__ . '/backtests_' . $type . '/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }

            // Ulož dekomprimovaný soubor (bez .gz přípony)
            $saveName = str_replace('.gz', '', $filename);
            $safeName = preg_replace('/[^a-zA-Z0-9_\.\-]/', '_', $saveName);

            if (file_put_contents($uploadDir . $safeName, $content) !== false) {
                return "ok - saved: $type ($filename)";
            } else {
                return "ERROR: Failed to save file: $filename";
            }
        } else {
            return "ERROR: Unknown type: $type ($filename)";
        }

    } catch (PDOException $e) {
        return "ERROR: DB error for $filename - " . $e->getMessage();
    }
}

// ========================================
// Funkce pro vyčištění dočasného adresáře
// ========================================
function cleanupTempDir($dir) {
    if (!is_dir($dir)) {
        return;
    }

    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::CHILD_FIRST
    );

    foreach ($files as $fileInfo) {
        if ($fileInfo->isDir()) {
            rmdir($fileInfo->getRealPath());
        } else {
            unlink($fileInfo->getRealPath());
        }
    }

    rmdir($dir);
}
?>
