<?php
header('Content-Type: text/plain');
ini_set('display_errors', 1);
error_reporting(E_ALL);

$chatDir = 'data/chats/';
echo "Checking directory: $chatDir\n";

// 1. Check/Create Directory
if (!file_exists($chatDir)) {
    echo "Directory does not exist. Attempting to create...\n";
    if (mkdir($chatDir, 0777, true)) {
        echo "Directory created successfully.\n";
    } else {
        echo "FAILED to create directory. Check permissions.\n";
        exit;
    }
} else {
    echo "Directory exists.\n";
}

// 2. Check Writability
if (is_writable($chatDir)) {
    echo "Directory is writable.\n";
} else {
    echo "Directory is NOT writable. Attempting chmod...\n";
    if (chmod($chatDir, 0777)) {
        echo "chmod successful.\n";
    } else {
        echo "FAILED to chmod. PHP process user: " . get_current_user() . "\n";
    }
}

// 3. Test Write
$testFile = $chatDir . 'test_write_' . time() . '.json';
$data = json_encode(['test' => 'success', 'timestamp' => time()]);

if (file_put_contents($testFile, $data)) {
    echo "Successfully wrote test file: $testFile\n";

    // 4. Test Read
    $readBack = file_get_contents($testFile);
    echo "Read back content: $readBack\n";

    // cleanup
    // unlink($testFile);
} else {
    echo "FAILED to write test file.\n";
    echo "Last error: " . print_r(error_get_last(), true) . "\n";
}

// 5. List Files
echo "\nListing files in $chatDir:\n";
$files = glob($chatDir . '*.json');
foreach ($files as $f) {
    echo " - " . basename($f) . " (" . filesize($f) . " bytes)\n";
}
