<?php
require_once dirname(__DIR__) . '/config.php';
require_once 'session_manager.php';

$sessionDetected = detectAndStartUserSession();

header('Content-Type: application/json');

if (!$sessionDetected || !isset($_SESSION['username']) || !isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    echo json_encode(['exists' => false, 'debug' => ['session_detected' => $sessionDetected, 'username' => $_SESSION['username'] ?? 'not_set']]);
    exit;
}

$username = $_SESSION['username'];
$userImagePath = "img/chart-img/{$username}/";
$uploadDir = IMG_DIR . "/chart-img/{$username}/";

if (!is_dir($uploadDir)) {
    echo json_encode(['exists' => false, 'debug' => ['dir_exists' => false, 'path' => $uploadDir]]);
    exit;
}

$files = glob($uploadDir . 'photo_*.{jpg,jpeg,png}', GLOB_BRACE);

if (!empty($files)) {
    $latestFile = array_reduce($files, function($latest, $file) {
        return (!$latest || filemtime($file) > filemtime($latest)) ? $file : $latest;
    });
    
    $relativePath = str_replace('../', '', $latestFile);
    echo json_encode([
        'exists' => true,
        'path' => $relativePath,
        'user' => $username
    ]);
} else {
    echo json_encode(['exists' => false, 'debug' => ['files_found' => count($files), 'search_path' => $uploadDir . 'photo_*']]);
}
?>