<?php
// src/controllers/ProfileController.php
class ProfileController {
    public static function view($db) {
        require_login();
        $uid = $_SESSION['user']['id'];
        
        // Obtener datos del usuario
        $selCols = ["id", "username", "email", "birth_date", "created_at", "bio", "avatar_url"];
        try {
            $cols = $db->query("SHOW COLUMNS FROM users")->fetchAll(PDO::FETCH_COLUMN, 0);
            $want = ["gender", "country_code", "country", "region", "city"];
            foreach ($want as $w) { 
                if (in_array($w, $cols, true)) { 
                    $selCols[] = $w; 
                } 
            }
        } catch (Throwable $t) {
            error_log("Error obteniendo columnas: " . $t->getMessage());
        }
        
        $sql = "SELECT " . implode(", ", array_map(fn($c) => "`$c`", $selCols)) . " FROM users WHERE id = ?";
        $user_stmt = $db->prepare($sql);
        $user_stmt->execute([$uid]);
        $user = $user_stmt->fetch();
        
        if (!$user) {
            flash('error', 'Usuario no encontrado');
            redirect('dashboard');
            return;
        }
        
        // Estadísticas
        $stats = $db->prepare("
            SELECT 
                (SELECT COUNT(*) FROM posts WHERE author_id = ?) as post_count,
                (SELECT COUNT(*) FROM friends WHERE (user1_id = ? OR user2_id = ?) AND status = 'accepted') as friend_count,
                (SELECT COUNT(*) FROM likes WHERE user_id = ?) as like_count,
                (SELECT COUNT(*) FROM comments WHERE user_id = ?) as comment_count
        ");
        $stats->execute([$uid, $uid, $uid, $uid, $uid]);
        $user_stats = $stats->fetch();
        
        // Posts
        $posts = $db->prepare("
            SELECT p.*, ph.url, 
                   (SELECT COUNT(*) FROM likes WHERE post_id = p.id) as likes,
                   (SELECT COUNT(*) FROM comments WHERE post_id = p.id) as comments
            FROM posts p
            LEFT JOIN photos ph ON ph.post_id = p.id
            WHERE p.author_id = ?
            ORDER BY p.created_at DESC
            LIMIT 6
        ");
        $posts->execute([$uid]);
        
        view('profile/view', [
            'user' => $user,
            'stats' => $user_stats,
            'posts' => $posts->fetchAll()
        ]);
    }
    
    public static function update($db) {
        require_login();
        $uid = $_SESSION['user']['id'];
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            validate_csrf();
            
            $username = trim($_POST['username'] ?? '');
            $bio = trim($_POST['bio'] ?? '');
            $gender = trim($_POST['gender'] ?? '');
            $country = trim($_POST['country'] ?? '');
            $region  = trim($_POST['region'] ?? '');
            $city    = trim($_POST['city'] ?? '');
            
            if (empty($username)) {
                flash('error', 'El nombre de usuario es requerido');
                redirect('profile');
                return;
            }
            
            $check = $db->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
            $check->execute([$username, $uid]);
            
            if ($check->fetch()) {
                flash('error', 'El nombre de usuario ya está en uso');
                redirect('profile');
                return;
            }
            
            $set = ["username = ?", "bio = ?", "updated_at = NOW()"];
            $vals = [$username, $bio];
            try {
                $cols = $db->query("SHOW COLUMNS FROM users")->fetchAll(PDO::FETCH_COLUMN, 0);
                $have = fn($c) => in_array($c, $cols, true);
                if ($have("gender"))       { $set[] = "gender = ?";       $vals[] = $gender; }
                if ($have("country_code")) { $set[] = "country_code = ?"; $vals[] = $country; }
                elseif ($have("country"))  { $set[] = "country = ?";      $vals[] = $country; }
                if ($have("region"))       { $set[] = "region = ?";       $vals[] = $region; }
                if ($have("city"))         { $set[] = "city = ?";         $vals[] = $city; }
            } catch (Throwable $t) {
                error_log("Error actualizando perfil: " . $t->getMessage());
            }
            
            $sql = "UPDATE users SET " . implode(", ", $set) . " WHERE id = ?";
            $update = $db->prepare($sql);
            $vals[] = $uid;
            
            if ($update->execute($vals)) {
                $_SESSION['user']['username'] = $username;
                $_SESSION['user']['bio'] = $bio;
                $_SESSION['user']['gender'] = $gender;
                $_SESSION['user']['country_code'] = $country;
                $_SESSION['user']['region'] = $region;
                $_SESSION['user']['city'] = $city;
                
                flash('success', 'Perfil actualizado correctamente');
            } else {
                flash('error', 'Error al actualizar el perfil');
            }
            
            redirect('profile');
        }
    }
    
    public static function updateAvatar($db) {
        require_login();
        $uid = isset($_SESSION['user']['id']) ? (string)$_SESSION['user']['id'] : '';

        // Verificar CSRF
        if (function_exists('validate_csrf')) {
            try { 
                validate_csrf(); 
            } catch (Throwable $t) {
                if (!empty($_GET['ajax'])) {
                    header('Content-Type: application/json');
                    echo json_encode(['success' => false, 'message' => 'Error de seguridad (CSRF)']);
                    exit;
                }
                flash('error', 'Error de seguridad');
                redirect('./?r=profile');
                return;
            }
        }

        // DEBUG: Log para verificar que la función se está ejecutando
        error_log("🔄 updateAvatar llamado para usuario: " . $uid);

        // Verificar que se recibió un archivo
        if (empty($_FILES['avatar']) || ($_FILES['avatar']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
            $errorMsg = 'No se recibió archivo. Error: ' . ($_FILES['avatar']['error'] ?? 'DESCONOCIDO');
            error_log("❌ " . $errorMsg);
            
            if (!empty($_GET['ajax'])) {
                header('Content-Type: application/json');
                echo json_encode(['success' => false, 'message' => $errorMsg]);
                exit;
            }
            flash('error', $errorMsg);
            redirect('./?r=profile');
            return;
        }

        $file = $_FILES['avatar'];
        error_log("📁 Archivo recibido: " . $file['name'] . " - Tamaño: " . $file['size']);
        
        // Validar tamaño (max 10MB)
        if ($file['size'] > 10 * 1024 * 1024) {
            $errorMsg = 'Archivo demasiado grande (máx. 10MB)';
            error_log("❌ " . $errorMsg);
            
            if (!empty($_GET['ajax'])) {
                header('Content-Type: application/json');
                echo json_encode(['success' => false, 'message' => $errorMsg]);
                exit;
            }
            flash('error', $errorMsg);
            redirect('./?r=profile');
            return;
        }

        // Validar tipo MIME
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($finfo, $file['tmp_name']);
        finfo_close($finfo);

        error_log("📊 Tipo MIME detectado: " . $mime);

        $allowed = [
            'image/jpeg' => 'jpg',
            'image/png'  => 'png',
            'image/webp' => 'webp',
            'image/gif'  => 'gif',
        ];
        
        if (!isset($allowed[$mime])) {
            $errorMsg = 'Formato no permitido. Use JPEG, PNG, WEBP o GIF.';
            error_log("❌ " . $errorMsg);
            
            if (!empty($_GET['ajax'])) {
                header('Content-Type: application/json');
                echo json_encode(['success' => false, 'message' => $errorMsg]);
                exit;
            }
            flash('error', $errorMsg);
            redirect('./?r=profile');
            return;
        }
        
        $ext = $allowed[$mime];

        // Configurar rutas
        $projectRoot = realpath(__DIR__ . '/../../') ?: dirname(__FILE__, 3);
        $avatarsDir = $projectRoot . '/uploads/avatars';
        
        error_log("📂 Directorio de avatares: " . $avatarsDir);
        
        // Crear directorio si no existe
        if (!is_dir($avatarsDir)) {
            if (!mkdir($avatarsDir, 0775, true)) {
                $errorMsg = 'No se pudo crear el directorio de avatares';
                error_log("❌ " . $errorMsg);
                
                if (!empty($_GET['ajax'])) {
                    header('Content-Type: application/json');
                    echo json_encode(['success' => false, 'message' => $errorMsg]);
                    exit;
                }
                flash('error', $errorMsg);
                redirect('./?r=profile');
                return;
            }
        }

        // Verificar permisos de escritura
        if (!is_writable($avatarsDir)) {
            $errorMsg = 'Carpeta de avatares no tiene permisos de escritura';
            error_log("❌ " . $errorMsg);
            
            if (!empty($_GET['ajax'])) {
                header('Content-Type: application/json');
                echo json_encode(['success' => false, 'message' => $errorMsg]);
                exit;
            }
            flash('error', $errorMsg);
            redirect('./?r=profile');
            return;
        }

        // Generar nombre único para el archivo
        $filename = 'u' . $uid . '_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
        $destPath = $avatarsDir . '/' . $filename;
        $publicUrl = '/uploads/avatars/' . $filename;

        error_log("💾 Guardando archivo en: " . $destPath);

        // Procesar imagen (recortar y redimensionar)
        $saved = false;
        if (function_exists('imagecreatetruecolor')) {
            try {
                switch ($mime) {
                    case 'image/jpeg': 
                        $src = imagecreatefromjpeg($file['tmp_name']); 
                        break;
                    case 'image/png':  
                        $src = imagecreatefrompng($file['tmp_name']);  
                        break;
                    case 'image/webp': 
                        $src = function_exists('imagecreatefromwebp') ? imagecreatefromwebp($file['tmp_name']) : null; 
                        break;
                    case 'image/gif':  
                        $src = imagecreatefromgif($file['tmp_name']);  
                        break;
                    default: 
                        $src = null;
                }
                
                if ($src) {
                    $w = imagesx($src); 
                    $h = imagesy($src);
                    $side = min($w, $h);
                    $sx = (int)(($w - $side) / 2); 
                    $sy = (int)(($h - $side) / 2);
                    $size = 512;
                    
                    $dst = imagecreatetruecolor($size, $size);
                    
                    // Manejar transparencia para PNG y WebP
                    if (in_array($mime, ['image/png', 'image/webp'], true)) {
                        imagealphablending($dst, false);
                        imagesavealpha($dst, true);
                        $transparent = imagecolorallocatealpha($dst, 0, 0, 0, 127);
                        imagefilledrectangle($dst, 0, 0, $size, $size, $transparent);
                    } else {
                        $white = imagecolorallocate($dst, 255, 255, 255);
                        imagefill($dst, 0, 0, $white);
                    }
                    
                    imagecopyresampled($dst, $src, 0, 0, $sx, $sy, $size, $size, $side, $side);
                    
                    // Guardar imagen procesada
                    switch ($mime) {
                        case 'image/jpeg': 
                            $saved = imagejpeg($dst, $destPath, 88); 
                            break;
                        case 'image/png':  
                            $saved = imagepng($dst, $destPath, 6);   
                            break;
                        case 'image/webp': 
                            $saved = function_exists('imagewebp') ? imagewebp($dst, $destPath, 88) : false; 
                            break;
                        case 'image/gif':  
                            $saved = imagegif($dst, $destPath);     
                            break;
                    }
                    
                    imagedestroy($src); 
                    imagedestroy($dst);
                    
                    if ($saved) {
                        error_log("✅ Imagen procesada y guardada correctamente");
                    } else {
                        error_log("⚠️ No se pudo guardar la imagen procesada");
                    }
                }
            } catch (Throwable $t) {
                error_log("❌ Error procesando imagen: " . $t->getMessage());
                $saved = false;
            }
        }

        // Fallback: mover archivo sin procesar
        if (!$saved) {
            if (move_uploaded_file($file['tmp_name'], $destPath)) {
                error_log("✅ Archivo movido sin procesar");
                $saved = true;
            } else {
                $errorMsg = 'No se pudo guardar la imagen';
                error_log("❌ " . $errorMsg);
                
                if (!empty($_GET['ajax'])) {
                    header('Content-Type: application/json');
                    echo json_encode(['success' => false, 'message' => $errorMsg]);
                    exit;
                }
                flash('error', $errorMsg);
                redirect('./?r=profile');
                return;
            }
        }

        // Eliminar avatar anterior si existe
        try {
            $stmtOld = $db->prepare("SELECT avatar_url FROM users WHERE id = ?");
            $stmtOld->execute([$uid]);
            $oldAvatar = (string)$stmtOld->fetchColumn();
            
            if ($oldAvatar && str_starts_with($oldAvatar, '/uploads/avatars/')) {
                $oldPath = $projectRoot . $oldAvatar;
                if (is_file($oldPath) && $oldPath !== $destPath) {
                    if (unlink($oldPath)) {
                        error_log("🗑️ Avatar anterior eliminado: " . $oldPath);
                    } else {
                        error_log("⚠️ No se pudo eliminar avatar anterior: " . $oldPath);
                    }
                }
            }
        } catch (Throwable $t) {
            error_log("⚠️ Error eliminando avatar anterior: " . $t->getMessage());
        }

        // Actualizar base de datos - VERIFICACIÓN EXTRA
        try {
            // Verificar que la columna avatar_url existe
            $checkColumn = $db->prepare("SHOW COLUMNS FROM users LIKE 'avatar_url'");
            $checkColumn->execute();
            $columnExists = $checkColumn->fetch();
            
            if (!$columnExists) {
                error_log("❌ Columna avatar_url no existe en la tabla users");
                @unlink($destPath); // Limpiar archivo subido
                
                if (!empty($_GET['ajax'])) {
                    header('Content-Type: application/json');
                    echo json_encode(['success' => false, 'message' => 'Error de configuración de base de datos']);
                    exit;
                }
                flash('error', 'Error de configuración de base de datos');
                redirect('./?r=profile');
                return;
            }
            
            // Actualizar la base de datos
            $updateStmt = $db->prepare("UPDATE users SET avatar_url = ?, updated_at = NOW() WHERE id = ?");
            $result = $updateStmt->execute([$publicUrl, $uid]);
            
            if ($result) {
                error_log("✅ Base de datos actualizada correctamente. Filas afectadas: " . $updateStmt->rowCount());
                
                // Verificar que realmente se actualizó
                $verifyStmt = $db->prepare("SELECT avatar_url FROM users WHERE id = ?");
                $verifyStmt->execute([$uid]);
                $newAvatar = $verifyStmt->fetchColumn();
                
                error_log("🔍 Verificación - Avatar en BD: " . $newAvatar);
                
                // Actualizar sesión
                $_SESSION['user']['avatar_url'] = $publicUrl;
                
            } else {
                error_log("❌ Error en execute() al actualizar BD");
                @unlink($destPath); // Limpiar archivo subido
                
                if (!empty($_GET['ajax'])) {
                    header('Content-Type: application/json');
                    echo json_encode(['success' => false, 'message' => 'Error actualizando base de datos']);
                    exit;
                }
                flash('error', 'Error actualizando perfil');
                redirect('./?r=profile');
                return;
            }
            
        } catch (Throwable $t) {
            error_log("❌ Excepción al actualizar BD: " . $t->getMessage());
            @unlink($destPath); // Limpiar archivo subido
            
            if (!empty($_GET['ajax'])) {
                header('Content-Type: application/json');
                echo json_encode(['success' => false, 'message' => 'Error de base de datos: ' . $t->getMessage()]);
                exit;
            }
            flash('error', 'Error actualizando perfil');
            redirect('./?r=profile');
            return;
        }

        // Respuesta exitosa
        error_log("🎉 Avatar actualizado exitosamente: " . $publicUrl);
        
        if (!empty($_GET['ajax'])) {
            header('Content-Type: application/json');
            echo json_encode([
                'success' => true,
                'url' => $publicUrl,
                'message' => 'Avatar actualizado correctamente'
            ]);
            exit;
        }

        flash('success', 'Avatar actualizado correctamente');
        redirect('./?r=profile');
    }

    public static function viewFriend($db) {
        require_login();
        $friend_id = $_GET['id'] ?? '';
        $current_user_id = $_SESSION['user']['id'];
        $isAdmin = isset($_SESSION['user']['role']) && in_array($_SESSION['user']['role'], ['admin', 'moderator']);
        
        if (empty($friend_id)) {
            flash('error', 'ID inválido'); 
            redirect('dashboard'); 
            return;
        }
        
        if (!$isAdmin) {
            $is_friend = $db->prepare("SELECT 1 FROM friends WHERE ((user1_id = ? AND user2_id = ?) OR (user1_id = ? AND user2_id = ?)) AND status = 'accepted'");
            $is_friend->execute([$current_user_id, $friend_id, $friend_id, $current_user_id]);
            if (!$is_friend->fetch()) {
                flash('error', 'No puedes ver este perfil.');
                redirect('dashboard');
                return;
            }
        }
        
        $friend_stmt = $db->prepare("SELECT id, username, avatar_url, bio, created_at FROM users WHERE id = ?");
        $friend_stmt->execute([$friend_id]);
        $friend = $friend_stmt->fetch();
        
        if (!$friend) {
            flash('error', 'Usuario no encontrado.');
            redirect('dashboard');
            return;
        }
        
        $stats = $db->prepare("
            SELECT 
                (SELECT COUNT(*) FROM posts WHERE author_id = ?) as post_count,
                (SELECT COUNT(*) FROM friends WHERE (user1_id = ? OR user2_id = ?) AND status = 'accepted') as friend_count,
                (SELECT COUNT(*) FROM likes WHERE user_id = ?) as like_count,
                (SELECT COUNT(*) FROM comments WHERE user_id = ?) as comment_count
        ");
        $stats->execute([$friend_id, $friend_id, $friend_id, $friend_id, $friend_id]);
        
        $posts = $db->prepare("
            SELECT p.*, ph.url, 
                   (SELECT COUNT(*) FROM likes WHERE post_id = p.id) as likes,
                   (SELECT COUNT(*) FROM comments WHERE post_id = p.id) as comments 
            FROM posts p 
            LEFT JOIN photos ph ON ph.post_id = p.id 
            WHERE p.author_id = ? 
            ORDER BY p.created_at DESC 
            LIMIT 6
        ");
        $posts->execute([$friend_id]);
        
        view('profile/friend', [
            'friend' => $friend,
            'stats' => $stats->fetch(),
            'posts' => $posts->fetchAll(),
            'isAdmin' => $isAdmin,
            'isFriend' => true
        ]);
    }
}