<?php

require_once __DIR__ . '/../../core/database.php';
require_once __DIR__ . '/BillingHelpers.php';

class BillingDocumentTypeService
{
    private $pdo;

    public function __construct(?PDO $pdo = null)
    {
        $this->pdo = $pdo ?: db();
    }

    public function getIssuedType($documentKey, $environment = 'sandbox')
    {
        $environment = billing_normalize_environment($environment);

        $stmt = $this->pdo->prepare("\n            SELECT *\n            FROM billing_document_types\n            WHERE document_key = ?\n              AND direction = 'issued'\n              AND is_active = 1\n            LIMIT 1\n        ");
        $stmt->execute(array($documentKey));
        $type = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$type) {
            throw new InvalidArgumentException('Tipo de documento no configurado: ' . $documentKey);
        }

        $type['environment_enabled'] = $environment === 'production'
            ? ((int) $type['enabled_production'] === 1)
            : ((int) $type['enabled_sandbox'] === 1);

        return $type;
    }

    public function listIssuedTypes($environment = 'sandbox')
    {
        $environment = billing_normalize_environment($environment);
        $enabledColumn = $environment === 'production' ? 'enabled_production' : 'enabled_sandbox';

        $stmt = $this->pdo->query("\n            SELECT *\n            FROM billing_document_types\n            WHERE direction = 'issued'\n              AND is_active = 1\n            ORDER BY document_family ASC, document_label ASC\n        ");

        $items = array();
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
            $row['environment_enabled'] = (int) $row[$enabledColumn] === 1;
            $items[] = $row;
        }

        return $items;
    }
}
