<?php

declare(strict_types=1);

namespace App\Models;

class CashBox extends BaseModel
{
    protected string $table = 'cajas';

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

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

    public function listByBranch(int $companyId, int $branchId): array
    {
        $stmt = $this->db()->prepare(
            'SELECT id, nombre, estado, created_at
             FROM cajas
             WHERE empresa_id = :empresa_id
               AND sucursal_id = :sucursal_id
             ORDER BY id DESC'
        );
        $stmt->execute([
            ':empresa_id' => $companyId,
            ':sucursal_id' => $branchId,
        ]);

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

    public function existsName(int $companyId, int $branchId, string $name): bool
    {
        $stmt = $this->db()->prepare(
            'SELECT 1
             FROM cajas
             WHERE empresa_id = :empresa_id
               AND sucursal_id = :sucursal_id
               AND nombre = :nombre
             LIMIT 1'
        );
        $stmt->execute([
            ':empresa_id' => $companyId,
            ':sucursal_id' => $branchId,
            ':nombre' => trim($name),
        ]);

        return (bool) $stmt->fetchColumn();
    }

    public function findByIdAndCompany(int $companyId, int $cashBoxId): ?array
    {
        $stmt = $this->db()->prepare(
            'SELECT *
             FROM cajas
             WHERE id = :id
               AND empresa_id = :empresa_id
             LIMIT 1'
        );
        $stmt->execute([
            ':id' => $cashBoxId,
            ':empresa_id' => $companyId,
        ]);

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