<?php

declare(strict_types=1);

namespace App\Models;

class DianResolution extends BaseModel
{
    protected string $table = 'resoluciones_dian';

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

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

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

        $stmt = $this->db()->prepare(
            'SELECT *
             FROM resoluciones_dian
             WHERE empresa_id = :empresa_id
               AND activo = 1
               AND (sucursal_id = :sucursal_id OR sucursal_id IS NULL)
               AND COALESCE(prefijo, "") = :prefijo
               AND CURDATE() BETWEEN fecha_desde AND fecha_hasta
             ORDER BY
                CASE WHEN sucursal_id = :sucursal_id_priority THEN 0 ELSE 1 END,
                id DESC
             LIMIT 1'
        );
        $stmt->execute([
            ':empresa_id' => $companyId,
            ':sucursal_id' => $branchId,
            ':sucursal_id_priority' => $branchId,
            ':prefijo' => trim($prefix),
        ]);

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

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

        $hasBranch = $branchId > 0;
        $stmt = $this->db()->prepare(
            'SELECT *
             FROM resoluciones_dian
             WHERE empresa_id = :empresa_id
               AND activo = 1
               AND (
                    :has_branch = 0
                    OR sucursal_id = :sucursal_id
                    OR sucursal_id IS NULL
               )
               AND CURDATE() BETWEEN fecha_desde AND fecha_hasta
             ORDER BY
                CASE WHEN :has_branch_priority = 1 AND sucursal_id = :sucursal_id_priority THEN 0 ELSE 1 END,
                id DESC
             LIMIT 1'
        );
        $stmt->execute([
            ':empresa_id' => $companyId,
            ':has_branch' => $hasBranch ? 1 : 0,
            ':sucursal_id' => $hasBranch ? $branchId : 0,
            ':has_branch_priority' => $hasBranch ? 1 : 0,
            ':sucursal_id_priority' => $hasBranch ? $branchId : 0,
        ]);

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