<?php
namespace backend\models;

use Yii;
use yii\base\Model;
use backend\models\SyncConfig;

class ImportPayment extends Model {
    public $tipe_tabel = "rst_fc_payment";

    public function kirimData($data, $access_token, $endpoint) {
        $base = SyncConfig::$base;
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://$base.jurnal.id/core/api/v1/$endpoint",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => array(
                "apikey: $access_token",
                "Content-Type: application/json"
            )
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }

    public function simpanStatus($data, $tipe_tabel, $id_lokal) {
        $conn = SyncConfig::getConnection();
        $tgl = date("Y-m-d H:i:s");
        $berhasil = 0;
        $data = json_decode($data, TRUE);
        for ($i=0; $i < count($data['receive_payments']); $i++) {
            $id = $id_lokal[$i];
            $status = $data['receive_payments'][$i]['receive_payment']['status'];
            $id_jurnal = 0;
            // BEGIN - Proses simpan status yang mendapat status code 201
            if ($status == 201) {
                $id_jurnal = $data['receive_payments'][$i]['receive_payment']['content']['id'];
                $status_sinkron = "success";
                $ket = "";
                $berhasil++;
            } else {
                $status_sinkron = "failed";
                $ket = json_encode($data['receive_payments'][$i]['receive_payment']['content']);
                $ket = addslashes($ket);
            }
            $stmt = mysqli_query($conn, "SELECT tipe_tabel, id_record FROM sync_to_jurnal WHERE tipe_tabel = '$tipe_tabel' AND id_record = '$id'");
            if (mysqli_fetch_assoc($stmt) < 1) {
                $query = "INSERT INTO sync_to_jurnal (last_update, tipe_tabel, id_record, status_sinkron, keterangan, id_jurnal, tipe_proses) VALUES ('$tgl', '$tipe_tabel', '$id', '$status_sinkron', '$ket', '$id_jurnal', 'new')";
                mysqli_query($conn, $query);
            } else {
                mysqli_query($conn, "UPDATE sync_to_jurnal SET status_sinkron = '$status_sinkron', keterangan = '$ket', id_jurnal = '$id_jurnal' WHERE id_record = '$id' AND tipe_tabel = '$tipe_tabel'");
            }
        }
        return $berhasil;
    }

    public function ambilData($status, $tipe_tabel, $access_token, $start, $end) {
        $conn = SyncConfig::getConnection();
        $base = SyncConfig::$base;
        $last_key = 0;
        if ($start != '0000-00-00') {
            $tambahan = "AND fdate >= '$start' AND fdate <= '$end'";
        } else {
            $tambahan = "";
        }
        $stmt = mysqli_query($conn, "SELECT branch_code FROM sync_config");
        $row = mysqli_fetch_assoc($stmt);
        $bcode = $row['branch_code'];

        $stmt = mysqli_query($conn, "SELECT id_record FROM sync_to_jurnal WHERE tipe_tabel = '$tipe_tabel' ORDER BY id_record DESC LIMIT 1");
        $row = mysqli_fetch_assoc($stmt);
        if ($row > 1) {
            $last_key = $row['id_record'];
        }
        $stmt = mysqli_query($conn, "SELECT ftranskey FROM rst_fc_payment WHERE fpkey > '$last_key' $tambahan AND fpayment_type != 99 AND fpayment_type != 101 ORDER BY fpkey LIMIT 1");
        $row = mysqli_fetch_assoc($stmt);
        if ($row > 0) {
            $transkey = $row['ftranskey'];
        } else {
            $transkey = 0;
        }
        $selisih = 0;

        // BEGIN - Proses ambil data yang belum pernah di import
        $result = array();
        if ($status == "import") {
            $stmt = mysqli_query($conn, "SELECT a.fpkey, a.ftranskey, b.fcode, a.fbill_amount, a.fpayment, a.fpayment_type, a.fchange, a.fdate, c.fname customer, d.fname payment, e.nama_akun, b.fpembulatan
            FROM rst_fc_payment a
            JOIN rst_fc_trans_header b ON a.ftranskey = b.fpkey
            JOIN bp_customer c ON b.fcustkey = c.fpkey
            JOIN solis_payment_type d ON a.fpayment_type = d.fpkey
            JOIN sync_account_to_jurnal e ON a.fpayment_type = e.payment_fpkey
            WHERE a.ftranskey = $transkey");
        // END - Proses ambil data yang belum pernah di import
        } else {
            // BEGIN - Proses ambil data yang pernah di import / mengimport kembali data yang gagal diimport sebelumnya
            $stmt = mysqli_query($conn, "SELECT a.fpkey, a.ftranskey, b.fcode, a.fbill_amount, a.fpayment, a.fpayment_type, a.fchange, a.fdate, c.fname customer, d.fname payment, e.nama_akun, b.fpembulatan
            FROM rst_fc_payment a
            JOIN rst_fc_trans_header b ON a.ftranskey = b.fpkey
            JOIN bp_customer c ON b.fcustkey = c.fpkey
            JOIN solis_payment_type d ON a.fpayment_type = d.fpkey
            JOIN sync_account_to_jurnal e ON a.fpayment_type = e.payment_fpkey
            JOIN sync_to_jurnal f ON a.fpkey = f.id_record
            WHERE status_sinkron = 'proses' AND tipe_proses = 'new' AND tipe_tabel = '$tipe_tabel'");
            // END - Proses ambil data yang pernah di import / mengimport kembali data yang gagal diimport sebelumnya
        }

        $i = 0;
        while ($row = mysqli_fetch_assoc($stmt)) {
            $payment = $row['fpayment'];
            $num = mysqli_num_rows($stmt)-1;
            $invoice = $bcode.'-'.$row['fcode'];
            if ($status == 'import' && $num == $i) {
                $curl = curl_init();
                curl_setopt_array($curl, array(
                    CURLOPT_URL => "https://$base.jurnal.id/core/api/v1/sales_invoices/$invoice",
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_CUSTOMREQUEST => "GET",
                    CURLOPT_HTTPHEADER => array(
                        "apikey: $access_token"
                    )
                ));
                $response = curl_exec($curl);
                curl_close($curl);
                $data = json_decode($response, TRUE);
                if (isset($data['sales_invoice']['id'])) {
                    $gt_jurnal = str_replace(".", "", $data['sales_invoice']['original_amount_currency_format']);
                    $gt_jurnal = str_replace(",", ".", $gt_jurnal);
                    $gt_jurnal = str_replace("Rp", "", $gt_jurnal);
                    $gt_jurnal = str_replace(" ", "", $gt_jurnal);
                    $selisih = $row['fbill_amount'] - $gt_jurnal;
                }
            }
            if ($row['fpayment_type'] == 97 && $payment > $row['fbill_amount']) {
                $payment = $gt_jurnal;
            }
            $jurnal_entry = abs($selisih);
            $result['receive_payments'][$i]['receive_payment']['id'] = $row['fpkey'];
            $result['receive_payments'][$i]['receive_payment']['transaction_date'] = substr($row['fdate'], 0, 10);
            $result['receive_payments'][$i]['receive_payment']['person_name'] = $row['customer'];
            $result['receive_payments'][$i]['receive_payment']['payment_method_name'] = $row['payment'];
            $result['receive_payments'][$i]['receive_payment']['deposit_to_name'] = $row['nama_akun'];
            $result['receive_payments'][$i]['receive_payment']['records_attributes'][0]['transaction_no'] = $invoice;
            $result['receive_payments'][$i]['receive_payment']['records_attributes'][0]['amount'] = $payment-$row['fchange']-$selisih;
            if ($status == 'import' && $num == $i) {
                $stmt2 = mysqli_query($conn, "SELECT fcode FROM rst_fc_trans_header WHERE fcharge_trans = '$transkey'");
                while ($row2 = mysqli_fetch_assoc($stmt2)) {
                    $invoice = $bcode.'-'.$row2['fcode'];
                    $curl = curl_init();
                    curl_setopt_array($curl, array(
                        CURLOPT_URL => "https://$base.jurnal.id/core/api/v1/sales_invoices/$invoice",
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_CUSTOMREQUEST => "GET",
                        CURLOPT_HTTPHEADER => array(
                            "apikey: $access_token"
                        )
                    ));
                    $response = curl_exec($curl);
                    curl_close($curl);
                    $data = json_decode($response, TRUE);
                    if (isset($data['sales_invoice']['id'])) {
                        $gt_jurnal = str_replace(".", "", $data['sales_invoice']['original_amount_currency_format']);
                        $gt_jurnal = str_replace(",", ".", $gt_jurnal);
                        $gt_jurnal = str_replace("Rp", "", $gt_jurnal);
                        $gt_jurnal = str_replace(" ", "", $gt_jurnal);
                        $arr = array();
                        $arr['transaction_no'] = $invoice;
                        $arr['amount'] = $gt_jurnal;
                        array_push($result['receive_payments'][$i]['receive_payment']['records_attributes'], $arr);
                    }
                }
            }
            $result['jurnal'] = $jurnal_entry;
            $result['pembulatan'] = $row['fpembulatan'];
            $i++;
        }
        return $result;
    }

    public function kirimJurnalEntry($jurnal_entry, $result, $access_token) {
        $conn = SyncConfig::getConnection();
        $jEntry = array();
        $stmt = mysqli_query($conn, "SELECT asset_account_name, income_account_name FROM sync_config");
        $row = mysqli_fetch_assoc($stmt);
        $jEntry['journal_entry']['transaction_date'] = $result['receive_payments'][0]['receive_payment']['transaction_date'];
        $jEntry['journal_entry']['transaction_no'] = $result['receive_payments'][0]['receive_payment']['records_attributes'][0]['transaction_no'];
        if ($jurnal_entry < 0.5) {
            $debit = $row['income_account_name'];
            $kredit = $row['asset_account_name'];
        } else {
            $debit = $row['asset_account_name'];
            $kredit = $row['income_account_name'];
        }
        $jEntry['journal_entry']['transaction_account_lines_attributes'][0]['account_name'] = $debit;
        $jEntry['journal_entry']['transaction_account_lines_attributes'][0]['debit'] = $jurnal_entry;
        $jEntry['journal_entry']['transaction_account_lines_attributes'][1]['account_name'] = $kredit;
        $jEntry['journal_entry']['transaction_account_lines_attributes'][1]['credit'] = $jurnal_entry;
        $jurnal = self::kirimData($jEntry, $access_token, 'journal_entries');
    }
}