<?php
// src/controllers/ReportController.php
class ReportController {
    
    public static function index($db) {
        require_login();
        $uid = $_SESSION['user']['id'];
        
        // Obtener reportes del usuario (si es user) o todos (si es admin/moderator)
        $is_moderator = ($_SESSION['user']['role'] ?? 'user') !== 'user';
        
        if ($is_moderator) {
            $reports = $db->prepare("
                SELECT r.*, u1.username as reporter_username, u2.username as target_username,
                       p.caption as post_caption, c.comment as comment_content,
                       CASE 
                           WHEN r.target_type = 'post' THEN p.caption
                           WHEN r.target_type = 'comment' THEN c.comment
                           ELSE NULL
                       END as content_preview
                FROM reports r
                LEFT JOIN users u1 ON r.reporter_id = u1.id
                LEFT JOIN users u2 ON r.target_type = 'user' AND r.target_id = u2.id
                LEFT JOIN posts p ON r.target_type = 'post' AND r.target_id = p.id
                LEFT JOIN comments c ON r.target_type = 'comment' AND r.target_id = c.id
                ORDER BY r.created_at DESC
                LIMIT 50
            ");
            $reports->execute();
        } else {
            $reports = $db->prepare("
                SELECT r.*, u.username as target_username,
                       p.caption as post_caption, c.comment as comment_content,
                       CASE 
                           WHEN r.target_type = 'post' THEN p.caption
                           WHEN r.target_type = 'comment' THEN c.comment
                           ELSE NULL
                       END as content_preview
                FROM reports r
                LEFT JOIN users u ON r.target_type = 'user' AND r.target_id = u.id
                LEFT JOIN posts p ON r.target_type = 'post' AND r.target_id = p.id
                LEFT JOIN comments c ON r.target_type = 'comment' AND r.target_id = c.id
                WHERE r.reporter_id = ?
                ORDER BY r.created_at DESC
                LIMIT 50
            ");
            $reports->execute([$uid]);
        }
        
        view('reports/index', [
            'reports' => $reports->fetchAll(),
            'is_moderator' => $is_moderator
        ]);
    }
    
    public static function create($db) {
        require_login();
        $uid = $_SESSION['user']['id'];
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            validate_csrf();
            
            $target_type = $_POST['target_type'] ?? '';
            $target_id = $_POST['target_id'] ?? '';
            $reason = $_POST['reason'] ?? '';
            $description = trim($_POST['description'] ?? '');
            
            // Validaciones
            if (!in_array($target_type, ['post', 'comment', 'user']) || empty($target_id)) {
                flash('error', 'Tipo de reporte no válido');
                redirect('dashboard');
                return;
            }
            
            if (!in_array($reason, ['spam', 'harassment', 'inappropriate', 'other'])) {
                flash('error', 'Razón no válida');
                redirect('dashboard');
                return;
            }
            
            // Verificar que el target existe
            $target_exists = false;
            switch ($target_type) {
                case 'post':
                    $check = $db->prepare("SELECT id FROM posts WHERE id = ?");
                    $check->execute([$target_id]);
                    $target_exists = (bool)$check->fetch();
                    break;
                    
                case 'comment':
                    $check = $db->prepare("SELECT id FROM comments WHERE id = ?");
                    $check->execute([$target_id]);
                    $target_exists = (bool)$check->fetch();
                    break;
                    
                case 'user':
                    $check = $db->prepare("SELECT id FROM users WHERE id = ? AND id != ?");
                    $check->execute([$target_id, $uid]);
                    $target_exists = (bool)$check->fetch();
                    break;
            }
            
            if (!$target_exists) {
                flash('error', 'El elemento a reportar no existe');
                redirect('dashboard');
                return;
            }
            
            // Verificar que no hay reporte duplicado reciente
            $duplicate = $db->prepare("
                SELECT id FROM reports 
                WHERE reporter_id = ? AND target_type = ? AND target_id = ? 
                AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
            ");
            $duplicate->execute([$uid, $target_type, $target_id]);
            
            if ($duplicate->fetch()) {
                flash('info', 'Ya has reportado este elemento recientemente');
                redirect('dashboard');
                return;
            }
            
            // Crear reporte
            $stmt = $db->prepare("
                INSERT INTO reports (id, reporter_id, target_type, target_id, reason, description, created_at)
                VALUES (UUID(), ?, ?, ?, ?, ?, NOW())
            ");
            
            $success = $stmt->execute([$uid, $target_type, $target_id, $reason, $description]);
            
            if ($success) {
                SecurityHelper::logSecurityEvent($db, 'report_created', 
                    "Reporte creado: $target_type/$target_id - $reason", $uid);
                
                // Notificar a moderadores
                self::notifyModerators($db, $target_type, $target_id, $reason);
                
                flash('success', 'Reporte enviado correctamente. Los moderadores lo revisarán.');
            } else {
                flash('error', 'Error al crear el reporte');
            }
            
            // Redirigir siempre a dashboard en lugar de usar HTTP_REFERER (que es inseguro)
            redirect('dashboard');
        }
    }
    
    public static function update($db) {
        require_login();
        $uid = $_SESSION['user']['id'];
        
        // Solo moderadores y admins pueden actualizar reportes
        if (($_SESSION['user']['role'] ?? 'user') === 'user') {
            flash('error', 'No tienes permisos para esta acción');
            redirect('dashboard');
            return;
        }
        
        $report_id = $_POST['report_id'] ?? '';
        $action = $_POST['action'] ?? '';
        $notes = trim($_POST['notes'] ?? '');
        
        if (empty($report_id) || !in_array($action, ['reviewed', 'resolved'])) {
            flash('error', 'Datos inválidos');
            redirect('reports');
            return;
        }
        
        // Obtener reporte
        $report = $db->prepare("SELECT * FROM reports WHERE id = ?");
        $report->execute([$report_id]);
        $report_data = $report->fetch();
        
        if (!$report_data) {
            flash('error', 'Reporte no encontrado');
            redirect('reports');
            return;
        }
        
        // Actualizar reporte
        $stmt = $db->prepare("
            UPDATE reports 
            SET status = ?, reviewed_by = ?, reviewed_at = NOW(), notes = ?
            WHERE id = ?
        ");
        
        $success = $stmt->execute([$action, $uid, $notes, $report_id]);
        
        if ($success) {
            SecurityHelper::logSecurityEvent($db, 'report_updated', 
                "Reporte $action: $report_id", $uid);
            
            // Tomar acciones adicionales si se resuelve
            if ($action === 'resolved') {
                self::takeAction($db, $report_data, $notes);
            }
            
            flash('success', 'Reporte actualizado correctamente');
        } else {
            flash('error', 'Error al actualizar el reporte');
        }
        
        redirect('reports');
    }
    
    private static function notifyModerators($db, $target_type, $target_id, $reason) {
        $moderators = $db->query("
            SELECT id FROM users WHERE role IN ('moderator', 'admin') AND email_verified = 1
        ")->fetchAll();
        
        foreach ($moderators as $mod) {
            $db->prepare("
                INSERT INTO notifications (id, user_id, type, message, created_at)
                VALUES (UUID(), ?, 'report', 'Nuevo reporte de $reason en $target_type', NOW())
            ")->execute([$mod['id']]);
        }
    }
    
    private static function takeAction($db, $report, $notes) {
        switch ($report['target_type']) {
            case 'post':
                if (strpos($notes, 'delete_post') !== false) {
                    $db->prepare("DELETE FROM posts WHERE id = ?")->execute([$report['target_id']]);
                    SecurityHelper::logSecurityEvent($db, 'post_deleted_by_report', 
                        "Post eliminado por reporte: " . $report['target_id'], $report['reviewed_by']);
                }
                break;
                
            case 'comment':
                if (strpos($notes, 'delete_comment') !== false) {
                    $db->prepare("DELETE FROM comments WHERE id = ?")->execute([$report['target_id']]);
                    SecurityHelper::logSecurityEvent($db, 'comment_deleted_by_report', 
                        "Comentario eliminado por reporte: " . $report['target_id'], $report['reviewed_by']);
                }
                break;
                
            case 'user':
                if (strpos($notes, 'warn_user') !== false) {
                    // Enviar advertencia al usuario
                    $db->prepare("
                        INSERT INTO notifications (id, user_id, type, message, created_at)
                        VALUES (UUID(), ?, 'warning', 'Has recibido una advertencia por: $notes', NOW())
                    ")->execute([$report['target_id']]);
                } elseif (strpos($notes, 'ban_user') !== false) {
                    // Banear usuario temporalmente
                    $lock_until = date('Y-m-d H:i:s', time() + (7 * 24 * 3600)); // 7 días
                    $db->prepare("UPDATE users SET locked_until = ? WHERE id = ?")
                       ->execute([$lock_until, $report['target_id']]);
                    SecurityHelper::logSecurityEvent($db, 'user_banned_by_report', 
                        "Usuario baneado por reporte: " . $report['target_id'], $report['reviewed_by']);
                }
                break;
        }
    }
    
    public static function getReportForm($db) {
        require_login();
        
        $target_type = $_GET['type'] ?? '';
        $target_id = $_GET['id'] ?? '';
        
        if (!in_array($target_type, ['post', 'comment', 'user']) || empty($target_id)) {
            flash('error', 'Parámetros inválidos');
            redirect('dashboard');
            return;
        }
        
        // Verificar que el target existe
        $target_exists = false;
        $target_info = [];
        
        switch ($target_type) {
            case 'post':
                $check = $db->prepare("SELECT p.*, u.username FROM posts p JOIN users u ON p.author_id = u.id WHERE p.id = ?");
                $check->execute([$target_id]);
                $target_info = $check->fetch();
                $target_exists = (bool)$target_info;
                break;
                
            case 'comment':
                $check = $db->prepare("SELECT c.*, u.username FROM comments c JOIN users u ON c.user_id = u.id WHERE c.id = ?");
                $check->execute([$target_id]);
                $target_info = $check->fetch();
                $target_exists = (bool)$target_info;
                break;
                
            case 'user':
                $check = $db->prepare("SELECT id, username FROM users WHERE id = ? AND id != ?");
                $check->execute([$target_id, $_SESSION['user']['id']]);
                $target_info = $check->fetch();
                $target_exists = (bool)$target_info;
                break;
        }
        
        if (!$target_exists) {
            flash('error', 'El elemento a reportar no existe');
            redirect('dashboard');
            return;
        }
        
        view('reports/create', [
            'target_type' => $target_type,
            'target_id' => $target_id,
            'target_info' => $target_info
        ]);
    }
}