<?php

declare(strict_types=1);

namespace App\Models;

class DocumentNumbering extends BaseModel
{
    protected string $table = 'numeraciones_documentos';

    public function listByCompany(int $companyId): array
    {
        $stmt = $this->db()->prepare(
            'SELECT nd.*, s.nombre AS sucursal
             FROM numeraciones_documentos nd
             LEFT JOIN sucursales s ON s.id = nd.sucursal_id
             WHERE nd.empresa_id = :empresa_id
             ORDER BY nd.id DESC'
        );
        $stmt->execute([':empresa_id' => $companyId]);

        return $stmt->fetchAll() ?: [];
    }

    public function findByTypeAndPrefix(int $companyId, string $type, ?string $prefix, ?int $branchId = null): ?array
    {
        $normalizedPrefix = trim((string) ($prefix ?? ''));
        $normalizedBranchId = $branchId !== null && $branchId > 0 ? $branchId : null;

        $sql = 'SELECT *
                FROM numeraciones_documentos
                WHERE empresa_id = :empresa_id
                  AND tipo_documento = :tipo_documento
                  AND COALESCE(prefijo, "") = :prefijo';
        $bindings = [
            ':empresa_id' => $companyId,
            ':tipo_documento' => trim(strtolower($type)),
            ':prefijo' => $normalizedPrefix,
        ];

        if ($normalizedBranchId === null) {
            $sql .= ' AND sucursal_id IS NULL';
        } else {
            $sql .= ' AND sucursal_id = :sucursal_id';
            $bindings[':sucursal_id'] = $normalizedBranchId;
        }

        $sql .= ' LIMIT 1';

        $stmt = $this->db()->prepare($sql);
        $stmt->execute($bindings);

        $row = $stmt->fetch();
        return $row ?: null;
    }

    public function activeByTypeForBranch(int $companyId, string $type, int $branchId): ?array
    {
        if ($companyId <= 0 || $branchId <= 0) {
            return null;
        }

        $stmt = $this->db()->prepare(
            'SELECT *
             FROM numeraciones_documentos
             WHERE empresa_id = :empresa_id
               AND tipo_documento = :tipo_documento
               AND activo = 1
               AND (sucursal_id = :sucursal_id OR sucursal_id IS NULL)
             ORDER BY
                CASE WHEN sucursal_id = :sucursal_id_priority THEN 0 ELSE 1 END,
                id ASC
             LIMIT 1'
        );
        $stmt->execute([
            ':empresa_id' => $companyId,
            ':tipo_documento' => trim(strtolower($type)),
            ':sucursal_id' => $branchId,
            ':sucursal_id_priority' => $branchId,
        ]);

        $row = $stmt->fetch();
        return $row ?: null;
    }
}
