<?php
namespace myretail\controllers;

use Yii;
use yii\web\Controller;
use myretail\models\ImportWarehouse;
use myretail\models\SyncConfig;

class ImportWarehouseController extends Controller {
    public function actionIndex() {
        $model = new ImportWarehouse();
        $tipe_tabel = $model::$tipe_tabel;
        $conn = SyncConfig::getConnection();
        $config = SyncConfig::find()->where(['type_con' => 'retail'])->one();
        $access_token = $config->api_key;

        $result = $model->ambilData("import", $tipe_tabel);

        if ($result != NULL) {
            $id_lokal = $result['warehouse']['id'];
            unset($result['warehouse']['id']);
            $response = $model->kirimData($result, $access_token);
            $simpan = $model->simpanStatus($response, $tipe_tabel, $id_lokal);
            $echo = $simpan;
            // END - proses ambil, kirim dan simpan data yang baru
        } else {
            // BEGIN - proses ambil, kirim dan simpan data yang gagal diimport
            $stmt = mysqli_query($conn, "SELECT * FROM sync_to_jurnal WHERE status_sinkron = 'proses' AND tipe_tabel = '$tipe_tabel'");
            if (mysqli_fetch_assoc($stmt) > 0) {
                $result = $model->ambilData("reimport", $tipe_tabel);
                for ($i=0; $i < count($result['warehouses']); $i++) {
                    $id_lokal[$i] = $result['warehouses'][$i]['warehouse']['id'];
                    unset($result['warehouses'][$i]['warehouse']['id']);
                }
                $response = $model->kirimData($result, $access_token);
                $simpan = $model->simpanStatus($response, $tipe_tabel, $id_lokal);
                $echo = $simpan;
            } else {
                mysqli_query($conn, "UPDATE sync_to_jurnal SET status_sinkron = 'proses' WHERE status_sinkron = 'failed' AND tipe_tabel = '$tipe_tabel'");
                $echo = "ware";
            }
            // END - proses ambil, kirim dan simpan data yang gagal diimport
        }

        return $echo;
    }
}