<?php
/**
 * ============================================================================
 * admin/user-reports.php - User Reports Management
 * Handle reported users with full moderation capabilities
 * ============================================================================
 */

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' => 'User Reports', 'url' => '']
];

// Fetch user reports
try {
    $sql = "SELECT 
                ur.*,
                reporter.full_name as reporter_name,
                reporter.phone_number as reporter_phone,
                reporter.profile_picture as reporter_avatar,
                reported.full_name as reported_name,
                reported.phone_number as reported_phone,
                reported.user_type as reported_user_type,
                reported.profile_picture as reported_avatar,
                reported.is_active as reported_is_active,
                reviewed_by_user.full_name as reviewed_by_name
            FROM user_reports ur
            JOIN users reporter ON ur.reporter_id = reporter.id
            JOIN users reported ON ur.reported_user_id = reported.id
            LEFT JOIN users reviewed_by_user ON ur.reviewed_by = reviewed_by_user.id
            ORDER BY 
                CASE ur.status 
                    WHEN 'pending' THEN 1 
                    WHEN 'reviewing' THEN 2 
                    ELSE 3 
                END,
                ur.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,
                SUM(CASE WHEN report_type = 'harassment' THEN 1 ELSE 0 END) as harassment,
                SUM(CASE WHEN report_type = 'spam' THEN 1 ELSE 0 END) as spam,
                SUM(CASE WHEN report_type = 'fake_profile' THEN 1 ELSE 0 END) as fake_profile
            FROM user_reports";
    $stmt = $db->query($sql);
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    logError('User reports fetch error: ' . $e->getMessage());
    $reports = [];
    $stats = ['total' => 0, 'pending' => 0, 'reviewing' => 0, 'resolved' => 0, 'dismissed' => 0];
}

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

<style>
.report-card {
    transition: all 0.2s ease;
    border-left: 4px solid #6b7280;
}
.report-card:hover {
    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    transform: translateY(-2px);
}
.report-card.pending { border-left-color: #f59e0b; }
.report-card.reviewing { border-left-color: #3b82f6; }
.report-card.resolved { border-left-color: #22c55e; }
.report-card.dismissed { border-left-color: #6b7280; }
.user-avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    object-fit: cover;
}
.evidence-thumbnail {
    width: 80px;
    height: 80px;
    object-fit: cover;
    border-radius: 8px;
    cursor: pointer;
}
</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-person-x me-2"></i>User Reports
        </h2>
        <p class="text-muted mb-0">Review and moderate reported users</p>
    </div>
    <div class="d-flex gap-2">
        <button class="btn btn-outline-primary" onclick="exportReports()">
            <i class="bi bi-download me-2"></i>Export
        </button>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#filterModal">
            <i class="bi bi-funnel me-2"></i>Filter
        </button>
    </div>
</div>

<!-- Statistics Cards -->
<div class="row mb-4">
    <div class="col-lg-2 col-md-4 col-sm-6 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-lg-2 col-md-4 col-sm-6 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-lg-2 col-md-4 col-sm-6 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-lg-2 col-md-4 col-sm-6 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-lg-2 col-md-4 col-sm-6 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 class="col-lg-2 col-md-4 col-sm-6 mb-3">
        <div class="card border-0 shadow-sm text-center">
            <div class="card-body">
                <div class="text-danger small mb-1">Harassment</div>
                <h3 class="mb-0 fw-bold text-danger"><?php echo $stats['harassment']; ?></h3>
            </div>
        </div>
    </div>
</div>

<!-- Filter Tabs -->
<ul class="nav nav-tabs mb-4" id="reportTabs">
    <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="#reviewing">
            Reviewing <span class="badge bg-info ms-1"><?php echo $stats['reviewing']; ?></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="reviewing">
        <?php renderReportsList(array_filter($reports, fn($r) => $r['status'] === 'reviewing')); ?>
    </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: ?>
        <?php foreach ($reports as $report): ?>
        <div class="card border-0 shadow-sm mb-3 report-card <?php echo $report['status']; ?>">
            <div class="card-body">
                <div class="row">
                    <!-- Report Info -->
                    <div class="col-md-8">
                        <!-- Header -->
                        <div class="d-flex justify-content-between align-items-start mb-3">
                            <div>
                                <span class="badge bg-<?php 
                                    echo $report['report_type'] === 'harassment' ? 'danger' : 
                                        ($report['report_type'] === 'spam' ? 'warning' : 
                                        ($report['report_type'] === 'fake_profile' ? 'dark' : 'secondary'));
                                ?> me-2">
                                    <?php echo strtoupper(str_replace('_', ' ', $report['report_type'])); ?>
                                </span>
                                <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 & Reported User -->
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="d-flex align-items-center mb-2">
                                    <img src="<?php echo getAvatarUrl($report['reporter_id']); ?>" 
                                         class="user-avatar me-2">
                                    <div>
                                        <strong class="d-block">Reporter:</strong>
                                        <small><?php echo htmlspecialchars($report['reporter_name']); ?></small><br>
                                        <small class="text-muted"><?php echo htmlspecialchars($report['reporter_phone']); ?></small>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="d-flex align-items-center mb-2">
                                    <img src="<?php echo getAvatarUrl($report['reported_user_id']); ?>" 
                                         class="user-avatar me-2">
                                    <div>
                                        <strong class="d-block">Reported User:</strong>
                                        <small><?php echo htmlspecialchars($report['reported_name']); ?></small>
                                        <span class="badge bg-<?php echo $report['reported_is_active'] ? 'success' : 'danger'; ?> ms-1">
                                            <?php echo $report['reported_is_active'] ? 'Active' : 'Suspended'; ?>
                                        </span>
                                        <br>
                                        <small class="text-muted"><?php echo htmlspecialchars($report['reported_phone']); ?></small>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Description -->
                        <div class="mb-3">
                            <strong>Description:</strong>
                            <p class="mb-0 text-muted"><?php echo nl2br(htmlspecialchars($report['description'] ?? 'No description provided')); ?></p>
                        </div>
                        
                        <!-- Evidence -->
                        <?php if ($report['evidence_urls']): 
                            $evidence = json_decode($report['evidence_urls'], true);
                            if (is_array($evidence) && count($evidence) > 0):
                        ?>
                        <div class="mb-3">
                            <strong>Evidence:</strong>
                            <div class="d-flex gap-2 mt-2">
                                <?php foreach ($evidence as $url): ?>
                                <img src="<?php echo htmlspecialchars($url); ?>" 
                                     class="evidence-thumbnail"
                                     onclick="viewEvidence('<?php echo htmlspecialchars($url); ?>')">
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endif; endif; ?>
                        
                        <!-- Timeline -->
                        <div class="border-top pt-2">
                            <small class="text-muted">
                                <i class="bi bi-clock me-1"></i>Reported: <?php echo timeAgo($report['created_at']); ?>
                                <?php if ($report['reviewed_at']): ?>
                                | <i class="bi bi-check-circle me-1"></i>Reviewed: <?php echo timeAgo($report['reviewed_at']); ?>
                                by <?php echo htmlspecialchars($report['reviewed_by_name']); ?>
                                <?php endif; ?>
                            </small>
                        </div>
                    </div>
                    
                    <!-- Actions -->
                    <div class="col-md-4">
                        <?php if ($report['status'] === 'pending'): ?>
                        <div class="d-grid gap-2">
                            <button class="btn btn-info btn-sm" 
                                    onclick="updateStatus(<?php echo $report['id']; ?>, 'reviewing')">
                                <i class="bi bi-eye me-1"></i>Start Review
                            </button>
                            <button class="btn btn-warning btn-sm" 
                                    onclick="warnUser(<?php echo $report['id']; ?>, <?php echo $report['reported_user_id']; ?>)">
                                <i class="bi bi-exclamation-triangle me-1"></i>Warn User
                            </button>
                            <button class="btn btn-danger btn-sm" 
                                    onclick="suspendUser(<?php echo $report['id']; ?>, <?php echo $report['reported_user_id']; ?>)">
                                <i class="bi bi-ban me-1"></i>Suspend User
                            </button>
                            <button class="btn btn-dark btn-sm" 
                                    onclick="banUser(<?php echo $report['id']; ?>, <?php echo $report['reported_user_id']; ?>)">
                                <i class="bi bi-x-circle me-1"></i>Ban User
                            </button>
                            <button class="btn btn-success btn-sm" 
                                    onclick="resolveReport(<?php echo $report['id']; ?>)">
                                <i class="bi bi-check-circle me-1"></i>Resolve
                            </button>
                            <button class="btn btn-outline-secondary btn-sm" 
                                    onclick="dismissReport(<?php echo $report['id']; ?>)">
                                <i class="bi bi-x me-1"></i>Dismiss
                            </button>
                        </div>
                        <?php elseif ($report['status'] === 'reviewing'): ?>
                        <div class="alert alert-info mb-2">
                            <small><i class="bi bi-eye me-1"></i>Under Review</small>
                        </div>
                        <div class="d-grid gap-2">
                            <button class="btn btn-success btn-sm" 
                                    onclick="resolveReport(<?php echo $report['id']; ?>)">
                                <i class="bi bi-check-circle me-1"></i>Resolve
                            </button>
                            <button class="btn btn-outline-secondary btn-sm" 
                                    onclick="dismissReport(<?php echo $report['id']; ?>)">
                                <i class="bi bi-x me-1"></i>Dismiss
                            </button>
                        </div>
                        <?php else: ?>
                        <div class="alert alert-<?php echo $report['status'] === 'resolved' ? 'success' : 'secondary'; ?> mb-0">
                            <strong><?php echo ucfirst($report['status']); ?></strong>
                            <?php if ($report['admin_notes']): ?>
                            <hr class="my-2">
                            <small><?php echo htmlspecialchars($report['admin_notes']); ?></small>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>
                        
                        <!-- View User Profile -->
                        <button class="btn btn-outline-primary btn-sm w-100 mt-2" 
                                onclick="viewUserProfile(<?php echo $report['reported_user_id']; ?>)">
                            <i class="bi bi-person me-1"></i>View User Profile
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    <?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" id="actionModalTitle">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="user_id" id="action_user_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 affect the reported user's account.
                    </div>
                    <div class="mb-3" id="duration_field" style="display:none;">
                        <label class="form-label">Suspension Duration</label>
                        <select class="form-select" name="duration">
                            <option value="1">1 Day</option>
                            <option value="3">3 Days</option>
                            <option value="7" selected>1 Week</option>
                            <option value="30">1 Month</option>
                            <option value="permanent">Permanent</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Admin Notes *</label>
                        <textarea class="form-control" name="admin_notes" rows="3" required 
                                  placeholder="Explain the reason for this action..."></textarea>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="notify_user" id="notify_user" checked>
                        <label class="form-check-label" for="notify_user">
                            Notify user via email/SMS
                        </label>
                    </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" id="actionConfirmBtn">Confirm</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Evidence Viewer Modal -->
<div class="modal fade" id="evidenceModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Evidence</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body text-center">
                <img id="evidenceImage" src="" class="img-fluid" style="max-height: 70vh;">
            </div>
        </div>
    </div>
</div>

<!-- Filter Modal -->
<div class="modal fade" id="filterModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Filter Reports</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Report Type</label>
                    <select class="form-select" id="filter_type">
                        <option value="">All Types</option>
                        <option value="spam">Spam</option>
                        <option value="harassment">Harassment</option>
                        <option value="fake_profile">Fake Profile</option>
                        <option value="inappropriate_content">Inappropriate Content</option>
                        <option value="scam">Scam</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Status</label>
                    <select class="form-select" id="filter_status">
                        <option value="">All Statuses</option>
                        <option value="pending">Pending</option>
                        <option value="reviewing">Reviewing</option>
                        <option value="resolved">Resolved</option>
                        <option value="dismissed">Dismissed</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Date Range</label>
                    <input type="date" class="form-control mb-2" id="filter_date_from" placeholder="From">
                    <input type="date" class="form-control" id="filter_date_to" placeholder="To">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="clearFilters()">Clear</button>
                <button type="button" class="btn btn-primary" onclick="applyFilters()">Apply Filters</button>
            </div>
        </div>
    </div>
</div>

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

function warnUser(reportId, userId) {
    showActionModal('Warn User', reportId, userId, 'warn', false);
}

function suspendUser(reportId, userId) {
    showActionModal('Suspend User', reportId, userId, 'suspend', true);
}

function banUser(reportId, userId) {
    showActionModal('Ban User', reportId, userId, 'ban', false);
}

function showActionModal(title, reportId, userId, actionType, showDuration) {
    $('#actionModalTitle').text(title);
    $('#action_report_id').val(reportId);
    $('#action_user_id').val(userId);
    $('#action_type').val(actionType);
    $('#duration_field').toggle(showDuration);
    $('#actionConfirmBtn').removeClass().addClass('btn').addClass(
        actionType === 'ban' ? 'btn-dark' : (actionType === 'suspend' ? 'btn-danger' : 'btn-warning')
    );
    $('#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_user_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');
        }
    });
});

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_user_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',
        input: 'textarea',
        inputPlaceholder: 'Reason for dismissal...',
        showCancelButton: true,
        confirmButtonText: 'Dismiss'
    }).then((result) => {
        if (result.isConfirmed) {
            showLoading();
            $.post(APP_URL + '/api/admin.php', {
                action: 'dismiss_user_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 viewEvidence(url) {
    $('#evidenceImage').attr('src', url);
    $('#evidenceModal').modal('show');
}

function viewUserProfile(userId) {
    window.open(APP_URL + '/profile/view.php?id=' + userId, '_blank');
}

function exportReports() {
    window.location.href = APP_URL + '/admin/export-user-reports.php';
}

function applyFilters() {
    // Apply filters logic
    $('#filterModal').modal('hide');
    showToast('Filters applied', 'success');
}

function clearFilters() {
    $('#filter_type, #filter_status').val('');
    $('#filter_date_from, #filter_date_to').val('');
}
</script>

<?php renderAdminFooter(); ?>