<?php
require_once __DIR__ . '/../../../config/database.php';

$type = $_GET['type'] ?? '';
$value = $_GET['value'] ?? '';

if ($type === 'accounts') {

    $stmt = $pdo->prepare("
        SELECT DISTINCT ba.account_name
        FROM billing_accounts ba
        JOIN billing_customers cu ON cu.id = ba.customer_id
        WHERE cu.customer_name = ?
        ORDER BY ba.account_name ASC
    ");
    $stmt->execute([$value]);

    echo json_encode($stmt->fetchAll(PDO::FETCH_COLUMN));
    exit;
}

if ($type === 'units') {

    $stmt = $pdo->prepare("
        SELECT DISTINCT unit_name
        FROM invoices
        WHERE account_name = ?
        AND unit_name IS NOT NULL
        ORDER BY unit_name ASC
    ");
    $stmt->execute([$value]);

    echo json_encode($stmt->fetchAll(PDO::FETCH_COLUMN));
    exit;
}