<?php

namespace backend\models;

use Yii;

use backend\models\SolisPaymentType;
use backend\models\SyncAccountToJurnal;

/**
 * This is the model class for table "sync_config".
 *
 * @property string $inventory_account_number
 * @property string $tax_name
 * @property string $branch_code
 * @property string $branch_name
 * @property string $api_key
 */
class SyncConfig extends \yii\db\ActiveRecord {
    public $accountPayments = array();
    public static $base = 'api';

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'sync_config';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['branch_code'], 'required'],
            [['inventory_account_number'], 'string', 'max' => 20],
            [['asset_account_name'], 'string', 'max' => 40],
            [['income_account_name'], 'string', 'max' => 40],
            [['tax_name'], 'string', 'max' => 40],
            [['branch_code'], 'string', 'max' => 10],
            [['branch_name'], 'string', 'max' => 255],
            [['api_key'], 'string', 'max' => 50],
            [['branch_code'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'inventory_account_number' => 'Inventory Account Number',
            'asset_account_name' => 'Asset Account Name',
            'income_account_name' => 'Income Account Name',
            'tax_name' => 'Tax Name',
            'branch_code' => 'Branch Code',
            'branch_name' => 'Branch Name',
            'api_key' => 'API Key',
        ];
    }

    public function getPaymentData() {
        $data = SolisPaymentType::find()
            ->asArray()
            ->all();
        $data = array_column($data, 'fname', 'fpkey');
        return $data;
    }

    public function getAccountData() {
        $config = self::find()->one();
        $access_token = $config->api_key;
        $base = self::$base;

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://$base.jurnal.id/core/api/v1/accounts",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_POSTFIELDS => "",
            CURLOPT_HTTPHEADER => array(
                "apikey: $access_token"
          ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            return "cURL Error #:" . $err;
        } else {
            $data = json_decode($response, TRUE); //data array yang dari jurnal nanti yang diambil name nya
            $data = array_column($data['accounts'], 'name', 'name');
            return $data;
        }
    }

    public function getPaymentAccountData() {
        $payments = self::getPaymentData();
        $paymentAccounts = array_keys($payments);
        $paymentAccounts = array_fill_keys($paymentAccounts, null);

        $syncAccountToJurnal = SyncAccountToJurnal::find()
            ->asArray()
            ->all();
        $syncAccountToJurnal = array_column($syncAccountToJurnal, 'nama_akun', 'payment_fpkey');
        $data = $syncAccountToJurnal + $paymentAccounts;
        return $data;
    }

    public static function getConnection() {
        $dsn = Yii::$app->db->dsn;
        $dsn = explode(';', $dsn);
        
        $dbhost = $dsn[0];
        $dbhost = explode('=', $dbhost);
        $dbhost = $dbhost[1];

        $dbname = $dsn[1];
        $dbname = explode('=', $dbname);
        $dbname = $dbname[1];
        
        $dbuser = Yii::$app->db->username;
        $dbpass = Yii::$app->db->password;
        

        date_default_timezone_set("Asia/Jakarta");
        // melakukan koneksi ke database
        $conn = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
        // cek koneksi yang kita lakukan berhasil atau tidak
        if (!$conn) {
           // jika terjadi error, matikan proses dengan die() atau exit();
           die('Maaf koneksi gagal: '. mysqli_connect_error());
        }
        return $conn;
    }
}
