<?php
/**
 * ajax/reviewer_feedback_stats.php
 * Returns JSON: how many reviews each reviewer submitted in the given range,
 * plus average days taken from assignment to review submission.
 * Used by Tab 3 (Feedback Received) in live_feedback.php
 */
session_start();
include __DIR__ . '/../config/db.php';
include __DIR__ . '/../config/auth.php';
require_role('admin');

header('Content-Type: application/json');

$range = trim($_GET['range'] ?? '7');
$from  = trim($_GET['from']  ?? '');
$to    = trim($_GET['to']    ?? '');

function buildDateRange($range, $from, $to) {
    switch ($range) {
        case 'today':     return ["DATE(rv.reviewed_at) = CURDATE()", []];
        case 'yesterday': return ["DATE(rv.reviewed_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)", []];
        case 'custom':
            if ($from && $to)   return ["DATE(rv.reviewed_at) BETWEEN ? AND ?", [$from, $to]];
            if ($from)          return ["DATE(rv.reviewed_at) >= ?", [$from]];
            if ($to)            return ["DATE(rv.reviewed_at) <= ?", [$to]];
            return ["1=1", []];
        default:
            $days = is_numeric($range) ? (int)$range : 7;
            return ["rv.reviewed_at >= DATE_SUB(NOW(), INTERVAL $days DAY)", []];
    }
}

[$dateWhere, $dateParams] = buildDateRange($range, $from, $to);

try {
    $stmt = $pdo->prepare("
        SELECT
            rev.id         AS reviewer_id,
            CONCAT(u.first_name,' ',u.last_name) AS reviewer,
            u.email        AS reviewer_email,
            rev.reviewing_interests,

            COUNT(rv.id)   AS feedback_count,
            ROUND(
                AVG(
                    CASE
                        WHEN ra.request_sent_date IS NOT NULL AND rv.reviewed_at IS NOT NULL
                        THEN DATEDIFF(rv.reviewed_at, ra.request_sent_date)
                    END
                ), 1
            )              AS avg_days

        FROM reviews rv
        JOIN reviewers rev ON rev.id = rv.reviewer_id
        JOIN users u       ON u.user_id = rev.user_id
        LEFT JOIN review_assignments ra ON ra.submission_id = rv.submission_id
                                       AND ra.reviewer_id   = rev.id
        WHERE rv.reviewed_at IS NOT NULL
          AND $dateWhere
        GROUP BY rev.id, u.first_name, u.last_name, u.email, rev.reviewing_interests
        ORDER BY feedback_count DESC
    ");
    $stmt->execute($dateParams);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($rows as &$r) {
        if ($r['reviewing_interests']) {
            $decoded = json_decode($r['reviewing_interests'], true);
            if (is_array($decoded)) {
                $r['reviewing_interests'] = implode(', ', $decoded);
            }
        }
    }

    echo json_encode($rows);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}