<?php

namespace myresto\models;

use Yii;

use myresto\models\SolisPaymentType;
use myresto\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';
    public static $type_con = 'resto';

    /**
     * {@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],
            [['jurnal_referral'], 'string', 'max' => 40],
            [['branch_code'], 'unique'],
            [['type_con'], 'default', 'value'=> 'resto'],
        ];
    }

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

    public function getPaymentData() {
        $data = SolisPaymentType::find()
            ->where(['not in', 'fpkey', [95, 96]])
            ->asArray()
            ->all();
        $data = array_column($data, 'fname', 'fpkey');
        return $data;
    }

    public function getAccountData() {
        $config = self::find()->where(['type_con' => 'resto'])->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()->where(['type_con' => 'resto'])
            ->asArray()
            ->all();
        $syncAccountToJurnal = array_column($syncAccountToJurnal, 'nama_akun', 'payment_fpkey');
        $data = $syncAccountToJurnal + $paymentAccounts;
        return $data;
    }

    public static function getConnection($which = 'MyConnection') {
        if ($which == 'MyConnection')
            $db = Yii::$app->db;
        elseif ($which == 'MyResto')
            $db = Yii::$app->dbMyResto;
        elseif ($which == 'MyRetail')
            $db = Yii::$app->dbMyRetail;

        $dsn = $db->dsn;
        $dsn = explode(';', $dsn);
        
        $dbhost = $dsn[0];
        $dbhost = explode('=', $dbhost);
        $dbhost = $dbhost[1];

        $dbname = $dsn[1];
        $dbname = explode('=', $dbname);
        $dbname = $dbname[1];
        
        $dbuser = $db->username;
        $dbpass = $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;
    }

    public static function getDbNameMyConnection() {
        $db = Yii::$app->db;

        $dsn = $db->dsn;
        $dsn = explode(';', $dsn);
        
        $dbname = $dsn[1];
        $dbname = explode('=', $dbname);
        $dbname = $dbname[1];
        
        return $dbname;
    }

    public static function isEmpty() {
        $empty = false;

        $config = self::find()->where(['type_con' => 'resto'])->one();
        if (empty($config))
            $empty = true;
        elseif (empty($config->api_key))
            $empty = true;

        return $empty;
    }
}
