<?php
namespace backend\models;

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

class ImportTransaction extends Model {
    public $tipe_tabel = "rst_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/batch_create",
            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['sales_invoices']); $i++) {
            $id = $id_lokal[$i];
            $status = $data['sales_invoices'][$i]['sales_invoice']['status'];
            $id_jurnal = 0;
            // BEGIN - Proses simpan status yang mendapat status code 201
            if ($status == 201) {
                $id_jurnal = $data['sales_invoices'][$i]['sales_invoice']['content']['id'];
                $status_sinkron = "success";
                $ket = "";
                $berhasil++;
            } elseif ($status == 409) {
                $status_sinkron = "skip";
                $ket = "Nomor Nota Sudah Ada";
            } else {
                $status_sinkron = "failed";
                $ket = json_encode($data['sales_invoices'][$i]['sales_invoice']['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'");
            }
            // END - Proses simpan status
        }
        return $berhasil;
    }

    public function ambilData($status, $tipe_tabel, $start, $end) {
        $conn = SyncConfig::getConnection();
        $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' 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 tax_name, branch_code, branch_name FROM sync_config");
        $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($conn, "SELECT DISTINCT a.fpkey, a.fcode, a.fdate, a.fpos_discType, a.fpos_discValue, a.fpos_discount, a.fiscompliment, b.fname
            FROM rst_fc_trans_header a
            LEFT JOIN bp_customer b ON a.fcustkey = b.fpkey
            JOIN rst_fc_trans_detail c ON a.fpkey = c.ftranskey
            WHERE a.fpkey > '$last_key' AND a.fcancelby = 0 $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($conn, "SELECT DISTINCT a.fpkey, a.fcode, a.fdate, a.fpos_discType, a.fpos_discValue, a.fpos_discount, a.fiscompliment, b.fname
            FROM rst_fc_trans_header a
            LEFT JOIN bp_customer b ON a.fcustkey = b.fpkey
            JOIN rst_fc_trans_detail c ON a.fpkey = c.ftranskey
            JOIN sync_to_jurnal d ON a.fpkey = d.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
        }
        $i = 0;
        while ($row = mysqli_fetch_assoc($stmt)) {//merubah kode transaksi dari database dengan format dari jurnal.id
            $price = 0;
            if ($row['fpos_discType'] == 1) {
                $disc_name = "value";
                $disc_value = $row['fpos_discount'];
            } else {
                $disc_name = "Percent";
                $disc_value = $row['fpos_discValue'];
            }
            $result['sales_invoices'][$i]['sales_invoice']['transaction_date'] = $row['fdate'];
            $result['sales_invoices'][$i]['sales_invoice']['due_date'] = $row['fdate'];
            $result['sales_invoices'][$i]['sales_invoice']['id'] = $row['fpkey'];
            $result['sales_invoices'][$i]['sales_invoice']['person_name'] = $row['fname'];
            $result['sales_invoices'][$i]['sales_invoice']['term_name'] = "Cash On Delivery";
            $result['sales_invoices'][$i]['sales_invoice']['transaction_no'] = $bcode.'-'.$row['fcode'];
            $result['sales_invoices'][$i]['sales_invoice']['tags'][0] = $bname;
            $result['sales_invoices'][$i]['sales_invoice']['discount_type_name'] = $disc_name;
            $result['sales_invoices'][$i]['sales_invoice']['discount_unit'] = $disc_value;

            $id_header = $row['fpkey'];
            $stmt2 = mysqli_query($conn, "SELECT b.fname, a.fprice, a.fnotespricesubtotal, a.fnotes, a.fqty, a.fdisctype, a.fdiscvalue, a.fdiscount, fcomboheader
                FROM rst_fc_trans_detail a
                JOIN rst_menu b ON a.fmenukey = b.fpkey
                WHERE a.ftranskey = '$id_header' AND fiscomboheader != 1");
            
            $j = 0;
            $num = mysqli_num_rows($stmt2);
            while ($row2 = mysqli_fetch_assoc($stmt2)) {
                if ($row2['fdisctype'] == 1) {
                    $discount = $row2['fdiscvalue'];
                } elseif ($row2['fdisctype'] == 2) {
                    $discount = ($row2['fdiscount']/$row2['fprice'])*100;
                } else {
                    $discount = 0;
                }

                if ($row['fiscompliment'] == 0) {
                    $price = $row2['fprice']+$row2['fnotespricesubtotal'];
                }
                
                $result['sales_invoices'][$i]['sales_invoice']['transaction_lines_attributes'][$j]['quantity'] = $row2['fqty'];
                $result['sales_invoices'][$i]['sales_invoice']['transaction_lines_attributes'][$j]['product_name'] = $row2['fname'];
                $result['sales_invoices'][$i]['sales_invoice']['transaction_lines_attributes'][$j]['rate'] = $price;
                $result['sales_invoices'][$i]['sales_invoice']['transaction_lines_attributes'][$j]['discount'] = $discount;
                $result['sales_invoices'][$i]['sales_invoice']['transaction_lines_attributes'][$j]['line_tax_name'] = $tax;
                if ($row2['fnotes'] != "") {
                    $result['sales_invoices'][$i]['sales_invoice']['transaction_lines_attributes'][$j]['description'] = $row2['fnotes'];
                }
                if ($row2['fcomboheader'] != 0) {
                    $x = $row2['fcomboheader'];
                    $ssmt = mysqli_query($conn, "SELECT a.fname FROM rst_menu a JOIN rst_fc_trans_detail b ON a.fpkey = b.fmenukey WHERE b.fpkey = '$x'");
                    $r = mysqli_fetch_assoc($ssmt);
                    $result['sales_invoices'][$i]['sales_invoice']['transaction_lines_attributes'][$j]['description'] = $r['fname'];
                }
                $j++;
            }
            $i++;
        }
        return $result;
    }
}