<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/database.php';

class BankCard
{
    public function all(): array
    {
        $stmt = db()->query('SELECT * FROM bank_cards ORDER BY sort_order ASC, id ASC');
        return $stmt->fetchAll() ?: [];
    }

    public function active(): array
    {
        $stmt = db()->prepare('SELECT * FROM bank_cards WHERE is_active = 1 ORDER BY sort_order ASC, id ASC');
        $stmt->execute();
        return $stmt->fetchAll() ?: [];
    }

    public function find(int $id): ?array
    {
        $stmt = db()->prepare('SELECT * FROM bank_cards WHERE id = :id LIMIT 1');
        $stmt->execute(['id' => $id]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    public function create(array $data): bool
    {
        $stmt = db()->prepare(
            'INSERT INTO bank_cards (bank_name, card_number_masked, card_holder, iban, sort_order, is_active)
             VALUES (:bank_name, :card_number_masked, :card_holder, :iban, :sort_order, :is_active)'
        );
        return $stmt->execute([
            'bank_name' => $data['bank_name'],
            'card_number_masked' => $data['card_number_masked'],
            'card_holder' => $data['card_holder'],
            'iban' => $data['iban'] ?: null,
            'sort_order' => (int)$data['sort_order'],
            'is_active' => (int)(bool)$data['is_active'],
        ]);
    }

    public function update(int $id, array $data): bool
    {
        $stmt = db()->prepare(
            'UPDATE bank_cards SET bank_name=:bank_name, card_number_masked=:card_number_masked,
             card_holder=:card_holder, iban=:iban, sort_order=:sort_order, is_active=:is_active WHERE id=:id'
        );
        return $stmt->execute([
            'id' => $id,
            'bank_name' => $data['bank_name'],
            'card_number_masked' => $data['card_number_masked'],
            'card_holder' => $data['card_holder'],
            'iban' => $data['iban'] ?: null,
            'sort_order' => (int)$data['sort_order'],
            'is_active' => (int)(bool)$data['is_active'],
        ]);
    }

    public function delete(int $id): bool
    {
        $stmt = db()->prepare('DELETE FROM bank_cards WHERE id = :id');
        return $stmt->execute(['id' => $id]);
    }
}
