<?php
require_once '../config/cors.php';
header('Content-Type: application/json');

require_once '../config/db.php';

try {
    $userId = isset($_GET['user_id']) ? (int) $_GET['user_id'] : 0;
    if (empty($userId)) {
        echo json_encode(['status' => 'error', 'message' => 'user_id required']);
        exit;
    }

    // Helper: get user total points
    function getUserTotalPoints($pdo, $uid)
    {
        $s = $pdo->prepare("
            SELECT
                (SELECT COALESCE(SUM(mp.points), 0) FROM match_points mp JOIN match_schedules ms ON mp.match_id = ms.id WHERE mp.user_id = ?) +
                (SELECT COALESCE(SUM(points), 0) FROM manual_match_points WHERE user_id = ?) as total_points
        ");
        $s->execute([$uid, $uid]);
        return (float) $s->fetchColumn();
    }

    // ── 1. Match‑signification notifications ──────────────────────────────
    // We fetch ALL significations for this user so the app can build rich notifications.
    // Extra columns: reviewer_role, withdrawal_reason, officer_remarks, deduction_points
    $stmt = $pdo->prepare("
        SELECT
            ms.id,
            ms.match_id,
            ms.status,
            ms.reviewed_at,
            ms.created_at,
            ms.withdrawal_reason,
            ms.officer_remarks,
            m.match_name,
            m.start_date,
            m.end_date,
            m.location,
            m.match_level,
            COALESCE(
                (SELECT al.performed_by_role FROM activity_logs al 
                 WHERE al.reference_type = 'match_signification' 
                   AND al.reference_id = ms.id 
                   AND al.performed_by_role IN ('AC', 'AAC', 'ADMIN', 'RM')
                 ORDER BY al.id DESC LIMIT 1),
                CASE WHEN ms.reviewed_by = m.rm_id THEN 'RM' ELSE u_reviewer.role END
            ) AS reviewer_role,
            u_reviewer.first_name AS reviewer_first,
            u_reviewer.last_name  AS reviewer_last,
            (SELECT 1 FROM activity_logs al 
             WHERE al.reference_type = 'match_signification' 
               AND al.reference_id = ms.id 
               AND al.id = (SELECT max(id) FROM activity_logs al2 WHERE al2.reference_type = 'match_signification' AND al2.reference_id = ms.id)
               AND al.description LIKE '%Rejected withdrawal%') as is_withdrawal_rejected
        FROM match_significations ms
        JOIN match_schedules m  ON m.id  = ms.match_id
        LEFT JOIN users u_reviewer ON u_reviewer.id = ms.reviewed_by
        WHERE ms.user_id = ?
          AND m.end_date >= CURDATE()
        ORDER BY COALESCE(ms.reviewed_at, ms.created_at) DESC
    ");
    $stmt->execute([$userId]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Fetch demerit (negative) points from match_points for withdrawn matches
    $demerits = [];
    $demeritStmt = $pdo->prepare("
        SELECT match_id, SUM(points) as demerit
        FROM match_points
        WHERE user_id = ? AND rm_signature = 'DEMERIT' AND points < 0
        GROUP BY match_id
    ");
    $demeritStmt->execute([$userId]);
    foreach ($demeritStmt->fetchAll(PDO::FETCH_ASSOC) as $d) {
        $demerits[(int) $d['match_id']] = abs((float) $d['demerit']);
    }

    // Compute total points once (used in withdrawal notifications)
    $totalPoints = getUserTotalPoints($pdo, $userId);

    $notifications = [];
    foreach ($rows as $r) {
        $deductionPts = $demerits[(int) $r['match_id']] ?? 0;
        $reviewerRole = strtoupper(trim($r['reviewer_role'] ?? ''));
        $roleMap = ['AC' => 'AC', 'AAC' => 'AAC', 'ADMIN' => 'Admin', 'RM' => 'RM'];
        $reviewerLabel = isset($roleMap[$reviewerRole]) ? $roleMap[$reviewerRole] : (empty($reviewerRole) ? '' : $reviewerRole);

        $notifications[] = [
            'id' => (int) $r['id'],
            'match_id' => (int) $r['match_id'],
            'match_name' => $r['match_name'],
            'match_level' => $r['match_level'],
            'status' => $r['status'],
            'reviewed_at' => $r['reviewed_at'],
            'created_at' => $r['created_at'],
            'location' => $r['location'],
            'start_date' => $r['start_date'],
            'end_date' => $r['end_date'],
            'withdrawal_reason' => $r['withdrawal_reason'] ?? '',
            'officer_remarks' => $r['officer_remarks'] ?? '',
            'reviewer_role' => $reviewerLabel,
            'deduction_points' => $deductionPts,
            'is_withdrawal_rejected' => (bool) ($r['is_withdrawal_rejected'] ?? false),
            // remaining_points only attached to withdrawn items
            'remaining_points' => ($r['status'] === 'withdrawn' && $deductionPts > 0) ? $totalPoints : null,
        ];
    }

    echo json_encode([
        'status' => 'success',
        'data' => $notifications,
    ]);
} catch (PDOException $e) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Database error: ' . $e->getMessage(),
    ]);
}
