<?php
namespace myresto\models;

use Yii;
use yii\base\Model;
use myresto\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, $idHeaderLog, $lastheader) {
        $conn = SyncConfig::getConnection();
        $type_con = SyncConfig::$type_con;
        $tgl = date("Y-m-d H:i:s");
        $berhasil = 0;
        $data = json_decode($data, TRUE);
        for ($i=0; $i < count($data['receive_payments']); $i++) {
            $status = $data['receive_payments'][$i]['receive_payment']['status'];
            $id_jurnal = 0;
            // BEGIN - Proses simpan status
            if ($status == 201) {
                $id = $data['receive_payments'][$i]['receive_payment']['content']['custom_id'];
                $id_jurnal = $data['receive_payments'][$i]['receive_payment']['content']['id'];
                $status_sinkron = "success";
                $ket = "";
                $berhasil++;
            } elseif ($status == 409 && isset($data['receive_payments'][$i]['receive_payment']['content']['custom_id'])) {
                $id = $data['receive_payments'][$i]['receive_payment']['body']['receive_payment']['custom_id'];
                $status_sinkron = "success";
                $ket = "";
            } else {
                $status_sinkron = "failed";
                $id = $data['receive_payments'][$i]['receive_payment']['body']['receive_payment']['custom_id'];
                $ket = json_encode($data['receive_payments'][$i]['receive_payment']['content']);
                $ket = addslashes($ket);
            }
            mysqli_query($conn, "UPDATE sync_to_jurnal SET status_sinkron = 'failed', id_jurnal = '$id_jurnal' WHERE id_record = '$id' AND tipe_tabel = '$tipe_tabel' AND id_header = '$lastheader' AND type_con = '$type_con'");
            mysqli_query($conn, "INSERT INTO sync_to_jurnal (id_header, last_update, tipe_tabel, id_record, status_sinkron, keterangan, id_jurnal, tipe_proses, type_con) VALUES ('$idHeaderLog', '$tgl', '$tipe_tabel', '$id', '$status_sinkron', '$ket', '$id_jurnal', 'new', '$type_con')");
            // END - Proses simpan status
        }
        return $berhasil;
    }

    public function ambilData($status, $tipe_tabel, $access_token, $start, $end) {
        $conn = SyncConfig::getConnection('MyConnection');
        $type_con = SyncConfig::$type_con;
        $connMyResto = SyncConfig::getConnection('MyResto');
        $dbNameMyConnection = SyncConfig::getDbNameMyConnection();
        $base = SyncConfig::$base;
        $last_key = 0;
        
        if ($start != '0000-00-00')
            $filterStart = " AND a.fdate >= '$start'";
        else
            $filterStart = "";
        if ($end != '0000-00-00')
            $filterEnd = " AND a.fdate <= '$end'";
        else
            $filterEnd = "";

        $stmt = mysqli_query($conn, "SELECT branch_code FROM sync_config WHERE type_con = '$type_con'");
        $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' AND type_con = '$type_con' ORDER BY id_record DESC LIMIT 1");
        $row = mysqli_fetch_assoc($stmt);
        if ($row > 1) {
            $last_key = $row['id_record'];
        }
        $stmt = mysqli_query($connMyResto, "SELECT ftranskey FROM rst_fc_payment a WHERE fpkey > '$last_key' $filterStart $filterEnd AND fpayment_type != 99 AND fpayment_type != 101 AND fpayment_type != 100 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($connMyResto, "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 $dbNameMyConnection.sync_account_to_jurnal e ON a.fpayment_type = e.payment_fpkey
            WHERE a.ftranskey = $transkey AND e.type_con = 'resto'");
        // 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($connMyResto, "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 $dbNameMyConnection.sync_account_to_jurnal e ON a.fpayment_type = e.payment_fpkey
            JOIN $dbNameMyConnection.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 = $selisih;
            $method = $row['payment'];
            $result['receive_payments'][$i]['receive_payment']['custom_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'] = $method;
            $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($connMyResto, "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'];
            $result['method'] = $method;
            $i++;
        }
        return $result;
    }

    public function kirimJurnalEntry($jurnal_entry, $result, $access_token, $account) {
        $type_con = SyncConfig::$type_con;
        $conn = SyncConfig::getConnection();
        $jEntry = array();
        $stmt = mysqli_query($conn, "SELECT asset_account_name, income_account_name FROM sync_config WHERE type_con = '$type_con'");
        $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 = $account;
        } else {
            $debit = $account;
            $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'] = abs($jurnal_entry);
        $jEntry['journal_entry']['transaction_account_lines_attributes'][1]['account_name'] = $kredit;
        $jEntry['journal_entry']['transaction_account_lines_attributes'][1]['credit'] = abs($jurnal_entry);
        $jurnal = self::kirimData($jEntry, $access_token, 'journal_entries');
    }
}