<?php

namespace App\Helpers;

/**
 * Manipulate the JSON Nigerian bank data
 */
class NigerianBank
{
    private $dataFile;
    private $bankData;

    public function __construct(string $dataFile = __DIR__ . '/data/bank.json')
    {
        $this->dataFile = $dataFile;
        $this->loadData();
    }

    private function loadData()
    {
        $jsonData = file_get_contents($this->dataFile);
        $this->bankData = json_decode($jsonData, true);
    }

    private function saveData()
    {
        $jsonData = json_encode($this->bankData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
        file_put_contents($this->dataFile, $jsonData);
    }

    public function getBankById(int $id)
    {
        foreach ($this->bankData['data'] as $bank) {
            if ($bank['id'] === $id) {
                return $bank;
            }
        }
        return null;
    }

    public function getBankBySlug(string $slug){
        foreach ($this->bankData['data'] as $bank) {
            if ($bank['slug'] === $slug) {
                return $bank;
            }
        }
        return null;
    }

    public function getBankByCode(string $code){
        foreach ($this->bankData['data'] as $bank) {
            if ($bank['code'] === $code) {
                return $bank;
            }
        }
        return null;
    }

    public function updateBankById(int $id, array $newData)
    {
        foreach ($this->bankData['data'] as &$bank) {
            if ($bank['id'] === $id) {
                $bank = array_merge($bank, $newData);
                $this->saveData();
                return true;
            }
        }
        return false;
    }

    public function getAllBanks()
    {
        return $this->bankData['data'];
    }
}
