<?php
// src/controllers/ReportAdminController.php

class ReportAdminController {
    
    /**
     * Obtener estadísticas del sistema (reutilizable desde AdminController)
     */
    private static function getStats($db) {
        return $db->query("
            SELECT 
                (SELECT COUNT(*) FROM users) as total_users,
                (SELECT COUNT(*) FROM posts) as total_posts,
                (SELECT COUNT(*) FROM comments) as total_comments,
                (SELECT COUNT(*) FROM reports WHERE status = 'pending') as pending_reports,
                (SELECT COUNT(*) FROM security_logs WHERE created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)) as daily_logs,
                (SELECT COUNT(*) FROM login_attempts WHERE locked_until > NOW()) as locked_attempts
        ")->fetch();
    }
    
    /**
     * Vista detallada del reporte (mejorada)
     */
    public static function detail($db) {
        // Verificar permisos de administrador
        if (session_status() === PHP_SESSION_NONE) session_start();
        $isAdmin = isset($_SESSION['user']['role']) && in_array($_SESSION['user']['role'], ['admin', 'moderator']);
        if (!$isAdmin) {
            http_response_code(403);
            view('admin/error', [
                'message' => 'Acceso denegado. No tienes permisos para acceder a esta área.'
            ]);
            exit;
        }
        
        // Obtener el ID del reporte
        $report_id = $_GET['id'] ?? '';
        if (empty($report_id)) {
            flash('error', 'ID de reporte no válido.');
            header('Location: ./?r=admin/reports');
            exit;
        }
        
        // Obtener información detallada del reporte
        $stmt = $db->prepare("
            SELECT r.*, 
                   u.username as reporter_username, u.email as reporter_email,
                   ru.username as target_username, ru.email as target_email,
                   ru.profile_image as target_avatar,
                   a.username as admin_username,
                   p.caption as post_caption, p.author_id as post_author_id,
                   c.comment as comment_content, c.user_id as comment_author_id
            FROM reports r 
            LEFT JOIN users u ON r.reporter_id = u.id 
            LEFT JOIN users ru ON r.target_id = ru.id AND r.target_type = 'user'
            LEFT JOIN users a ON r.reviewed_by = a.id
            LEFT JOIN posts p ON r.target_id = p.id AND r.target_type = 'post'
            LEFT JOIN comments c ON r.target_id = c.id AND r.target_type = 'comment'
            WHERE r.id = ?
        ");
        
        $stmt->execute([$report_id]);
        $report = $stmt->fetch();
        
        if (!$report) {
            flash('error', 'Reporte no encontrado.');
            header('Location: ./?r=admin/reports');
            exit;
        }
        
        // Obtener historial de acciones relacionadas
        $history_stmt = $db->prepare("
            SELECT sl.*, u.username as admin_username
            FROM security_logs sl
            LEFT JOIN users u ON sl.user_id = u.id
            WHERE (sl.details LIKE ? OR sl.admin_reason LIKE ?)
            AND sl.action LIKE '%report%'
            ORDER BY sl.created_at DESC
            LIMIT 10
        ");
        
        $search_term = "%$report_id%";
        $history_stmt->execute([$search_term, $search_term]);
        $history = $history_stmt->fetchAll();
        
        // Obtener contenido reportado según el tipo
        $reported_content = '';
        $content_author = '';
        $comment_post_id = null;
        
        switch ($report['target_type']) {
            case 'post':
                $reported_content = $report['post_caption'] ?? 'Sin título';
                $author_stmt = $db->prepare("SELECT username FROM users WHERE id = ?");
                $author_stmt->execute([$report['post_author_id']]);
                $author = $author_stmt->fetch();
                $content_author = $author ? $author['username'] : 'Desconocido';
                
                // Obtener imágenes del post
                $images_stmt = $db->prepare("SELECT url FROM photos WHERE post_id = ?");
                $images_stmt->execute([$report['target_id']]);
                $images = $images_stmt->fetchAll();
                break;
                
            case 'comment':
                $reported_content = $report['comment_content'] ?? 'Contenido no disponible';
                $author_stmt = $db->prepare("SELECT username FROM users WHERE id = ?");
                $author_stmt->execute([$report['comment_author_id']]);
                $author = $author_stmt->fetch();
                $content_author = $author ? $author['username'] : 'Desconocido';
                
                // Obtener post_id del comentario para enlace
                $post_stmt = $db->prepare("SELECT post_id FROM comments WHERE id = ?");
                $post_stmt->execute([$report['target_id']]);
                $post_data = $post_stmt->fetch();
                $comment_post_id = $post_data ? $post_data['post_id'] : null;
                break;
                
            case 'user':
                $reported_content = 'Perfil de usuario: ' . ($report['target_username'] ?? 'Usuario');
                $content_author = $report['target_username'] ?? 'Desconocido';
                break;
        }
        
        $stats = self::getStats($db);
        
        // Usar la nueva vista mejorada de report-detail
        view('admin/report-detail', [
            'report' => $report,
            'history' => $history,
            'reported_content' => $reported_content,
            'content_author' => $content_author,
            'images' => $images ?? [],
            'comment_post_id' => $comment_post_id,
            'stats' => $stats,
            'currentPage' => 'reports',
            'pageTitle' => 'Detalles del Reporte #' . $report['id'],
            'pageSubtitle' => 'Información completa del reporte - ' . ucfirst($report['target_type'])
        ]);
    }
    
    /**
     * Actualizar estado del reporte (nuevo endpoint unificado)
     */
    public static function updateStatus($db) {
        // Verificar permisos
        if (session_status() === PHP_SESSION_NONE) session_start();
        $isAdmin = isset($_SESSION['user']['role']) && in_array($_SESSION['user']['role'], ['admin', 'moderator']);
        if (!$isAdmin) {
            http_response_code(403);
            echo json_encode(['success' => false, 'message' => 'Acceso denegado']);
            exit;
        }
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            validate_csrf();
            
            $report_id = $_POST['report_id'] ?? '';
            $status = $_POST['status'] ?? '';
            $notes = trim($_POST['notes'] ?? '');
            $notify_reporter = isset($_POST['notify_reporter']) && $_POST['notify_reporter'] == '1';
            
            if (empty($report_id) || empty($status)) {
                flash('error', 'Datos incompletos');
                header('Location: ./?r=admin/reports');
                exit;
            }
            
            // Obtener estado actual para el historial
            $current_stmt = $db->prepare("SELECT status FROM reports WHERE id = ?");
            $current_stmt->execute([$report_id]);
            $current_status = $current_stmt->fetch()['status'] ?? 'pending';
            
            // Actualizar reporte
            $stmt = $db->prepare("
                UPDATE reports 
                SET status = ?, notes = ?, reviewed_at = NOW(), reviewed_by = ? 
                WHERE id = ?
            ");
            $success = $stmt->execute([$status, $notes, $_SESSION['user']['id'], $report_id]);
            
            if ($success) {
                // Registrar en logs de seguridad
                SecurityHelper::logSecurityEvent($db, 'report_status_updated', 
                    "Reporte actualizado: ID $report_id, estado: $current_status → $status", 
                    $_SESSION['user']['id'], 'medium', "Cambio de estado a $status");
                
                // Notificar al reportador si está marcado
                if ($notify_reporter) {
                    self::notifyReporter($db, $report_id, $status, $_SESSION['user']['id']);
                }
                
                flash('success', 'Estado del reporte actualizado correctamente');
                
                // REDIRECCIÓN CORREGIDA - usar header Location directamente
                header('Location: ./?r=admin/report-detail&id=' . $report_id . '&success=1');
                exit;
            } else {
                flash('error', 'Error al actualizar el reporte');
                header('Location: ./?r=admin/report-detail&id=' . $report_id);
                exit;
            }
        } else {
            flash('error', 'Método no permitido');
            header('Location: ./?r=admin/reports');
            exit;
        }
    }
    
    /**
     * Tomar acciones específicas sobre el contenido reportado
     */
    public static function takeAction($db) {
        // Verificar permisos
        if (session_status() === PHP_SESSION_NONE) session_start();
        $isAdmin = isset($_SESSION['user']['role']) && in_array($_SESSION['user']['role'], ['admin', 'moderator']);
        if (!$isAdmin) {
            http_response_code(403);
            echo json_encode(['success' => false, 'message' => 'Acceso denegado']);
            exit;
        }
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            validate_csrf();
            
            $action = $_POST['action'] ?? '';
            $target_id = $_POST['target_id'] ?? '';
            $target_type = $_POST['target_type'] ?? '';
            $report_id = $_POST['report_id'] ?? '';
            $reason = trim($_POST['reason'] ?? '');
            
            if (empty($action) || empty($target_id) || empty($reason) || empty($report_id)) {
                flash('error', 'Datos incompletos');
                header('Location: ./?r=admin/reports');
                exit;
            }
            
            $success = false;
            $action_details = '';
            
            switch ($action) {
                case 'delete_post':
                    // Eliminar publicación
                    $db->beginTransaction();
                    try {
                        // Eliminar likes
                        $db->prepare("DELETE FROM likes WHERE post_id = ?")->execute([$target_id]);
                        // Eliminar comentarios
                        $db->prepare("DELETE FROM comments WHERE post_id = ?")->execute([$target_id]);
                        // Eliminar fotos
                        $db->prepare("DELETE FROM photos WHERE post_id = ?")->execute([$target_id]);
                        // Eliminar tags
                        $db->prepare("DELETE FROM tags WHERE post_id = ?")->execute([$target_id]);
                        // Eliminar el post
                        $db->prepare("DELETE FROM posts WHERE id = ?")->execute([$target_id]);
                        $db->commit();
                        $success = true;
                        $action_details = "Publicación eliminada: ID $target_id";
                    } catch (Exception $e) {
                        $db->rollBack();
                        $success = false;
                        error_log("Error eliminando post: " . $e->getMessage());
                    }
                    break;
                    
                case 'delete_comment':
                    // Eliminar comentario
                    try {
                        $stmt = $db->prepare("DELETE FROM comments WHERE id = ?");
                        $success = $stmt->execute([$target_id]);
                        $action_details = "Comentario eliminado: ID $target_id";
                    } catch (Exception $e) {
                        error_log("Error eliminando comentario: " . $e->getMessage());
                        $success = false;
                    }
                    break;
                    
                case 'warn_user':
                    // Advertir usuario
                    try {
                        $user_stmt = $db->prepare("SELECT username FROM users WHERE id = ?");
                        $user_stmt->execute([$target_id]);
                        $user = $user_stmt->fetch();
                        $username = $user ? $user['username'] : $target_id;
                        
                        // Crear notificación de advertencia
                        $notif_stmt = $db->prepare("
                            INSERT INTO notifications (id, user_id, type, message, created_at)
                            VALUES (UUID(), ?, 'warning', ?, NOW())
                        ");
                        $warning_message = "Has recibido una advertencia por: " . $reason;
                        $success = $notif_stmt->execute([$target_id, $warning_message]);
                        $action_details = "Usuario advertido: $username (ID: $target_id)";
                    } catch (Exception $e) {
                        error_log("Error advirtiendo usuario: " . $e->getMessage());
                        $success = false;
                    }
                    break;
                    
                case 'block_user':
                    // Bloquear usuario temporalmente (24 horas)
                    try {
                        $lock_until = date('Y-m-d H:i:s', time() + (24 * 60 * 60));
                        $stmt = $db->prepare("UPDATE users SET locked_until = ? WHERE id = ?");
                        $success = $stmt->execute([$lock_until, $target_id]);
                        
                        $user_stmt = $db->prepare("SELECT username FROM users WHERE id = ?");
                        $user_stmt->execute([$target_id]);
                        $user = $user_stmt->fetch();
                        $username = $user ? $user['username'] : $target_id;
                        $action_details = "Usuario bloqueado: $username hasta $lock_until";
                    } catch (Exception $e) {
                        error_log("Error bloqueando usuario: " . $e->getMessage());
                        $success = false;
                    }
                    break;
                    
                default:
                    flash('error', 'Acción no válida');
                    header('Location: ./?r=admin/report-detail&id=' . $report_id);
                    exit;
            }
            
            if ($success) {
                // Registrar la acción en logs de seguridad
                SecurityHelper::logSecurityEvent($db, 'report_action_taken', 
                    "$action_details - Reporte: $report_id", 
                    $_SESSION['user']['id'], 'high', $reason);
                
                // Actualizar el reporte como resuelto si se tomó una acción
                if (in_array($action, ['delete_post', 'delete_comment', 'block_user'])) {
                    $update_stmt = $db->prepare("
                        UPDATE reports 
                        SET status = 'resolved', reviewed_at = NOW(), reviewed_by = ? 
                        WHERE id = ?
                    ");
                    $update_stmt->execute([$_SESSION['user']['id'], $report_id]);
                }
                
                flash('success', 'Acción realizada correctamente');
            } else {
                flash('error', 'Error al realizar la acción');
            }
            
            header('Location: ./?r=admin/report-detail&id=' . $report_id);
            exit;
        } else {
            flash('error', 'Método no permitido');
            header('Location: ./?r=admin/reports');
            exit;
        }
    }
    
    /**
     * Notificar al reportador sobre el cambio de estado
     */
    private static function notifyReporter($db, $report_id, $new_status, $admin_id) {
        try {
            // Obtener información del reporte y reportador
            $stmt = $db->prepare("
                SELECT r.reporter_id, r.reason, r.target_type, u.username as admin_name
                FROM reports r 
                LEFT JOIN users u ON u.id = ?
                WHERE r.id = ?
            ");
            $stmt->execute([$admin_id, $report_id]);
            $report_data = $stmt->fetch();
            
            if ($report_data && $report_data['reporter_id']) {
                $status_messages = [
                    'resolved' => 'ha sido resuelto',
                    'dismissed' => 'ha sido desestimado', 
                    'investigating' => 'está en investigación',
                    'pending' => 'está pendiente de revisión'
                ];
                
                $message = "Tu reporte de {$report_data['reason']} sobre un {$report_data['target_type']} " . 
                          ($status_messages[$new_status] ?? 'ha sido actualizado') . 
                          " por el moderador {$report_data['admin_name']}.";
                
                // Insertar notificación
                $notif_stmt = $db->prepare("
                    INSERT INTO notifications (id, user_id, type, message, created_at)
                    VALUES (UUID(), ?, 'report_update', ?, NOW())
                ");
                $notif_stmt->execute([$report_data['reporter_id'], $message]);
            }
        } catch (Exception $e) {
            error_log("Error notificando reporter: " . $e->getMessage());
        }
    }
    
    /**
     * Obtener reportes recientes para el dashboard
     */
    public static function getRecentReports($db, $limit = 5) {
        $stmt = $db->prepare("
            SELECT r.*, u.username as reporter_username 
            FROM reports r 
            LEFT JOIN users u ON r.reporter_id = u.id 
            ORDER BY r.created_at DESC 
            LIMIT ?
        ");
        $stmt->execute([$limit]);
        return $stmt->fetchAll();
    }
}