<?php
require_once __DIR__ . '/includes/base.php';
$breadcrumbs = [['title' => 'Reports', 'url' => '']];

try {
    $sql = "SELECT r.*, 
            reporter.full_name as reporter_name,
            CASE 
                WHEN r.report_type = 'user' THEN u.full_name
                WHEN r.report_type = 'product' THEN p.product_name
                ELSE 'N/A'
            END as reported_item_name
            FROM reports r
            JOIN users reporter ON r.reporter_id = reporter.id
            LEFT JOIN users u ON r.report_type = 'user' AND r.reported_item_id = u.id
            LEFT JOIN products p ON r.report_type = 'product' AND r.reported_item_id = p.id
            ORDER BY r.created_at DESC";
    $reports = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    
    $stats = [
        'pending' => count(array_filter($reports, fn($r) => $r['status'] === 'pending')),
        'reviewing' => count(array_filter($reports, fn($r) => $r['status'] === 'reviewing')),
        'resolved' => count(array_filter($reports, fn($r) => $r['status'] === 'resolved'))
    ];
} catch (PDOException $e) {
    $reports = [];
    $stats = ['pending' => 0, 'reviewing' => 0, 'resolved' => 0];
}

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

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold">User Reports</h2>
        <p class="text-muted mb-0">Review and resolve user-submitted reports</p>
    </div>
</div>

<div class="row mb-4">
    <div class="col-md-4 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h4 class="text-warning mb-0"><?php echo $stats['pending']; ?></h4>
                <small class="text-muted">Pending</small>
            </div>
        </div>
    </div>
    <div class="col-md-4 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h4 class="text-info mb-0"><?php echo $stats['reviewing']; ?></h4>
                <small class="text-muted">Reviewing</small>
            </div>
        </div>
    </div>
    <div class="col-md-4 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <h4 class="text-success mb-0"><?php echo $stats['resolved']; ?></h4>
                <small class="text-muted">Resolved</small>
            </div>
        </div>
    </div>
</div>

<div class="card shadow-sm border-0">
    <div class="card-body p-0">
        <table class="table table-hover mb-0" id="reportsTable">
            <thead class="table-light">
                <tr>
                    <th>Reporter</th>
                    <th>Type</th>
                    <th>Reported Item</th>
                    <th>Reason</th>
                    <th>Status</th>
                    <th>Date</th>
                    <th class="text-end">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($reports as $report): ?>
                <tr>
                    <td><?php echo htmlspecialchars($report['reporter_name']); ?></td>
                    <td><span class="badge bg-info"><?php echo ucfirst($report['report_type']); ?></span></td>
                    <td><?php echo htmlspecialchars($report['reported_item_name']); ?></td>
                    <td><small><?php echo htmlspecialchars(substr($report['reason'], 0, 50)) . '...'; ?></small></td>
                    <td>
                        <span class="badge bg-<?php 
                            echo $report['status'] === 'resolved' ? 'success' : 
                                ($report['status'] === 'reviewing' ? 'info' : 'warning'); 
                        ?>">
                            <?php echo ucfirst($report['status']); ?>
                        </span>
                    </td>
                    <td><small class="text-muted"><?php echo date('M d, Y', strtotime($report['created_at'])); ?></small></td>
                    <td class="text-end">
                        <div class="btn-group btn-group-sm">
                            <button class="btn btn-outline-info" onclick='viewReport(<?php echo json_encode($report); ?>)'>
                                <i class="bi bi-eye"></i>
                            </button>
                            <?php if ($report['status'] !== 'resolved'): ?>
                            <button class="btn btn-outline-success" onclick="resolveReport(<?php echo $report['id']; ?>)">
                                <i class="bi bi-check-lg"></i>
                            </button>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- View Modal -->
<div class="modal fade" id="viewModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-flag me-2"></i>Report Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="reportContent"></div>
        </div>
    </div>
</div>

<!-- Resolve Modal -->
<div class="modal fade" id="resolveModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Resolve Report</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="resolveForm">
                <div class="modal-body">
                    <input type="hidden" name="id" id="resolveId">
                    <div class="mb-3">
                        <label>Resolution *</label>
                        <select class="form-select" name="status" required>
                            <option value="resolved">Mark as Resolved</option>
                            <option value="dismissed">Dismiss Report</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label>Admin Notes *</label>
                        <textarea class="form-control" name="admin_notes" rows="4" required></textarea>
                    </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-success">Resolve</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    $('#reportsTable').DataTable({pageLength: 25, order: [[5, 'desc']]});
});

function viewReport(report) {
    $('#reportContent').html(`
        <h5>Report Information</h5>
        <table class="table">
            <tr><th>Reporter:</th><td>${report.reporter_name}</td></tr>
            <tr><th>Type:</th><td>${report.report_type}</td></tr>
            <tr><th>Item:</th><td>${report.reported_item_name}</td></tr>
            <tr><th>Status:</th><td><span class="badge bg-${report.status === 'resolved' ? 'success' : 'warning'}">${report.status}</span></td></tr>
        </table>
        <h6>Reason:</h6>
        <p>${report.reason}</p>
        ${report.admin_notes ? `<div class="alert alert-info"><strong>Admin Notes:</strong> ${report.admin_notes}</div>` : ''}
    `);
    new bootstrap.Modal(document.getElementById('viewModal')).show();
}

function resolveReport(id) {
    $('#resolveId').val(id);
    new bootstrap.Modal(document.getElementById('resolveModal')).show();
}

$('#resolveForm').submit(function(e) {
    e.preventDefault();
    $.post(APP_URL + '/api/admin.php', $(this).serialize() + '&action=resolve_report')
    .done(function(r) {
        if (r.success) {
            showToast(r.message, 'success');
            $('#resolveModal').modal('hide');
            setTimeout(() => location.reload(), 1000);
        }
    });
});
</script>

<?php renderAdminFooter(); ?>