<?php
namespace backend\models;

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

class ImportSupplier extends Model {
    public $tipe_tabel = "bp_supplier";

    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/vendors/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['vendors']); $i++) {
            $id = $id_lokal[$i];
            $status = $data['vendors'][$i]['vendor']['status'];
            $id_jurnal = 0;
            // BEGIN - Proses simpan status
            if ($status == 201) {
                $id_jurnal = $data['vendors'][$i]['vendor']['content']['id'];
                $status_sinkron = "success";
                $ket = "";
                $berhasil++;
            } elseif ($status == 409) {
                $status_sinkron = "skip";
                $ket = "Nama Supplier Sudah Ada";
            } else {
                $status_sinkron = "failed";
                $ket = json_encode($data['vendors'][$i]['vendor']['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) {
        $conn = SyncConfig::getConnection();
        $last_key = 0;
        $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'];
        }
        // BEGIN - Proses ambil data yang belum pernah di import
        $result = array();
        if ($status == "import") {
            $stmt = mysqli_query($conn, "SELECT * FROM bp_supplier WHERE fpkey > $last_key AND fpkey < 9999 LIMIT 15");
        // 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 * FROM bp_supplier a
                JOIN sync_to_jurnal b ON a.fpkey = b.id_record
                WHERE status_sinkron = 'proses' AND tipe_proses = 'new' AND tipe_tabel = '$tipe_tabel' LIMIT 15");
            // END - Proses ambil data yang pernah di import / mengimport kembali data yang gagal diimport sebelumnya
        }
        
        $i = 0;
        while ($row = mysqli_fetch_assoc($stmt)) {
            $result['vendors'][$i]['vendor']['id'] = $row['fpkey'];
            $result['vendors'][$i]['vendor']['display_name'] = $row['fname'];
            $result['vendors'][$i]['vendor']['address'] = $row['faddress'];
            $result['vendors'][$i]['vendor']['phone'] = $row['fphone'];
            $result['vendors'][$i]['vendor']['email'] = $row['femail'];
            $result['vendors'][$i]['vendor']['fax'] = $row['ffax'];
            $i++;
        }
        return $result;
    }
}