<?php
/**
 * سودانا — Content Reports API v21
 * البلاغات على المحتوى المخالف
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE
$ctx = Kernel::handle(['auth' => true]);
$u   = $ctx['user'];
$b = json_decode(file_get_contents('php://input'), true) ?? [];

$action = $_GET['action'] ?? ($b['action'] ?? 'create');
$isStaff = !empty($u['user_type']) && in_array($u['user_type'], ['admin','staff','moderator']);

// ── CREATE REPORT ───────────────────────────────────────────
if ($action === 'create') {
    if (!check_rate_limit('report_'.$u['id'], 10, 3600))
        Kernel::fail('rate_limit', '', 429);

    $contentType = $b['content_type'] ?? '';
    $contentId   = (int)($b['content_id'] ?? 0);
    $reason      = $b['reason'] ?? 'other';
    $details     = mb_substr(trim($b['details'] ?? ''), 0, 500);

    $allowedTypes   = ['pulse_post','market_item','provider_profile','consultation_message','event','comment'];
    $allowedReasons = ['spam','misleading','inappropriate','dangerous','medical_misinformation','harassment','other'];

    if (!in_array($contentType, $allowedTypes)) Kernel::fail('invalid_content_type', '', 400);
    if (!$contentId) Kernel::fail('content_id_required', '', 400);
    if (!in_array($reason, $allowedReasons)) $reason = 'other';

    try {
        db()->prepare(
            'INSERT INTO content_reports (reporter_id, content_type, content_id, reason, details)
             VALUES (?,?,?,?,?)
             ON DUPLICATE KEY UPDATE reason=VALUES(reason), details=VALUES(details)'
        )->execute([$u['id'], $contentType, $contentId, $reason, $details]);
    } catch (Throwable $e) {
        if (str_contains($e->getMessage(), 'Duplicate'))
            Kernel::fail('already_reported', 'أبلغت عن هذا المحتوى مسبقاً', 409);
        Kernel::fail('server_error', '', 500);
    }

    // Auto-flag if reports reach threshold
    try {
        $count = db()->prepare("SELECT COUNT(*) FROM content_reports WHERE content_type=? AND content_id=? AND status='pending'");
        $count->execute([$contentType, $contentId]);
        if ((int)$count->fetchColumn() >= 5) {
            // Notify staff — content is widely reported
            $token = get_user_token(1); // admin
            if ($token) send_push($token, '⚠️ محتوى مُبلَّغ عنه كثيراً', "$contentType #$contentId وصل 5+ بلاغات");
        }
    } catch (Throwable $ignored) {}

    json_response(['success'=>true,'message'=>'تم إرسال البلاغ — سيُراجَع خلال 24 ساعة']);
}

// ── LIST (staff) ─────────────────────────────────────────────
if ($action === 'list') {
    if (!$isStaff) Kernel::fail('not_staff', '', 403);
    $st = db()->prepare(
        "SELECT cr.*, u.name AS reporter_name,
         (SELECT COUNT(*) FROM content_reports cr2 WHERE cr2.content_type=cr.content_type AND cr2.content_id=cr.content_id) AS total_reports
         FROM content_reports cr JOIN users u ON u.id=cr.reporter_id
         WHERE cr.status='pending' ORDER BY total_reports DESC, cr.created_at ASC LIMIT 50"
    );
    $st->execute();
    json_response(['success'=>true,'reports'=>$st->fetchAll()]);
}

// ── REVIEW (staff) ───────────────────────────────────────────
if ($action === 'review') {
    if (!$isStaff) Kernel::fail('not_staff', '', 403);
    $reportId   = (int)($b['report_id'] ?? 0);
    $decision   = $b['decision'] ?? ''; // dismiss|warn|delete|ban
    $actionNote = mb_substr(trim($b['action_note'] ?? ''), 0, 300);

    if (!$reportId || !$decision) Kernel::fail('missing_fields', '', 400);

    $statusMap = ['dismiss'=>'dismissed','warn'=>'action_taken','delete'=>'action_taken','ban'=>'action_taken'];
    $status    = $statusMap[$decision] ?? 'reviewed';

    db()->prepare(
        "UPDATE content_reports SET status=?, action_taken=?, reviewed_by=?, reviewed_at=NOW()
         WHERE id=?"
    )->execute([$status, $decision.': '.$actionNote, $u['id'], $reportId]);

    json_response(['success'=>true,'message'=>"تم تسجيل القرار: $decision"]);
}

Kernel::fail('unknown_action', '', 400);
