<?php

declare(strict_types=1);

namespace App\Repositories;

use PDO;

final class CashboxRepository
{
    public function __construct(private PDO $pdo) {}

    public function search(string $q): array
    {
        $where = ['1=1']; $params = [];
        if ($q !== '') { $where[] = '(name LIKE ?)'; $params[] = "%{$q}%"; }
        $st = $this->pdo->prepare("SELECT id, name, opening_balance, is_active FROM cashboxes WHERE ".implode(' AND ', $where)." ORDER BY is_active DESC, id ASC");
        $st->execute($params);
        return $st->fetchAll() ?: [];
    }

    public function activeAllBasic(): array
    {
        return $this->pdo->query("SELECT id,name,opening_balance FROM cashboxes WHERE is_active=1 ORDER BY id ASC")->fetchAll() ?: [];
    }

    public function activeForSelect(): array
    {
        return $this->pdo->query("SELECT id,name FROM cashboxes WHERE is_active=1 ORDER BY id ASC")->fetchAll() ?: [];
    }

    public function findById(int $id): array|false
    {
        $st = $this->pdo->prepare("SELECT id,name,opening_balance,is_active FROM cashboxes WHERE id=?");
        $st->execute([$id]);
        return $st->fetch();
    }

    public function update(int $id, array $data): void
    {
        $this->pdo->prepare("UPDATE cashboxes SET name=?, opening_balance=?, is_active=? WHERE id=?")
            ->execute([$data['name'], $data['opening_balance'], $data['is_active'], $id]);
    }

    public function create(array $data): int
    {
        $this->pdo->prepare("INSERT INTO cashboxes (name, opening_balance, is_active) VALUES (?,?,?)")
            ->execute([$data['name'], $data['opening_balance'], $data['is_active']]);
        return (int)$this->pdo->lastInsertId();
    }

    public function ledgerRows(int $cashboxId, string $from, string $to): array
    {
        $st = $this->pdo->prepare("SELECT id,trx_date,trx_type,amount,ref_type,ref_id,notes
                    FROM cashbox_transactions
                    WHERE cashbox_id=? AND trx_date >= ? AND trx_date < ?
                    ORDER BY trx_date ASC, id ASC");
        $st->execute([$cashboxId, $from . ' 00:00:00', date('Y-m-d 00:00:00', strtotime($to . ' +1 day'))]);
        return $st->fetchAll() ?: [];
    }
}
