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

try {
    session_start();
    require_once('image_optimizer.php'); 

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

    include_once 'db_connection.php'; 
    require_once '../files/guardiankey.php';

    $user_id = $_SESSION['user_id'] ?? null;
    if (!$user_id) {
        throw new Exception('SESION NO VALIDA');
    }

    if (!isset($_FILES['profile_photo_upload']) || $_FILES['profile_photo_upload']['error'] !== UPLOAD_ERR_OK) {
        $upload_error = $_FILES['profile_photo_upload']['error'] ?? UPLOAD_ERR_NO_FILE;
        $error_message = 'ERROR AL SUBIR ARCHIVO';
        switch ($upload_error) {
            case UPLOAD_ERR_INI_SIZE:
            case UPLOAD_ERR_FORM_SIZE: $error_message = 'ARCHIVO DEMASIADO GRANDE'; break;
            case UPLOAD_ERR_PARTIAL: $error_message = 'SUBIDA PARCIAL'; break;
            case UPLOAD_ERR_NO_FILE: $error_message = 'NO SE SUBIO ARCHIVO'; break;
        }
        throw new Exception($error_message);
    }

    $file = $_FILES['profile_photo_upload'];
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']; 
    $max_size = 12 * 1024 * 1024; 

    if (!in_array($file['type'], $allowed_types)) {
        throw new Exception('TIPO DE ARCHIVO NO PERMITIDO');
    } 
    if ($file['size'] > $max_size) {
        throw new Exception('ARCHIVO DEMASIADO GRANDE');
    } 
        
    $upload_dir_absolute = __DIR__ . '/../uploads/profile/'; 
    $upload_dir_relative_for_db = 'uploads/profile/'; 

    if (!is_dir($upload_dir_absolute)) {
        if (!mkdir($upload_dir_absolute, 0777, true)) {
             throw new Exception('ERROR DIRECTORIO SUBIDA');
        }
    }

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

    if ($old_photo_path_relative && !filter_var($old_photo_path_relative, FILTER_VALIDATE_URL) && strpos($old_photo_path_relative, 'uploads/profile/') !== false) {
        $old_photo_path_absolute = __DIR__ . '/../' . $old_photo_path_relative; 
        if (file_exists($old_photo_path_absolute) && is_file($old_photo_path_absolute)) {
             if (!unlink($old_photo_path_absolute)) error_log("Advertencia: No se pudo borrar foto antigua: " . $old_photo_path_absolute);
             else error_log("Foto antigua borrada: " . $old_photo_path_absolute);
        }
    }

    $new_filename = 'profile_' . $user_id . '_' . uniqid() . '.webp'; 
    $destination_path_absolute = $upload_dir_absolute . $new_filename; 
    $relative_path_for_db = $upload_dir_relative_for_db . $new_filename; 

    $maxWidth = 300; 
    $quality = 80;   

    $success_optimizing = optimizeAndSaveImage($file['tmp_name'], $destination_path_absolute, $maxWidth, $quality);

    if (!$success_optimizing) {
        $imageInfo = getimagesize($file['tmp_name']);
        if ($imageInfo && $imageInfo[2] === IMAGETYPE_GIF) {
            $file_extension = pathinfo($file['name'], PATHINFO_EXTENSION);
            $new_filename = 'profile_' . $user_id . '_' . uniqid() . '.' . strtolower($file_extension);
            $destination_path_absolute = $upload_dir_absolute . $new_filename;
            $relative_path_for_db = $upload_dir_relative_for_db . $new_filename;
            if (!move_uploaded_file($file['tmp_name'], $destination_path_absolute)) {
                throw new Exception('ERROR AL MOVER GIF');
            }
        } else {
             throw new Exception('ERROR AL OPTIMIZAR FOTO');
        }
    } else {
         chmod($destination_path_absolute, 0664); 
    }

    $stmt_update = $pdo->prepare("UPDATE users SET profile_photo_url = ? WHERE user_id = ?");
    $stmt_update->execute([$relative_path_for_db, $user_id]);
    

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

} catch (PDOException $e) {
    error_log("Error PDO en profile-photo-upload.php: " . $e->getMessage());
    $response['message'] = 'ERROR DE BASE DE DATOS';
} catch (Exception $e) {
    error_log("Error general en profile-photo-upload.php: " . $e->getMessage());
    $response['message'] = strtoupper($e->getMessage()); 
}

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