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

// Start session detection
$sessionDetected = detectAndStartUserSession();

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// Comprehensive debug info
$debugInfo = [
    'method' => $_SERVER['REQUEST_METHOD'],
    'session_detected' => $sessionDetected,
    'session_id' => session_id(),
    'session_name' => session_name(),
    'session_username' => $_SESSION['username'] ?? 'not_set',
    'logged_in' => $_SESSION['logged_in'] ?? 'not_set',
    'files_received' => isset($_FILES['image']),
    'php_upload_errors' => [
        'max_file_size' => ini_get('upload_max_filesize'),
        'max_post_size' => ini_get('post_max_size'),
        'file_uploads' => ini_get('file_uploads')
    ]
];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Method not allowed', 'debug' => $debugInfo]);
    exit;
}

if (!isset($_FILES['image'])) {
    echo json_encode(['success' => false, 'message' => 'No image file provided', 'debug' => $debugInfo]);
    exit;
}

$file = $_FILES['image'];
$debugInfo['file_info'] = [
    'name' => $file['name'],
    'type' => $file['type'],
    'size' => $file['size'],
    'error' => $file['error'],
    'tmp_name' => $file['tmp_name'],
    'tmp_exists' => file_exists($file['tmp_name'])
];

// Authentication check
if (!$sessionDetected || !isset($_SESSION['username']) || !isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    echo json_encode(['success' => false, 'message' => 'User not authenticated', 'debug' => $debugInfo]);
    exit;
}

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

$debugInfo['paths'] = [
    'username' => $username,
    'user_image_path' => $userImagePath,
    'upload_dir' => $uploadDir,
    'upload_dir_absolute' => realpath($uploadDir) ?: 'not_exists'
];

// Create directory
if (!is_dir($uploadDir)) {
    $created = mkdir($uploadDir, 0777, true);
    $debugInfo['dir_created'] = $created;
    if (!$created) {
        echo json_encode(['success' => false, 'message' => 'Failed to create directory', 'debug' => $debugInfo]);
        exit;
    }
}

$debugInfo['dir_status'] = [
    'exists' => is_dir($uploadDir),
    'readable' => is_readable($uploadDir),
    'writable' => is_writable($uploadDir),
    'permissions' => substr(sprintf('%o', fileperms($uploadDir)), -4)
];

// File validation
$allowedTypes = ['image/jpeg', 'image/jpg', 'image/png'];
if (!in_array($file['type'], $allowedTypes)) {
    echo json_encode(['success' => false, 'message' => 'Invalid file type', 'debug' => $debugInfo]);
    exit;
}

if ($file['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['success' => false, 'message' => 'Upload error: ' . $file['error'], 'debug' => $debugInfo]);
    exit;
}

// Generate filename
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = 'photo_' . date('Y-m-d_H-i-s') . '.' . $extension;
$targetPath = $uploadDir . $filename;

$debugInfo['upload_attempt'] = [
    'filename' => $filename,
    'target_path' => $targetPath,
    'source_exists' => file_exists($file['tmp_name'])
];

// Attempt upload
if (move_uploaded_file($file['tmp_name'], $targetPath)) {
    $debugInfo['upload_result'] = [
        'move_successful' => true,
        'file_exists_after' => file_exists($targetPath),
        'file_size' => file_exists($targetPath) ? filesize($targetPath) : 0
    ];
    
    if (file_exists($targetPath)) {
        echo json_encode([
            'success' => true,
            'message' => 'Upload successful',
            'filename' => $filename,
            'path' => $userImagePath . $filename,
            'user' => $username,
            'debug' => $debugInfo
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'File moved but not found', 'debug' => $debugInfo]);
    }
} else {
    $debugInfo['upload_result'] = ['move_successful' => false];
    echo json_encode(['success' => false, 'message' => 'Failed to move uploaded file', 'debug' => $debugInfo]);
}
?>