<?php
ob_start(); 
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'ERROR DESCONOCIDO'];

try {
    ini_set('display_errors', 0); 
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../../logs/php_errors.log');
    error_reporting(E_ALL);

    // Inicialización Centralizada
    require_once __DIR__ . '/../core/api.php';
    require_once __DIR__ . '/../core/image_optimizer.php'; 

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('METODO NO PERMITIDO');
    }

    if (!isset($_FILES['profile_photo_upload']) || $_FILES['profile_photo_upload']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('NO SE RECIBIO EL ARCHIVO O HUBO UN ERROR');
    }

    $user_id = 1; 
    $uploadDir = '../uploads/profile/'; 
    $dbPathPrefix = 'uploads/profile/'; 

    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $stmt = $pdo->prepare("SELECT profile_photo_url FROM users WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $oldPhotoUrl = $stmt->fetchColumn();

    $fileInfo = pathinfo($_FILES['profile_photo_upload']['name']);
    $newFileName = 'profile_' . $user_id . '_' . uniqid() . '.webp'; 
    $destinationPath = $uploadDir . $newFileName;
    $sourcePath = $_FILES['profile_photo_upload']['tmp_name'];

    $optimized = optimizeAndSaveImage($sourcePath, $destinationPath, 800, 80);

    if (!$optimized) {
        throw new Exception('FALLO LA OPTIMIZACION DE IMAGEN');
    }

    $newDbUrl = $dbPathPrefix . $newFileName;
    $updateStmt = $pdo->prepare("UPDATE users SET profile_photo_url = ? WHERE user_id = ?");
    $updateStmt->execute([$newDbUrl, $user_id]);

    if ($oldPhotoUrl && $oldPhotoUrl !== 'img/default-logo.png') {
        $oldFilePath = '../' . $oldPhotoUrl; 
        
        if (file_exists($oldFilePath) && is_file($oldFilePath) && strpos($oldFilePath, 'uploads/') !== false) {
            unlink($oldFilePath);
        }
    }

    $response['success'] = true;
    $response['message'] = 'FOTO ACTUALIZADA CORRECTAMENTE';
    $response['photo_url'] = $newDbUrl;

} catch (Exception $e) {
    error_log("Error en upload: " . $e->getMessage());
    $response['message'] = $e->getMessage();
}

if (ob_get_level() > 0) { ob_end_clean(); } 
echo json_encode($response);
exit;
?>