<?php
/**
 * App API: Get all accounts (pending + approved + deactivated) in AC/AAC's area.
 * GET user_id = officer's user id.
 * Returns: { success, pending: [], approved: [], deactivated: [] }
 */
require_once __DIR__ . '/../config/cors.php';
require_once __DIR__ . '/../config/db.php';

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

$response = ['success' => false, 'pending' => [], 'approved' => [], 'deactivated' => [], 'message' => ''];

try {
    $officerUserId = isset($_GET['user_id']) ? (int) $_GET['user_id'] : 0;
    if ($officerUserId <= 0) {
        $response['message'] = 'User ID is required';
        echo json_encode($response);
        exit;
    }

    $stmt = $pdo->prepare("SELECT id, role, area FROM users WHERE id = ? AND status = 'approved'");
    $stmt->execute([$officerUserId]);
    $officer = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$officer || !in_array($officer['role'], ['AC', 'AAC'])) {
        $response['message'] = 'Unauthorized. AC or AAC only.';
        echo json_encode($response);
        exit;
    }

    $area = trim($officer['area'] ?? '');
    if ($area === '') {
        $response['success'] = true;
        echo json_encode($response);
        exit;
    }

    $stmt = $pdo->prepare("
        SELECT u.id, u.first_name, u.last_name, u.nroi_id, u.email, u.phone_number,
               u.area, u.role, u.rank, u.status, u.created_at,
               u.gender, u.dob, u.region, u.province, u.city_municipality,
               u.profile_photo
        FROM users u
        WHERE TRIM(COALESCE(u.area, '')) = ?
          AND u.status IN ('pending', 'approved', 'deactivated')
          AND u.id NOT IN (SELECT user_id FROM removed_accounts)
          AND u.id != ?
        ORDER BY u.status ASC, u.last_name ASC, u.first_name ASC
    ");
    $stmt->execute([$area, $officerUserId]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($rows as $row) {
        $s = $row['status'] ?? 'pending';
        if ($s === 'pending') {
            $response['pending'][] = $row;
        } elseif ($s === 'approved') {
            $response['approved'][] = $row;
        } else {
            $response['deactivated'][] = $row;
        }
    }

    $response['success'] = true;
} catch (Throwable $e) {
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
