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

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

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

try {
    $stmt = $pdo->prepare("SELECT role, area FROM users WHERE id = ? AND status = 'approved'");
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$user || empty($user['area'])) {
        echo json_encode(['status' => 'error', 'message' => 'User or area not found']);
        exit;
    }

    $role = strtoupper(trim($user['role'] ?? ''));
    $area = $user['area'];

    $recipientType = '';
    $list = [];

    if (in_array($role, ['R.O', 'C.R.O']) || $role === '') {
        $recipientType = 'ac_aac_same_area';
        $stmt = $pdo->prepare("SELECT id, first_name, last_name, nroi_id FROM users WHERE status = 'approved' AND area = ? AND UPPER(TRIM(role)) IN ('AC', 'AAC') ORDER BY last_name, first_name");
        $stmt->execute([$area]);
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $list[] = [
                'id' => (int) $row['id'],
                'name' => trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? '')),
                'nroi_id' => $row['nroi_id'] ?? '',
            ];
        }
    } elseif ($role === 'AC' || $role === 'AAC') {
        $recipientType = 'area_members_or_specific';
        $stmt = $pdo->prepare("SELECT id, first_name, last_name, nroi_id FROM users WHERE status = 'approved' AND area = ? AND (UPPER(TRIM(role)) IN ('R.O', 'C.R.O') OR role = '' OR role IS NULL) ORDER BY last_name, first_name");
        $stmt->execute([$area]);
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $list[] = [
                'id' => (int) $row['id'],
                'name' => trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? '')),
                'nroi_id' => $row['nroi_id'] ?? '',
            ];
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Role cannot use this']);
        exit;
    }

    echo json_encode([
        'status' => 'success',
        'recipient_type' => $recipientType,
        'area' => $area,
        'list' => $list,
    ]);
} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
