<?php

namespace nota\models;

use Yii;

class PaymentSettings extends \yii\db\ActiveRecord
{
    public static function getDb() {
        return Yii::$app->get('dbnota'); 
    }

    public static function tableName()
    {
        return 'payment_settings';
    }

    public function rules()
    {
        return [
            [['payment_method_id'],'required'],
            [['account_number','owner_name','bank_name'],'safe'],
        ];
    }

    // Relasi ke PaymentMethod
    public function getPaymentMethod()
    {
        return $this->hasOne(PaymentMethod::class, ['id' => 'payment_method_id']);
    }

    // Ambil semua setting indexed by code
    // Ambil semua rekening per metode
    // Ambil semua setting indexed by code
    public static function getAllSettings()
    {
        $rows = self::find()->with('paymentMethod')->where(['payment_settings.idCluster'=>Yii::$app->user->identity->idCluster])->all();
        $settings = [];
        foreach($rows as $row){
            if($row->paymentMethod){
                $settings[$row->paymentMethod->code][] = [
                    'bank_name' => $row->bank_name,
                    'account_number' => $row->account_number,
                    'owner_name' => $row->owner_name ?? ''
                ]; 
            }
        }
        return $settings;
    }

    // Dropdown fleksibel
    public static function getDropdownOptions()
    {
        $rows = self::find()->with('paymentMethod')->where(['idCluster'=>Yii::$app->user->identity->idCluster])->all();
        $options = [];
        foreach($rows as $row){
            if($row->paymentMethod){
                $label = $row->paymentMethod->name;
                if($row->account_number){
                    $label .= " ({$row->account_number})";
                }
                $options[$row->payment_method_id] = $label;
            }
        }
        return $options;
    }
}
