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

try {
    $logFilePath = __DIR__ . '/../logs/php_errors.log';
    $uploadDirAbsolute = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'logo'; 
    $uploadDirRelativeForDb = '../uploads/logo'; 

    ini_set('log_errors', 1);
    ini_set('error_log', $logFilePath);

    $dbConnectionPath = __DIR__ . '/db_connection.php';
    if (file_exists($dbConnectionPath)) { require_once($dbConnectionPath); } 
    else { throw new Exception("ERROR CRITICO DB CONNECTION"); }
    if (!isset($pdo)) { throw new Exception("ERROR CRITICO PDO"); }
    
    require_once('image_optimizer.php'); 
    require_once '../files/guardiankey.php';

    if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_FILES['logo_upload'])) {
        throw new Exception("METODO NO PERMITIDO");
    }
    
    if (!is_dir($uploadDirAbsolute)) {
        if (!mkdir($uploadDirAbsolute, 0777, true)) {
             throw new Exception('ERROR DIRECTORIO SUBIDA');
        }
    } elseif (!is_writable($uploadDirAbsolute)) {
         throw new Exception('ERROR PERMISOS ESCRITURA');
    }

    $pdo->beginTransaction();

    $file = $_FILES['logo_upload'];
    
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $maxSize = 25 * 1024 * 1024; 
    if ($file['error'] !== UPLOAD_ERR_OK) { throw new Exception('ERROR AL SUBIR ARCHIVO'); }
    if (!in_array($file['type'], $allowedTypes)) { throw new Exception('TIPO DE ARCHIVO NO PERMITIDO'); }
    if ($file['size'] > $maxSize) { throw new Exception('ARCHIVO DEMASIADO GRANDE'); }

    $stmt_old = $pdo->query("SELECT id, logo_url FROM business_info WHERE id = 1 LIMIT 1");
    $currentRecord = $stmt_old->fetch(PDO::FETCH_ASSOC);
    $id = 1; 
    $old_logo_path_relative_from_db = null;
    if (!$currentRecord) { 
        $pdo->query("INSERT INTO business_info (id, company_name) VALUES (1, 'Mi Empresa (Temporal)') ON DUPLICATE KEY UPDATE id=id");
    } else {
        $old_logo_path_relative_from_db = $currentRecord['logo_url'];
    }

    if ($old_logo_path_relative_from_db && !filter_var($old_logo_path_relative_from_db, FILTER_VALIDATE_URL) && strpos($old_logo_path_relative_from_db, 'uploads/logo/') !== false) {
        $old_logo_path_absolute = dirname(__DIR__) . DIRECTORY_SEPARATOR . str_replace('../', '', $old_logo_path_relative_from_db);
        if (file_exists($old_logo_path_absolute) && is_file($old_logo_path_absolute)) {
            unlink($old_logo_path_absolute);
        }
    }
    
    $fileName = uniqid('logo_') . '.webp'; 
    $new_logo_path_relative_for_db = $uploadDirRelativeForDb . '/' . $fileName; 
    $new_logo_path_absolute = $uploadDirAbsolute . DIRECTORY_SEPARATOR . $fileName; 

    $maxWidth = 500; 
    $quality = 85;  

    $success = optimizeAndSaveImage($file['tmp_name'], $new_logo_path_absolute, $maxWidth, $quality);

    if (!$success) {
        $imageInfo = getimagesize($file['tmp_name']);
        if ($imageInfo && $imageInfo[2] === IMAGETYPE_GIF) {
            $fileName = uniqid('logo_') . '.' . pathinfo($file['name'], PATHINFO_EXTENSION); 
            $new_logo_path_relative_for_db = $uploadDirRelativeForDb . '/' . $fileName;
            $new_logo_path_absolute = $uploadDirAbsolute . DIRECTORY_SEPARATOR . $fileName;
            if (!move_uploaded_file($file['tmp_name'], $new_logo_path_absolute)) {
                 throw new Exception('ERROR CRITICO MOVE UPLOADED FILE');
            }
        } else {
            throw new Exception('ERROR AL OPTIMIZAR LOGO');
        }
    } else {
         chmod($new_logo_path_absolute, 0664); 
    }

    $sql_update = "UPDATE business_info SET logo_url=? WHERE id=?";
    $stmt_update = $pdo->prepare($sql_update);
    if (!$stmt_update->execute([$new_logo_path_relative_for_db, $id])) { 
         throw new Exception('ERROR DB AL ACTUALIZAR URL');
    }

    $pdo->commit();
    
    $response = [
        'success' => true,
        'message' => 'LOGO ACTUALIZADO',
        'logo_url' => $new_logo_path_relative_for_db 
    ];

} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); }
    http_response_code(500);
    $response = ['success' => false, 'message' => strtoupper($e->getMessage())];
}

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