<?php
namespace backend\controllers;

use Yii;
use yii\web\Controller;
use backend\models\SalesReturn;
use backend\models\SyncConfig;

class SalesReturnController extends Controller {
    public function actionIndex() {
        $model = new SalesReturn();
        $tipe_tabel = $model->tipe_tabel;
        $conn = SyncConfig::getConnection();
        $config = SyncConfig::find()->one();
        $access_token = $config->api_key;

        if (isset($_POST['date_start'])) {$start = $_POST['date_start'];} else {$start = '0000-00-00';}
        if (isset($_POST['date_end'])) {$end = $_POST['date_end'];} else {$end = '0000-00-00';}

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

        if ($result != NULL) {
            $id_lokal = $result['sales_return']['id'];
            unset($result['sales_return']['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, $start, $end);
                $id_lokal = $result['sales_return']['id'];
                unset($result['sales_return']['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 = "ret_tran";
            }
            // END - proses ambil, kirim dan simpan data yang gagal diimport
        }

        return $echo;
    }
}