<?php
/**
 * ============================================================================
 * admin/message-reports.php - Reported Messages Moderation
 * Handle reported messages including encrypted content
 * ============================================================================
 */

require_once __DIR__ . '/includes/base.php';

// Check permission
if (!hasAdminPermission('manage_reports')) {
    setFlashMessage('Access denied. Report management permission required.', 'error');
    header('Location: ' . APP_URL . '/admin/index.php');
    exit();
}

$breadcrumbs = [
    ['title' => 'Message Reports', 'url' => '']
];

// Fetch reported messages
try {
    $sql = "SELECT 
                mr.*,
                reporter.full_name as reporter_name,
                reporter.phone_number as reporter_phone,
                m.chat_id,
                m.message_type,
                m.is_encrypted,
                m.created_at as message_date,
                c.chat_type,
                reviewed_by_user.full_name as reviewed_by_name
            FROM message_reports mr
            JOIN users reporter ON mr.reporter_id = reporter.id
            LEFT JOIN messages m ON mr.message_id = m.id
            LEFT JOIN chats c ON m.chat_id = c.id
            LEFT JOIN users reviewed_by_user ON mr.reviewed_by = reviewed_by_user.id
            ORDER BY 
                CASE mr.status 
                    WHEN 'pending' THEN 1 
                    WHEN 'reviewing' THEN 2 
                    ELSE 3 
                END,
                mr.created_at DESC";
    
    $stmt = $db->query($sql);
    $reports = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get statistics
    $sql = "SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
                SUM(CASE WHEN status = 'reviewing' THEN 1 ELSE 0 END) as reviewing,
                SUM(CASE WHEN status = 'resolved' THEN 1 ELSE 0 END) as resolved,
                SUM(CASE WHEN status = 'dismissed' THEN 1 ELSE 0 END) as dismissed
            FROM message_reports";
    $stmt = $db->query($sql);
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    logError('Message reports fetch error: ' . $e->getMessage());
    $reports = [];
    $stats = ['total' => 0, 'pending' => 0, 'reviewing' => 0, 'resolved' => 0, 'dismissed' => 0];
}

renderAdminHeader('Message Reports', $breadcrumbs);
?>

<style>
.report-card {
    border-left: 4px solid #6b7280;
    transition: all 0.2s ease;
}
.report-card:hover {
    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}
.report-card.pending {
    border-left-color: #f59e0b;
}
.report-card.resolved {
    border-left-color: #22c55e;
}
.report-card.dismissed {
    border-left-color: #6b7280;
}
.encrypted-badge {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: 600;
}
</style>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold">
            <i class="bi bi-chat-square-text me-2"></i>Message Reports
        </h2>
        <p class="text-muted mb-0">Review and moderate reported messages</p>
    </div>
</div>

<!-- Statistics -->
<div class="row mb-4">
    <div class="col-md-2 mb-3">
        <div class="card border-0 shadow-sm text-center">
            <div class="card-body">
                <div class="text-muted small mb-1">Total Reports</div>
                <h3 class="mb-0 fw-bold"><?php echo $stats['total']; ?></h3>
            </div>
        </div>
    </div>
    <div class="col-md-2 mb-3">
        <div class="card border-0 shadow-sm text-center">
            <div class="card-body">
                <div class="text-warning small mb-1">Pending</div>
                <h3 class="mb-0 fw-bold text-warning"><?php echo $stats['pending']; ?></h3>
            </div>
        </div>
    </div>
    <div class="col-md-2 mb-3">
        <div class="card border-0 shadow-sm text-center">
            <div class="card-body">
                <div class="text-info small mb-1">Reviewing</div>
                <h3 class="mb-0 fw-bold text-info"><?php echo $stats['reviewing']; ?></h3>
            </div>
        </div>
    </div>
    <div class="col-md-2 mb-3">
        <div class="card border-0 shadow-sm text-center">
            <div class="card-body">
                <div class="text-success small mb-1">Resolved</div>
                <h3 class="mb-0 fw-bold text-success"><?php echo $stats['resolved']; ?></h3>
            </div>
        </div>
    </div>
    <div class="col-md-2 mb-3">
        <div class="card border-0 shadow-sm text-center">
            <div class="card-body">
                <div class="text-muted small mb-1">Dismissed</div>
                <h3 class="mb-0 fw-bold text-muted"><?php echo $stats['dismissed']; ?></h3>
            </div>
        </div>
    </div>
</div>

<?php if (hasAdminPermission('view_encrypted_messages')): ?>
<div class="alert alert-warning border-0 shadow-sm mb-4">
    <div class="d-flex align-items-start">
        <i class="bi bi-shield-lock-fill me-3 fs-4"></i>
        <div>
            <h6 class="alert-heading mb-2">Encrypted Message Access</h6>
            <p class="mb-0">You have special authorization to view encrypted message metadata for moderation purposes. 
            The actual message content remains encrypted and cannot be viewed. You can only see:</p>
            <ul class="mb-0 mt-2 small">
                <li>Message timestamp and type</li>
                <li>Sender and receiver information</li>
                <li>Report description from the reporter</li>
                <li>Evidence provided by the reporter</li>
            </ul>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Filter Tabs -->
<ul class="nav nav-tabs mb-4">
    <li class="nav-item">
        <a class="nav-link active" data-bs-toggle="tab" href="#all">
            All Reports <span class="badge bg-secondary ms-1"><?php echo $stats['total']; ?></span>
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-bs-toggle="tab" href="#pending">
            Pending <span class="badge bg-warning ms-1"><?php echo $stats['pending']; ?></span>
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link" data-bs-toggle="tab" href="#encrypted">
            Encrypted <span class="encrypted-badge ms-1">
                <?php echo count(array_filter($reports, fn($r) => $r['is_encrypted'] == 1)); ?>
            </span>
        </a>
    </li>
</ul>

<!-- Reports List -->
<div class="tab-content">
    <div class="tab-pane fade show active" id="all">
        <?php renderReportsList($reports); ?>
    </div>
    <div class="tab-pane fade" id="pending">
        <?php renderReportsList(array_filter($reports, fn($r) => $r['status'] === 'pending')); ?>
    </div>
    <div class="tab-pane fade" id="encrypted">
        <?php renderReportsList(array_filter($reports, fn($r) => $r['is_encrypted'] == 1)); ?>
    </div>
</div>

<?php
function renderReportsList($reports) {
    if (empty($reports)): ?>
        <div class="text-center py-5">
            <i class="bi bi-inbox text-muted" style="font-size: 4rem;"></i>
            <p class="text-muted mt-3">No reports found</p>
        </div>
    <?php else: ?>
        <div class="row">
            <?php foreach ($reports as $report): ?>
            <div class="col-12 mb-3">
                <div class="card border-0 shadow-sm report-card <?php echo $report['status']; ?>">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-8">
                                <!-- Report Header -->
                                <div class="d-flex align-items-start justify-content-between mb-3">
                                    <div>
                                        <span class="badge bg-<?php 
                                            echo $report['report_type'] === 'spam' ? 'warning' : 
                                                ($report['report_type'] === 'harassment' ? 'danger' : 
                                                ($report['report_type'] === 'scam' ? 'dark' : 'secondary'));
                                        ?> me-2">
                                            <?php echo strtoupper(str_replace('_', ' ', $report['report_type'])); ?>
                                        </span>
                                        
                                        <?php if ($report['is_encrypted']): ?>
                                        <span class="encrypted-badge">
                                            <i class="bi bi-lock-fill me-1"></i>ENCRYPTED
                                        </span>
                                        <?php endif; ?>
                                        
                                        <span class="badge bg-<?php 
                                            echo $report['status'] === 'pending' ? 'warning' : 
                                                ($report['status'] === 'resolved' ? 'success' : 
                                                ($report['status'] === 'reviewing' ? 'info' : 'secondary'));
                                        ?>">
                                            <?php echo strtoupper($report['status']); ?>
                                        </span>
                                    </div>
                                    <small class="text-muted">Report #<?php echo $report['id']; ?></small>
                                </div>
                                
                                <!-- Reporter Info -->
                                <div class="mb-3">
                                    <strong>Reported by:</strong> 
                                    <?php echo htmlspecialchars($report['reporter_name']); ?>
                                    <small class="text-muted">(<?php echo htmlspecialchars($report['reporter_phone']); ?>)</small>
                                    <br>
                                    <small class="text-muted">
                                        <i class="bi bi-clock me-1"></i><?php echo timeAgo($report['created_at']); ?>
                                    </small>
                                </div>
                                
                                <!-- Report Description -->
                                <div class="mb-3">
                                    <strong>Description:</strong>
                                    <p class="mb-0 text-muted"><?php echo htmlspecialchars($report['description'] ?? 'No description provided'); ?></p>
                                </div>
                                
                                <!-- Message Info -->
                                <div class="alert alert-light mb-0">
                                    <div class="row small">
                                        <div class="col-md-6">
                                            <strong>Message Type:</strong> <?php echo ucfirst($report['message_type']); ?><br>
                                            <strong>Chat Type:</strong> <?php echo ucfirst(str_replace('_', ' ', $report['chat_type'])); ?><br>
                                            <strong>Message Date:</strong> <?php echo formatDate($report['message_date']); ?>
                                        </div>
                                        <div class="col-md-6">
                                            <?php if ($report['is_encrypted']): ?>
                                                <div class="text-warning">
                                                    <i class="bi bi-shield-lock-fill me-1"></i>
                                                    <strong>End-to-End Encrypted</strong><br>
                                                    <small>Content cannot be viewed by admins</small>
                                                </div>
                                            <?php else: ?>
                                                <button class="btn btn-sm btn-outline-primary" 
                                                        onclick="viewMessageContent(<?php echo $report['message_id']; ?>)">
                                                    <i class="bi bi-eye me-1"></i>View Message Content
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Actions -->
                            <div class="col-md-4">
                                <?php if ($report['status'] === 'pending'): ?>
                                <div class="d-grid gap-2">
                                    <button class="btn btn-info" 
                                            onclick="updateReportStatus(<?php echo $report['id']; ?>, 'reviewing')">
                                        <i class="bi bi-eye-fill me-2"></i>Start Review
                                    </button>
                                    <button class="btn btn-danger" 
                                            onclick="takeAction(<?php echo $report['id']; ?>, 'block_user')">
                                        <i class="bi bi-ban me-2"></i>Block User
                                    </button>
                                    <button class="btn btn-warning" 
                                            onclick="takeAction(<?php echo $report['id']; ?>, 'delete_message')">
                                        <i class="bi bi-trash me-2"></i>Delete Message
                                    </button>
                                    <button class="btn btn-success" 
                                            onclick="resolveReport(<?php echo $report['id']; ?>)">
                                        <i class="bi bi-check-circle me-2"></i>Resolve
                                    </button>
                                    <button class="btn btn-outline-secondary" 
                                            onclick="dismissReport(<?php echo $report['id']; ?>)">
                                        <i class="bi bi-x-circle me-2"></i>Dismiss
                                    </button>
                                </div>
                                <?php elseif ($report['status'] === 'resolved'): ?>
                                <div class="alert alert-success mb-0">
                                    <strong>Resolved</strong><br>
                                    <small>By: <?php echo htmlspecialchars($report['reviewed_by_name'] ?? 'System'); ?></small><br>
                                    <small><?php echo timeAgo($report['reviewed_at']); ?></small>
                                    <?php if ($report['admin_notes']): ?>
                                    <hr>
                                    <small><strong>Notes:</strong> <?php echo htmlspecialchars($report['admin_notes']); ?></small>
                                    <?php endif; ?>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    <?php endif;
}
?>

<!-- Action Modal -->
<div class="modal fade" id="actionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Take Action</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="actionForm">
                <input type="hidden" name="report_id" id="action_report_id">
                <input type="hidden" name="action_type" id="action_type">
                <div class="modal-body">
                    <div class="alert alert-warning">
                        <i class="bi bi-exclamation-triangle me-2"></i>
                        This action will be logged and cannot be undone.
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Admin Notes</label>
                        <textarea class="form-control" name="admin_notes" rows="3" required></textarea>
                        <small class="text-muted">Explain the reason for this action</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Confirm Action</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function viewMessageContent(messageId) {
    showLoading();
    $.get(APP_URL + '/api/admin.php?action=get_message_content&message_id=' + messageId, function(response) {
        hideLoading();
        if (response.success) {
            Swal.fire({
                title: 'Message Content',
                html: '<div class="text-start">' + 
                      '<strong>Content:</strong><br>' + 
                      '<div class="alert alert-light">' + response.data.content + '</div>' +
                      (response.data.media_url ? '<strong>Media:</strong> ' + response.data.media_url : '') +
                      '</div>',
                icon: 'info',
                width: 600
            });
        } else {
            showToast(response.message, 'error');
        }
    });
}

function updateReportStatus(reportId, newStatus) {
    showLoading();
    $.post(APP_URL + '/api/admin.php', {
        action: 'update_message_report_status',
        report_id: reportId,
        status: newStatus
    }, function(response) {
        hideLoading();
        if (response.success) {
            showToast(response.message, 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast(response.message, 'error');
        }
    });
}

function takeAction(reportId, actionType) {
    $('#action_report_id').val(reportId);
    $('#action_type').val(actionType);
    $('#actionModal').modal('show');
}

$('#actionForm').submit(function(e) {
    e.preventDefault();
    const btn = $(this).find('button[type="submit"]');
    btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Processing...');
    
    $.post(APP_URL + '/api/admin.php', $(this).serialize() + '&action=take_message_report_action', function(response) {
        if (response.success) {
            showToast(response.message, 'success');
            $('#actionModal').modal('hide');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast(response.message, 'error');
            btn.prop('disabled', false).html('Confirm Action');
        }
    });
});

function resolveReport(reportId) {
    Swal.fire({
        title: 'Resolve Report',
        input: 'textarea',
        inputLabel: 'Resolution Notes',
        inputPlaceholder: 'Enter resolution notes...',
        showCancelButton: true,
        confirmButtonText: 'Resolve',
        confirmButtonColor: '#22c55e'
    }).then((result) => {
        if (result.isConfirmed) {
            showLoading();
            $.post(APP_URL + '/api/admin.php', {
                action: 'resolve_message_report',
                report_id: reportId,
                admin_notes: result.value
            }, function(response) {
                hideLoading();
                if (response.success) {
                    showToast(response.message, 'success');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showToast(response.message, 'error');
                }
            });
        }
    });
}

function dismissReport(reportId) {
    Swal.fire({
        title: 'Dismiss Report',
        text: 'This report will be marked as dismissed',
        input: 'textarea',
        inputPlaceholder: 'Reason for dismissal...',
        showCancelButton: true,
        confirmButtonText: 'Dismiss',
        confirmButtonColor: '#6b7280'
    }).then((result) => {
        if (result.isConfirmed) {
            showLoading();
            $.post(APP_URL + '/api/admin.php', {
                action: 'dismiss_message_report',
                report_id: reportId,
                admin_notes: result.value
            }, function(response) {
                hideLoading();
                if (response.success) {
                    showToast(response.message, 'success');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showToast(response.message, 'error');
                }
            });
        }
    });
}
</script>

<?php renderAdminFooter(); ?>