<?php

namespace myretail\controllers;

use Yii;
use myretail\models\SyncToJurnal;
use myretail\models\SyncToJurnalSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use myretail\models\SyncConfig;

/**
 * SyncToJurnalController implements the CRUD actions for SyncToJurnal model.
 */
class SyncToJurnalController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all SyncToJurnal models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new SyncToJurnalSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single SyncToJurnal model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new SyncToJurnal model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new SyncToJurnal();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing SyncToJurnal model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing SyncToJurnal model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the SyncToJurnal model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return SyncToJurnal the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = SyncToJurnal::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }

    public static function actionGetTotalSyncDataTransaction($json = false, $start = '', $end = '') {
        $conn = SyncConfig::getConnection('MyConnection');
        $connMyRetail = SyncConfig::getConnection('MyRetail');
        $type_con = SyncConfig::$type_con;
        $jumlah = array();

        if (!empty($start))
            $filterStart = " AND fdate >= '$start'";
        else
            $filterStart = "";
        if (!empty($end))
            $filterEnd = " AND fdate <= '$end'";
        else
            $filterEnd = "";

        $stmt = mysqli_query($conn, "SELECT id_record FROM sync_to_jurnal WHERE tipe_tabel = 'rtl_fc_trans_header' AND type_con = '$type_con' ORDER BY id_record DESC LIMIT 1");
        $row = mysqli_fetch_assoc($stmt);
        if ($row != NULL) {$last_key_tran = $row['id_record'];}else{$last_key_tran = 0;}

        $stmt = mysqli_query($conn, "SELECT id_record FROM sync_to_jurnal WHERE tipe_tabel = 'rtl_fc_payment' AND type_con = '$type_con' ORDER BY id_record DESC LIMIT 1");
        $row = mysqli_fetch_assoc($stmt);
        if ($row != NULL) {$last_key_pay = $row['id_record'];}else{$last_key_pay = 0;}

        $stmt = mysqli_query($conn, "SELECT id_record FROM sync_to_jurnal WHERE tipe_tabel = 'sales_return' AND type_con = '$type_con' ORDER BY id_record DESC LIMIT 1");
        $row = mysqli_fetch_assoc($stmt);
        if ($row != NULL) {$last_key_salret = $row['id_record'];}else{$last_key_salret = 0;}

        // BEGIN - Proses mengambil jumlah data yanga akan disinkron
        $stmt = mysqli_query($connMyRetail, "SELECT fpkey FROM rtl_fc_trans_header WHERE fpkey > $last_key_tran" . $filterStart . $filterEnd);
        $num = mysqli_num_rows($stmt);
        $jumlah['transaction'] = $num;

        $stmt = mysqli_query($connMyRetail, "SELECT fpkey FROM rtl_fc_payment WHERE fpkey > $last_key_pay" . $filterStart . $filterEnd);
        $num = mysqli_num_rows($stmt);
        $jumlah['payment'] = $num;

        $stmt = mysqli_query($connMyRetail, "SELECT fpkey FROM rtl_fc_trans_header WHERE fpkey > $last_key_salret AND fvoiddt != '0000-00-00 00:00:00'" . $filterStart . $filterEnd);
        $num = mysqli_num_rows($stmt);
        $jumlah['salesReturn'] = $num;

        if ($json)
            $jumlah = json_encode($jumlah);

        return $jumlah;
    }
}
