<?php

namespace backend\controllers;

use Yii;
use backend\models\SyncToJurnal;
use backend\models\SyncToJurnalSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\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();
        $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 = 'rst_fc_trans_header' 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 = 'rst_fc_payment' 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' 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;}
        // END - Proses mengambil id terakhir yang ada pada sync to jurnal

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

        $stmt = mysqli_query($conn, "SELECT id_record FROM sync_to_jurnal WHERE (status_sinkron = 'failed' OR status_sinkron = 'proses') AND tipe_tabel = 'rst_fc_trans_header'");
        $num = mysqli_num_rows($stmt);
        $jumlah['transaction'] += $num;

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

        $stmt = mysqli_query($conn, "SELECT id_record FROM sync_to_jurnal WHERE (status_sinkron = 'failed' OR status_sinkron = 'proses') AND tipe_tabel = 'rst_fc_payment'");
        $num = mysqli_num_rows($stmt);
        $jumlah['payment'] += $num;

        $stmt = mysqli_query($conn, "SELECT fpkey FROM rst_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;

        $stmt = mysqli_query($conn, "SELECT id_record FROM sync_to_jurnal WHERE (status_sinkron = 'failed' OR status_sinkron = 'proses') AND tipe_tabel = 'sales_return'");
        $num = mysqli_num_rows($stmt);
        $jumlah['salesReturn'] += $num;

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

        return $jumlah;
    }
}
