<?php
require "../config/database.php";
require "../includes/auth.php";

header("Content-Type: application/json; charset=utf-8");
requireApiAuth();

$userId = (int)($_SESSION["user"]["id"] ?? 0);
$roleId = (int)($_SESSION["user"]["role_id"] ?? 0);

$invoiceId = (int)($_GET["id"] ?? 0);

if ($invoiceId > 0) {
    $stmt = $pdo->prepare("
        SELECT *
        FROM payment_invoices
        WHERE id = ?
          AND (
            ? = 1 OR
            company_id = ? OR
            agency_id = ?
          )
        LIMIT 1
    ");
    $stmt->execute([$invoiceId, $roleId, $userId, $userId]);
    $invoice = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$invoice) {
        http_response_code(404);
        echo json_encode(["success" => false, "error" => "invoice_not_found"]);
        exit;
    }
    echo json_encode(["success" => true, "data" => $invoice]);
    exit;
}

$stmt = $pdo->prepare("
    SELECT *
    FROM payment_invoices
    WHERE (? = 1 OR company_id = ? OR agency_id = ?)
    ORDER BY id DESC
");
$stmt->execute([$roleId, $userId, $userId]);

echo json_encode([
    "success" => true,
    "data" => $stmt->fetchAll(PDO::FETCH_ASSOC)
]);
