<?php
/**
 * Debug script to test paths and file writing
 */
error_reporting(E_ALL);
ini_set('display_errors', '1');

echo "<pre style='font-family: monospace; background: #1a1a2e; color: #0f0; padding: 20px;'>";
echo "=== FLOWBOT DCI v2 - PATH DEBUG ===\n\n";

// Load config
$configPath = dirname(__DIR__) . '/config/config.php';
echo "1. Config file path: {$configPath}\n";
echo "   Config exists: " . (file_exists($configPath) ? "YES ✓" : "NO ✗") . "\n\n";

if (file_exists($configPath)) {
    $config = require $configPath;

    echo "2. Configured paths:\n";
    foreach ($config['paths'] as $key => $path) {
        echo "   - {$key}: {$path}\n";
        echo "     Exists: " . (file_exists($path) ? "YES ✓" : "NO ✗");
        echo " | Is dir: " . (is_dir($path) ? "YES ✓" : "NO ✗");
        echo " | Writable: " . (is_writable($path) ? "YES ✓" : "NO ✗") . "\n";
    }

    echo "\n3. Temp folder test:\n";
    $tempPath = $config['paths']['temp'];
    echo "   Temp path: {$tempPath}\n";

    // Try to create temp if not exists
    if (!is_dir($tempPath)) {
        echo "   Temp does not exist. Attempting to create...\n";
        $result = @mkdir($tempPath, 0777, true);
        echo "   mkdir result: " . ($result ? "SUCCESS ✓" : "FAILED ✗") . "\n";
        if (!$result) {
            echo "   Error: " . (error_get_last()['message'] ?? 'Unknown') . "\n";
        }
    }

    // Test write
    $testFile = $tempPath . '/test_write_' . time() . '.txt';
    echo "\n4. Write test:\n";
    echo "   Test file: {$testFile}\n";

    $writeResult = @file_put_contents($testFile, 'Test content: ' . date('Y-m-d H:i:s'));
    echo "   Write result: " . ($writeResult !== false ? "SUCCESS ({$writeResult} bytes) ✓" : "FAILED ✗") . "\n";

    if ($writeResult === false) {
        $error = error_get_last();
        echo "   Error: " . ($error['message'] ?? 'Unknown') . "\n";
    } else {
        // Clean up
        @unlink($testFile);
        echo "   Cleanup: OK ✓\n";
    }

    // Test process folder creation
    echo "\n5. Process folder test:\n";
    $processId = 'test_' . uniqid();
    $processFolder = $tempPath . '/' . $processId . '/';
    echo "   Process folder: {$processFolder}\n";

    $mkdirResult = @mkdir($processFolder, 0755, true);
    echo "   mkdir result: " . ($mkdirResult ? "SUCCESS ✓" : "FAILED ✗") . "\n";

    if ($mkdirResult) {
        $testJson = $processFolder . $processId . '_progress.json';
        $jsonData = json_encode(['test' => true, 'time' => time()]);
        $jsonWrite = @file_put_contents($testJson, $jsonData);
        echo "   JSON write: " . ($jsonWrite !== false ? "SUCCESS ✓" : "FAILED ✗") . "\n";

        // Cleanup
        @unlink($testJson);
        @rmdir($processFolder);
        echo "   Cleanup: OK ✓\n";
    } else {
        $error = error_get_last();
        echo "   Error: " . ($error['message'] ?? 'Unknown') . "\n";
    }

    // Check .env loading
    echo "\n6. Environment loading:\n";
    echo "   .env loaded: " . ($GLOBALS['env_loaded'] ?? false ? "YES ✓" : "NO ✗") . "\n";
    if (!empty($GLOBALS['env_errors'])) {
        echo "   .env errors:\n";
        foreach ($GLOBALS['env_errors'] as $err) {
            echo "     - {$err}\n";
        }
    }

    // Database test
    echo "\n7. Database connection:\n";
    try {
        $dsn = sprintf(
            'mysql:host=%s;dbname=%s;charset=%s',
            $config['database']['host'],
            $config['database']['name'],
            $config['database']['charset']
        );
        $pdo = new PDO($dsn, $config['database']['user'], $config['database']['password'], [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        ]);
        echo "   Connection: SUCCESS ✓\n";
        $pdo = null;
    } catch (PDOException $e) {
        echo "   Connection: FAILED ✗\n";
        echo "   Error: " . $e->getMessage() . "\n";
    }
}

// Server info
echo "\n8. Server info:\n";
echo "   PHP user: " . get_current_user() . "\n";
echo "   PHP version: " . PHP_VERSION . "\n";
echo "   Document root: " . ($_SERVER['DOCUMENT_ROOT'] ?? 'N/A') . "\n";
echo "   Script filename: " . ($_SERVER['SCRIPT_FILENAME'] ?? 'N/A') . "\n";
echo "   __DIR__: " . __DIR__ . "\n";
echo "   dirname(__DIR__): " . dirname(__DIR__) . "\n";

// Check posix if available
if (function_exists('posix_getpwuid') && function_exists('posix_geteuid')) {
    $processUser = posix_getpwuid(posix_geteuid());
    echo "   Process user: " . ($processUser['name'] ?? 'Unknown') . "\n";
}

echo "\n=== END DEBUG ===\n";
echo "</pre>";
