<?php
namespace myresto\models;

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

class ImportDeposit extends Model {
    public $tipe_tabel = "bp_customer_deposit";

    public function kirimData($data, $access_token) {
        $base = SyncConfig::$base;
        $endpoint = $data['endpoint'];
        $method = $data['method'];
        unset($data['endpoint']);
        unset($data['method']);
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://$base.jurnal.id/core/api/v1/$endpoint",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => $method,
            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, $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);
        $id_jurnal = 0;
        // BEGIN - Proses simpan status
        if (isset($data['credit_memo']['id']) || isset($data['customer_apply_credit_memo']['id'])) {
            if (isset($data['credit_memo'])) {
                $id_jurnal = $data['credit_memo']['id'];
            } else {
                $id_jurnal = $data['customer_apply_credit_memo']['id'];
            }
            $status_sinkron = "success";
            $ket = "";
            $berhasil++;
        } else {
            $status_sinkron = "failed";
            $ket = json_encode($data['error_full_messages']);
            $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 yang mendapat status code 201
        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();
        $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 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 > 0) {
            $last_key = $row['id_record'];
        }
        $stmt = mysqli_query($conn, "SELECT nama_akun FROM sync_account_to_jurnal WHERE type_con = '$type_con' AND payment_fpkey = '100'");
        $row = mysqli_fetch_assoc($stmt);
        $deposit = $row['nama_akun'];
        
        // BEGIN - Proses ambil data yang belum pernah di import
        $result = array();

        if ($status == "import") {
            $stmt = mysqli_query($connMyResto, "SELECT a.fpkey, a.fcustkey, c.id_jurnal AS id_customer, b.fname, fdate, ftotal_bfr, ftotal_afr, ftranscode
            FROM bp_customer_deposit a
            JOIN bp_customer b ON a.fcustkey = b.fpkey
            JOIN $dbNameMyConnection.sync_to_jurnal c ON a.fcustkey = c.id_record
            WHERE a.fpkey > '$last_key' AND tipe_tabel = 'bp_customer' $filterStart $filterEnd LIMIT 1");
        // 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.fcustkey, b.fname, fdate, ftotal_bfr, ftotal_afr, ftranscode
            FROM bp_customer_deposit a
            JOIN bp_customer b ON a.fcustkey = b.fpkey
            JOIN $dbNameMyConnection.sync_to_jurnal c ON a.fpkey = c.id_record
            WHERE c.tipe_tabel = '$tipe_tabel' AND status_sinkron = 'proses' AND tipe_proses = 'new' LIMIT 1");
            // END - Proses ambil data yang pernah di import / mengimport kembali data yang gagal diimport sebelumnya
        }
        
        $row = mysqli_fetch_assoc($stmt);
        if ($row > 0) {
            if ($status == 'reimport') {
                $id = $row['fcustkey'];
                $stmt2 = mysqli_query($conn, "SELECT id_jurnal FROM sync_to_jurnal WHERE type_con = 'resto' AND tipe_tabel = 'bp_customer' AND id_record = '$id' AND tipe_proses = 'new'");
                $row2 = mysqli_fetch_assoc($stmt2);
                $id_customer = $row2['id_jurnal'];
            } else {
                $id_customer = $row['id_customer'];
            }
            if ($row['ftotal_bfr'] == 0) {
                $date = substr($row['fdate'], 8, 2)."/".substr($row['fdate'], 5, 2)."/".substr($row['fdate'], 0, 4);    
                $result['credit_memo']['id'] = $row['fpkey'];
                $result['credit_memo']['person_id'] = $id_customer;
                $result['credit_memo']['person_name'] = $row['fname'];
                $result['credit_memo']['person_type'] = "customer";
                $result['credit_memo']['transaction_date'] = $date;
                $result['credit_memo']['transaction_account_lines_attributes'][0]['account_name'] = $deposit;
                $result['credit_memo']['transaction_account_lines_attributes'][0]['description'] = "Deposit";
                $result['credit_memo']['transaction_account_lines_attributes'][0]['debit'] = $row['ftotal_afr'];
                $result['method'] = "POST";
                $result['endpoint'] = "credit_memos";
            } elseif ($row['ftotal_bfr'] != 0 && $row['ftranscode'] == "") {
                $custkey = $row['fcustkey'];
                $fpkey = $row['fpkey'];
                $ssmt = mysqli_query($connMyResto, "SELECT fpkey FROM bp_customer_deposit WHERE fpkey < $fpkey AND fcustkey = $custkey AND ftranscode = '' ORDER BY fpkey DESC LIMIT 1");
                $roo = mysqli_fetch_assoc($ssmt);
                $idmemo = $roo['fpkey'];

                $ssmt = mysqli_query($conn, "SELECT id_jurnal FROM sync_to_jurnal WHERE id_record = '$idmemo' AND tipe_tabel = '$tipe_tabel' AND type_con = '$type_con'");
                $roo = mysqli_fetch_assoc($ssmt);
                $idjmemo = $roo['id_jurnal'];

                $curl = curl_init();

                curl_setopt_array($curl, array(
                    CURLOPT_URL => "https://api.jurnal.id/core/api/v1/credit_memos/$idjmemo",
                    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);
                $get_memo = json_decode($response, TRUE);

                $id_line = $get_memo['credit_memo']['transaction_account_lines_attributes'][0]['id'];

                $date = substr($row['fdate'], 8, 2)."/".substr($row['fdate'], 5, 2)."/".substr($row['fdate'], 0, 4);
                $result['credit_memo']['id'] = $row['fpkey'];
                $result['credit_memo']['person_id'] = $id_customer;
                $result['credit_memo']['person_name'] = $row['fname'];
                $result['credit_memo']['person_type'] = "customer";
                $result['credit_memo']['transaction_date'] = $date;
                $result['credit_memo']['transaction_account_lines_attributes'][0]['id'] = $id_line;
                $result['credit_memo']['transaction_account_lines_attributes'][0]['account_name'] = $deposit;
                $result['credit_memo']['transaction_account_lines_attributes'][0]['description'] = "Deposit";
                $result['credit_memo']['transaction_account_lines_attributes'][0]['debit'] = $row['ftotal_afr'];
                $result['method'] = "PATCH";
                $result['endpoint'] = "credit_memos/$idjmemo";
            } else {
                $custkey = $row['fcustkey'];
                $fpkey = $row['fpkey'];
                $ssmt = mysqli_query($connMyResto, "SELECT fpkey FROM bp_customer_deposit WHERE fpkey < $fpkey AND fcustkey = $custkey AND ftranscode = '' ORDER BY fpkey DESC LIMIT 1");
                $roo = mysqli_fetch_assoc($ssmt);
                $idmemo = $roo['fpkey'];

                $ssmt = mysqli_query($conn, "SELECT id_jurnal FROM sync_to_jurnal WHERE id_record = '$idmemo' AND tipe_tabel = '$tipe_tabel' AND type_con = '$type_con'");
                $roo = mysqli_fetch_assoc($ssmt);
                $idjmemo = $roo['id_jurnal'];

                $no_nota = $row['ftranscode'];
                $ssmt = mysqli_query($connMyResto, "SELECT id_jurnal 
                    FROM $dbNameMyConnection.sync_to_jurnal a 
                    JOIN rst_fc_trans_header b ON a.id_record = b.fpkey
                    WHERE b.fcode = '$no_nota'");
                $roo = mysqli_fetch_assoc($ssmt);
                $idjtran = $roo['id_jurnal'];

                $result['customer_apply_credit_memo']['id'] = $row['fpkey'];
                $result['customer_apply_credit_memo']['person_id'] = (int)$id_customer;
                $result['customer_apply_credit_memo']['selected_credit_memo_id'] = (int)$idjmemo;
                $result['customer_apply_credit_memo']['records_attributes'][0]['transaction_id'] = (int)$idjtran;
                $result['customer_apply_credit_memo']['records_attributes'][0]['amount'] = $row['ftotal_bfr']-$row['ftotal_afr'];
                $result['method'] = "POST";
                $result['endpoint'] = "customer_apply_credit_memo";
            }
        }

        return $result;
    }
}