<?php
namespace myretail\models;

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

class ImportTransaction extends Model {
    public $tipe_tabel = "rtl_fc_trans_header";

    public function kirimData($data, $access_token) {
        $base = SyncConfig::$base;
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://$base.jurnal.id/core/api/v1/sales_invoices",
            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) {
        $type_con = SyncConfig::$type_con;
        $conn = SyncConfig::getConnection();
        $tgl = date("Y-m-d H:i:s");
        $berhasil = 0;
        $data = json_decode($data, TRUE);
        $id_jurnal = 0;
        // BEGIN - Proses simpan status yang mendapat status code 201
        if (!isset($data['error_full_messages'])) {
            $id_jurnal = $data['sales_invoice']['id'];
            $status_sinkron = "success";
            $ket = "";
            $berhasil++;
        } elseif (isset($data['error_full_messages']) && $data['id'] != NULL) {
            $status_sinkron = "skip";
            $ket = "Nomor Nota Sudah Ada";
        } else {
            $status_sinkron = "failed";
            $ket = json_encode($data['error_full_messages']);
            $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_lokal'");
        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, type_con) VALUES ('$tgl', '$tipe_tabel', '$id_lokal', '$status_sinkron', '$ket', '$id_jurnal', 'new', '$type_con')";
            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_lokal' AND tipe_tabel = '$tipe_tabel'");
        }
        // END - Proses simpan status
        return $berhasil;
    }

    public function ambilData($status, $tipe_tabel, $start, $end) {
        $type_con = SyncConfig::$type_con;
        $conn = SyncConfig::getConnection('MyConnection');
        $connMyRetail = SyncConfig::getConnection('MyRetail');
        $dbNameMyConnection = SyncConfig::getDbNameMyConnection();
        $last_key = 0;
        if ($start != '0000-00-00') {
            $tambahan = "AND a.fdate >= '$start' AND a.fdate <= '$end'";
        } else {
            $tambahan = "";
        }
        $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($connMyRetail, "SELECT fname FROM inv_warehouse a
            JOIN solis_profile b ON a.fpkey = b.fvalue
            WHERE b.fcode = 'DEFAULT_WAREHOUSE'");
        $row = mysqli_fetch_assoc($stmt);
        $warehouse = $row['fname'];

        $stmt = mysqli_query($conn, "SELECT tax_name, branch_code, branch_name FROM sync_config WHERE type_con = '$type_con'");
        $row = mysqli_fetch_assoc($stmt);
        $tax = $row['tax_name'];
        $bname = $row['branch_name'];
        $bcode = $row['branch_code'];

        // BEGIN - Proses ambil data yang belum pernah di import
        $result = array();
        $x = array();
        if ($status=="import") {
            $stmt = mysqli_query($connMyRetail, "SELECT DISTINCT a.fpkey, a.fcode, a.fdate, a.fpos_discType, a.fpos_discValue, a.fpos_discount, a.fcustname, fpos_tax
                FROM rtl_fc_trans_header a
                JOIN rtl_fc_trans_detail b ON a.fpkey = b.ftranskey
                WHERE a.fpkey > '$last_key' $tambahan ORDER BY a.fpkey ASC LIMIT 1"); //mengambil data transaksi header
        // 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($connMyRetail, "SELECT DISTINCT a.fpkey, a.fcode, a.fdate, a.fpos_discType, a.fpos_discValue, a.fpos_discount, a.fcustname
            FROM rtl_fc_trans_header a
            JOIN rtl_fc_trans_detail b ON a.fpkey = b.ftranskey
            JOIN $dbNameMyConnection.sync_to_jurnal c ON a.fpkey = c.id_record
            WHERE status_sinkron = 'proses' AND tipe_proses = 'new' AND tipe_tabel = '$tipe_tabel' LIMIT 1"); //mengambil data transaksi header
            // END - Proses ambil data yang pernah di import / mengimport kembali data yang gagal diimport sebelumnya
        }
        $row = mysqli_fetch_assoc($stmt);
        if ($row > 0) {
            if ($row['fpos_tax'] == 0) {
                $tax = "";
            }
            if ($row['fpos_discType'] == 1) {
                $disc_name = "value";
                $disc_value = $row['fpos_discount'];
            } else {
                $disc_name = "Percent";
                $disc_value = $row['fpos_discValue'];
            }
            $result['sales_invoice']['transaction_date'] = $row['fdate'];
            $result['sales_invoice']['due_date'] = $row['fdate'];
            $result['sales_invoice']['id'] = $row['fpkey'];
            $result['sales_invoice']['person_name'] = $row['fcustname'];
            $result['sales_invoice']['warehouse_name'] = $warehouse;
            $result['sales_invoice']['term_name'] = "Cash On Delivery";
            $result['sales_invoice']['transaction_no'] = $bcode.'-'.$row['fcode'];
            $result['sales_invoice']['tags'][0] = $bname;
            $result['sales_invoice']['discount_type_name'] = $disc_name;
            $result['sales_invoice']['discount_unit'] = $disc_value;
            $result['sales_invoice']['use_tax_inclusive'] = true;

            $id_header = $row['fpkey'];
            $stmt2 = mysqli_query($connMyRetail, "SELECT b.fcode, a.fprice, a.fqty, a.fdisctype, a.fdiscvalue, a.fdiscount
            FROM rtl_fc_trans_detail a
            JOIN inv_item b ON a.fitemcode = b.fcode
            WHERE a.ftranskey = '$id_header'");
            
            $j = 0;
            $num = mysqli_num_rows($stmt2);
            while ($row2 = mysqli_fetch_assoc($stmt2)) {
                if ($row2['fdisctype'] == 1) {
                    $discount = ($row2['fdiscount']/$row2['fprice'])*100;
                } elseif ($row2['fdiscvalue'] != 0) {
                    $discount = $row2['fdiscvalue'];
                } else {
                    $discount = 0;
                }

                $result['sales_invoice']['transaction_lines_attributes'][$j]['quantity'] = $row2['fqty'];
                $result['sales_invoice']['transaction_lines_attributes'][$j]['product_code'] = $row2['fcode'];
                $result['sales_invoice']['transaction_lines_attributes'][$j]['rate'] = $row2['fprice'];
                $result['sales_invoice']['transaction_lines_attributes'][$j]['discount'] = $discount;
                $result['sales_invoice']['transaction_lines_attributes'][$j]['line_tax_name'] = $tax;
                $j++;
            }
        }
        return $result;
    }
}