<?php
namespace myresto\models;

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

class ImportProduct extends Model {
    public static $tipe_tabel = "rst_menu";

    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/products/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, $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['products']); $i++) { 
            $status = $data['products'][$i]['product']['status'];
            $id_jurnal = 0;
            // BEGIN - Proses simpan status
            if ($status == 201) {
                $id = $data['products'][$i]['product']['content']['custom_id'];
                $id_jurnal = $data['products'][$i]['product']['content']['id'];
                $status_sinkron = "success";
                $ket = "";
                $berhasil++;
            } elseif ($status == 409 && isset($data['products'][$i]['product']['content']['custom_id'])) {
                $id = $data['products'][$i]['product']['body']['custom_id'];
                $status_sinkron = "success";
                $ket = "";
                $berhasil++;
            } else {
                $id = $data['products'][$i]['product']['body']['custom_id'];
                $status_sinkron = "failed";
                $ket = json_encode($data['products'][$i]['product']['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 yang mendapat status code 201
        }
        return $berhasil;
    }

    public function ambilData($status, $tipe_tabel) {
        $type_con = SyncConfig::$type_con;
        $conn = SyncConfig::getConnection('MyConnection');
        $connMyResto = SyncConfig::getConnection('MyResto');
        $dbNameMyConnection = SyncConfig::getDbNameMyConnection();
        $last_key = 0;
        $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 inventory_account_number FROM sync_config WHERE type_con = '$type_con'");
        $row = mysqli_fetch_assoc($stmt);
        $inv = $row['inventory_account_number'];
        
        // BEGIN - Proses ambil data yang belum pernah di import
        $result = array();

        if ($status == "import") {
            $stmt = mysqli_query($connMyResto, "SELECT a.fpkey, a.fcode, fname, fprice, fdesc, b.fcategory category, c.fcategory sub_category FROM rst_menu a
            LEFT JOIN rst_menu_category b ON a.fcategory = b.fpkey
            LEFT JOIN rst_menu_sub_category c ON a.fcategory2 = c.fpkey
            WHERE a.fpkey > $last_key AND fcombo_attribute != 1 LIMIT 10");
        // 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.fcode, fname, fprice, fdesc, b.fcategory category, c.fcategory sub_category FROM rst_menu a
            LEFT JOIN rst_menu_category b ON a.fcategory = b.fpkey
            LEFT JOIN rst_menu_sub_category c ON a.fcategory2 = c.fpkey
            JOIN $dbNameMyConnection.sync_to_jurnal d ON a.fpkey = d.id_record
            WHERE d.tipe_tabel = '$tipe_tabel' AND status_sinkron = 'proses' AND tipe_proses = 'new' LIMIT 10");
            // END - Proses ambil data yang pernah di import / mengimport kembali data yang gagal diimport sebelumnya
        }
        
        $i = 0;
        while ($row = mysqli_fetch_assoc($stmt)) {
            $result['products'][$i]['product']['custom_id'] = $row['fpkey'];
            $result['products'][$i]['product']['product_code'] = $row['fcode'];
            $result['products'][$i]['product']['name'] = $row['fname'];
            $result['products'][$i]['product']['sell_price_per_unit'] = $row['fprice'];
            $result['products'][$i]['product']['taxable_sell'] = true;
            $result['products'][$i]['product']['description'] = $row['fdesc'];
            $result['products'][$i]['product']['is_sold'] = true;
            $result['products'][$i]['product']['track_inventory'] = "false";
            $result['products'][$i]['product']['inventory_asset_account_number'] = $inv;
            $result['products'][$i]['product']['product_category_names'][0] = $row['category'];
            $result['products'][$i]['product']['product_category_names'][1] = $row['sub_category'];
            $i++;
        }
        return $result;
    }
}