<?php
// Script de debug para identificar el problema exacto en la subida de cover (PostgreSQL)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Incluir CodeIgniter
define('BASEPATH', true);
require_once 'system/core/CodeIgniter.php';

// Simular la llamada al controlador
try {
    echo "<h2>Debug de Subida de Cover (PostgreSQL)</h2>";
    
    // 1. Verificar configuración de base de datos
    echo "<h3>1. Configuración de Base de Datos</h3>";
    $db_config = [
        'hostname' => 'localhost',
        'username' => 'postgres',
        'password' => '1234',
        'database' => 'db_chamba_produccion',
        'dbdriver' => 'postgres'
    ];
    
    try {
        $pdo = new PDO("pgsql:host={$db_config['hostname']};dbname={$db_config['database']}", 
                      $db_config['username'], $db_config['password']);
        echo "✅ Conexión a BD exitosa<br>";
    } catch (PDOException $e) {
        echo "❌ Error de conexión: " . $e->getMessage() . "<br>";
    }
    
    // 2. Verificar tabla y campo (PostgreSQL)
    echo "<h3>2. Estructura de Tabla</h3>";
    $stmt = $pdo->query("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'tbl_usuarios'");
    if ($stmt->rowCount() > 0) {
        echo "✅ Tabla tbl_usuarios existe<br>";
        
        $stmt = $pdo->query("SELECT column_name, data_type, is_nullable FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'tbl_usuarios' AND column_name = 'img_cover'");
        if ($stmt->rowCount() > 0) {
            echo "✅ Campo img_cover existe<br>";
            $column = $stmt->fetch(PDO::FETCH_ASSOC);
            echo "   - Tipo: " . $column['data_type'] . "<br>";
            echo "   - Null: " . $column['is_nullable'] . "<br>";
        } else {
            echo "❌ Campo img_cover NO existe<br>";
            
            // Mostrar campos existentes relacionados con imágenes
            echo "<br>Campos de imagen existentes:<br>";
            $stmt = $pdo->query("SELECT column_name, data_type FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'tbl_usuarios' AND (column_name LIKE '%img%' OR column_name LIKE '%image%') ORDER BY column_name");
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                echo "   - " . $row['column_name'] . ": " . $row['data_type'] . "<br>";
            }
        }
    } else {
        echo "❌ Tabla tbl_usuarios NO existe<br>";
        
        // Mostrar tablas disponibles
        echo "<br>Tablas disponibles:<br>";
        $stmt = $pdo->query("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' ORDER BY table_name LIMIT 10");
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo "   - " . $row['table_name'] . "<br>";
        }
    }
    
    // 3. Verificar directorios
    echo "<h3>3. Directorios de Upload</h3>";
    $upload_paths = [
        './uploads/',
        './uploads/community/',
        './uploads/community/covers/',
        './uploads/community/covers/thumbs/'
    ];
    
    foreach ($upload_paths as $path) {
        if (is_dir($path)) {
            echo "✅ $path existe (permisos: " . substr(sprintf('%o', fileperms($path)), -4) . ")<br>";
        } else {
            echo "❌ $path NO existe<br>";
        }
    }
    
    // 4. Verificar extensiones PHP
    echo "<h3>4. Extensiones PHP</h3>";
    $required_extensions = ['gd', 'mysqli', 'json'];
    foreach ($required_extensions as $ext) {
        if (extension_loaded($ext)) {
            echo "✅ Extensión $ext cargada<br>";
        } else {
            echo "❌ Extensión $ext NO cargada<br>";
        }
    }
    
    // 5. Verificar configuración de PHP
    echo "<h3>5. Configuración PHP</h3>";
    echo "upload_max_filesize: " . ini_get('upload_max_filesize') . "<br>";
    echo "post_max_size: " . ini_get('post_max_size') . "<br>";
    echo "max_execution_time: " . ini_get('max_execution_time') . "<br>";
    echo "memory_limit: " . ini_get('memory_limit') . "<br>";
    
    // 6. Probar el controlador directamente
    echo "<h3>6. Prueba del Controlador</h3>";
    echo "<form method='post' enctype='multipart/form-data' action='ajax/Comunidad_profile/update_cover'>";
    echo "<input type='hidden' name='user_id' value='1'>";
    echo "<input type='file' name='cover_image' required>";
    echo "<button type='submit'>Probar Subida</button>";
    echo "</form>";
    
    echo "<h3>7. Verificar Rutas</h3>";
    echo "Base URL: " . (function_exists('base_url') ? base_url() : 'No disponible') . "<br>";
    echo "SCRIPT_NAME: " . $_SERVER['SCRIPT_NAME'] . "<br>";
    echo "REQUEST_URI: " . $_SERVER['REQUEST_URI'] . "<br>";
    
} catch (Exception $e) {
    echo "❌ Error general: " . $e->getMessage() . "<br>";
    echo "Stack trace:<br><pre>" . $e->getTraceAsString() . "</pre>";
}
?>
