<?php

namespace nota\controllers;

use Yii;
use yii\web\Controller;
use nota\models\KasirShift;
use nota\models\KasirPengeluaran;
use nota\models\Nota;
use nota\models\Usermember;
use nota\models\Cluster;
use nota\models\Pembayaran;

class KasirShiftController extends Controller
{
	public function actionIndex()
    {
        $today = date('Y-m-d');

        // Semua shift
        $shifts = KasirShift::find()
            ->with('user')
            ->orderBy(['id' => SORT_DESC])
            ->all();

        // Shift hari ini
        $shiftHariIni = KasirShift::find()
            ->where(['like', 'tanggal_buka', $today])
            ->all();

        $totalShiftHariIni = count($shiftHariIni);

        $totalOmsetHariIni = KasirShift::find()
            ->where(['like', 'tanggal_buka', $today])
            ->sum('total_penjualan') ?? 0;

        $totalCashHariIni = KasirShift::find()
            ->where(['like', 'tanggal_buka', $today])
            ->sum('total_cash_shift') ?? 0;

        $totalSelisihHariIni = KasirShift::find()
            ->where(['like', 'tanggal_buka', $today])
            ->sum('selisih') ?? 0;

    $labels = [];
    $dataOmset = [];
    $dataModal = [];

    for ($i = 6; $i >= 0; $i--) {
        $tanggal = date('Y-m-d', strtotime("-$i days"));

        // Total penjualan (omset)
        $omset = KasirShift::find()
            ->where(['like', 'tanggal_buka', $tanggal])
            ->sum('total_penjualan') ?? 0;

        // Total modal awal hari itu
        $modal = KasirShift::find()
            ->where(['like', 'tanggal_buka', $tanggal])
            ->sum('modal_awal') ?? 0;

        $labels[] = date('d M', strtotime($tanggal));
        $dataOmset[] = (int)$omset;
        $dataModal[] = (int)$modal;
    }


    // ===============================
    // CASH vs NON CASH (7 HARI)
    // ===============================
    $labelsPayment = [];
    $dataCash = [];
    $dataNonCash = [];

    for ($i = 6; $i >= 0; $i--) {

        $tanggal = date('Y-m-d', strtotime("-$i days"));

        // Total cash
        $cash = KasirShift::find()
            ->where(['like', 'tanggal_buka', $tanggal])
            ->sum('total_cash_shift') ?? 0;

        // Total omset
        $omset = KasirShift::find()
            ->where(['like', 'tanggal_buka', $tanggal])
            ->sum('total_penjualan') ?? 0;

        $nonCash = $omset - $cash;

        $labelsPayment[] = date('d M', strtotime($tanggal));
        $dataCash[] = (int)$cash;
        $dataNonCash[] = (int)$nonCash;
    }



        return $this->render('index', [
            'shifts' => $shifts,
            'totalShiftHariIni' => $totalShiftHariIni,
            'totalOmsetHariIni' => $totalOmsetHariIni,
            'totalCashHariIni' => $totalCashHariIni,
            'totalSelisihHariIni' => $totalSelisihHariIni,
            'labels' => $labels,
        'dataOmset' => $dataOmset,
        'dataModal' => $dataModal,
        'labelsPayment' => $labelsPayment,
    'dataCash' => $dataCash,
    'dataNonCash' => $dataNonCash,

        ]);
    }


	public function actionDashboard()
    {
        $today = date('Y-m-d');

        // ================= TOTAL SHIFT HARI INI =================
        $totalShiftHariIni = KasirShift::find()
            ->where(['between','tanggal_buka',
                $today.' 00:00:00',
                $today.' 23:59:59'
            ])
            ->andWhere(['status'=>'closed'])
            ->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            ->count();

        // ================= MODAL AWAL (SHIFT PERTAMA HARI INI) =================
        $modalShiftPertama = KasirShift::find()
            ->where(['between','tanggal_buka',
                $today.' 00:00:00',
                $today.' 23:59:59'
            ])
            ->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            ->orderBy(['tanggal_buka'=>SORT_ASC])
            ->one();

        $totalModal = $modalShiftPertama ? $modalShiftPertama->modal_awal : 0;

        // ================= TOTAL OMSET =================
        $totalOmset = KasirShift::find()
            ->where(['between','tanggal_buka',
                $today.' 00:00:00',
                $today.' 23:59:59'
            ])
            ->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            // ->andWhere(['status'=>'closed'])
            ->sum('total_penjualan');

        if(!$totalOmset) $totalOmset = 0;

        // ================= TOTAL CASH =================
        $totalCash = KasirShift::find()
            ->where(['between','tanggal_buka',
                $today.' 00:00:00',
                $today.' 23:59:59'
            ])
            ->andWhere(['status'=>'closed'])
            ->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            ->sum('total_cash_shift');

        if(!$totalCash) $totalCash = 0;

        $totalNonCash = $totalOmset - $totalCash;

        // ================= TOTAL SELISIH =================
        $totalSelisih = KasirShift::find()
            ->where(['between','tanggal_buka',
                $today.' 00:00:00',
                $today.' 23:59:59'
            ])
            ->andWhere(['status'=>'closed'])
            ->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            ->sum('selisih');

        if(!$totalSelisih) $totalSelisih = 0;

        // ================= GRAFIK 7 HARI =================
        $labels7Hari = [];
        $data7Hari = [];

        for ($i=6; $i>=0; $i--) {

            $date = date('Y-m-d', strtotime("-$i days"));

            $total = KasirShift::find()
                ->where(['between','tanggal_buka',
                    $date.' 00:00:00',
                    $date.' 23:59:59'
                ])
                ->andWhere(['status'=>'closed'])
                ->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
                ->sum('total_penjualan');

            if(!$total) $total = 0;

            $labels7Hari[] = date('d M', strtotime($date));
            $data7Hari[] = (float)$total;
        }

        // ================= GRID =================
        $dataProvider = new \yii\data\ActiveDataProvider([
            'query' => KasirShift::find()->orderBy(['id'=>SORT_DESC]),
            'pagination' => ['pageSize'=>10]
        ]);

        return $this->render('dashboard', [
            'totalShiftHariIni'=>$totalShiftHariIni,
            'totalModal'=>$totalModal,
            'totalOmset'=>$totalOmset,
            'totalCash'=>$totalCash,
            'totalNonCash'=>$totalNonCash,
            'totalSelisih'=>$totalSelisih,
            'labels7Hari'=>$labels7Hari,
            'data7Hari'=>$data7Hari,
            'dataProvider'=>$dataProvider
        ]);
    }

	public function actionDashboard2()
    {
        $today = date('Y-m-d');

        // =========================
        // REALTIME DARI NOTA
        // =========================
        $omsetRealtime = Nota::find()
            ->where(['tanggal' => $today])->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            ->sum('grand_total') ?? 0;

        $cashRealtime = Nota::find()
            ->where([
                'tanggal' => $today,
                'payment_method_id' => 1 // ID CASH
            ])
            ->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            ->sum('grand_total') ?? 0;

        $cashRealtime = Nota::find()
                ->alias('n')
                ->joinWith('paymentMethod p')
                ->where([
                	'tanggal' => $today,
                    // 'n.shift_id' => $shift->id,
                    'p.code' => 'TN'
                ])
                ->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
                ->sum('n.grand_total') ?? 0;;

        $nonCashRealtime = $omsetRealtime - $cashRealtime;

        $totalTransaksi = Nota::find()
            ->where(['tanggal' => $today])->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            ->count();

        // =========================
        // DATA SHIFT
        // =========================
        $shiftToday = KasirShift::find()
            ->where(['between', 'tanggal_buka',
                $today.' 00:00:00',
                $today.' 23:59:59'
            ])
            ->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            ->all();

        $totalShift = count($shiftToday);

        $totalFinal = 0;
        $totalSelisih = 0;
        $modalHariIni = 0;

        foreach ($shiftToday as $shift) {
            if ($shift->status === 'closed') {
                $totalFinal += $shift->total_penjualan;
                $totalSelisih += $shift->selisih;
            }
        }

        // Modal ambil dari shift pertama hari ini
        $shiftAwal = KasirShift::find()
            ->where(['between', 'tanggal_buka',
                $today.' 00:00:00',
                $today.' 23:59:59'
            ])
            ->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            ->orderBy(['tanggal_buka' => SORT_ASC])
            ->one();

        if ($shiftAwal) {
            $modalHariIni = $shiftAwal->modal_awal;
        }

        // =========================
        // CEK SHIFT OPEN
        // =========================
        $shiftOpen = KasirShift::find()
            ->where(['status' => 'open'])->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            ->one();

        // =========================
        // GRAFIK 7 HARI
        // =========================
        $labels = [];
        $dataOmset = [];

        for ($i = 6; $i >= 0; $i--) {
            $tgl = date('Y-m-d', strtotime("-$i days"));
            $labels[] = date('d M', strtotime($tgl));

            $total = KasirShift::find()
                ->where(['status' => 'closed'])
                ->andWhere(['between', 'tanggal_buka',
                    $tgl.' 00:00:00',
                    $tgl.' 23:59:59'
                ])
                ->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
                ->sum('total_penjualan') ?? 0;

            $dataOmset[] = (float)$total;
        }

        return $this->render('dashboard2', compact(
            'omsetRealtime',
            'cashRealtime',
            'nonCashRealtime',
            'totalTransaksi',
            'totalShift',
            'totalFinal',
            'totalSelisih',
            'modalHariIni',
            'shiftOpen',
            'labels',
            'dataOmset'
        ));
    }


    public function actionView($id)
    {
        $shift = KasirShift::find()
            ->with('user')
            ->where(['id' => $id])->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            ->one();

        if (!$shift) {
            throw new \yii\web\NotFoundHttpException('Shift tidak ditemukan.');
        }

        // Opsional: jika ingin paksa redirect saat shift open
        // misal login / redirect logout
        // $shift->status == 'open' bisa ditangani di view alert

        return $this->render('view', [
            'shift' => $shift
        ]);
    }


    public function actionBuka()
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(['site/login']);
        }

        $user = Usermember::findOne(Yii::$app->user->id);

        $cluster = Cluster::find()
            ->where(['eDeleted' => 'Tidak', 'idCluster' => $user->idCluster])
            ->one();

        $pembayaran = Pembayaran::find()
            ->where(['idCluster' => $cluster->idCluster, 'eDeleted' => 'Tidak'])
            ->orderBy(['iId' => SORT_DESC])
            ->one();

        if ($pembayaran && $pembayaran->eStatus == 'PROSES') {
            return $this->redirect(['admin/invoice']);
        }
        if ($pembayaran && $pembayaran->dateFinish < date('Y-m-d H:i:s')) {
            return $this->redirect(['admin/create-inv']);
        }

        $model = new KasirShift();
        $today = date('Y-m-d');

        // Cek shift terakhir hari ini
        $shiftTerakhir = KasirShift::find()
            ->where(['between', 'tanggal_buka',
                $today . ' 00:00:00',
                $today . ' 23:59:59'
            ])
            ->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            ->orderBy(['tanggal_buka' => SORT_DESC])
            ->one();

        if ($shiftTerakhir && $shiftTerakhir->status == 'open') {
            Yii::$app->session->setFlash('error', 'Masih ada shift yang belum ditutup.');
            return $this->redirect(['view', 'id' => $shiftTerakhir->id]);
        }

        $kemarin = date('Y-m-d', strtotime('-1 day'));

        $shiftKemarin = KasirShift::find()
            ->where(['DATE(tanggal_buka)' => $kemarin])
            ->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            ->orderBy(['id' => SORT_DESC])
            ->one();

        $saldoKemarin = $shiftKemarin ? $shiftKemarin->saldo_akhir_sistem : null;

        // var_dump($saldoKemarin);die;

        $shiftBelumTutup = KasirShift::find()
            ->where(['status' => 'open'])
            ->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            ->one();

        if ($shiftBelumTutup) {
            Yii::$app->session->setFlash('error', 'Masih ada shift yang belum ditutup.');
            return $this->redirect(['view', 'id' => $shiftBelumTutup->id]);
        }

        if ($model->load(Yii::$app->request->post())) {

            $model->user_id = Yii::$app->user->id;
            $model->total_penjualan = 0;
            $model->total_cash_shift = 0;
            $model->total_pengeluaran = 0;
            $model->status = 'open';
            $model->tanggal_buka = date('Y-m-d H:i:s');
            $model->idCluster = Yii::$app->user->identity->idCluster;

            // 🔥 LOGIC MODAL OTOMATIS
            if ($shiftTerakhir) {
                // Bukan shift pertama → ambil saldo akhir sistem
                $model->modal_awal = $shiftTerakhir->saldo_akhir_sistem;
            }
            // Jika shift pertama → pakai input manual

            $model->save(false);

            return $this->redirect(['view', 'id' => $model->id]);
        }

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


    public function actionTutup($id)
{
    $shift = KasirShift::findOne($id);

    if (!$shift || $shift->status == 'closed') {
        throw new \yii\web\NotFoundHttpException();
    }

    if (Yii::$app->request->post()) {

        $saldo_fisik = Yii::$app->request->post('saldo_fisik');

        // ===============================
        // TOTAL SEMUA PENJUALAN
        // ===============================
        $total_penjualan = Nota::find()
            ->where(['shift_id' => $shift->id])
            ->sum('grand_total');

        $shift->total_penjualan = $total_penjualan ?? 0;

        // ===============================
        // TOTAL CASH SAJA (untuk laci)
        // ===============================
        $total_cash = Nota::find()
            ->alias('n')
            ->joinWith('paymentMethod p')
            ->where([
                'n.shift_id' => $shift->id,
                'p.code' => 'TN'
            ])
            ->sum('n.grand_total');

        $shift->total_cash_shift = $total_cash ?? 0;

        // ===============================
        // TOTAL PENGELUARAN (UPDATE)
        // ===============================
        $total_pengeluaran = \nota\models\KasirPengeluaran::find()
            ->where(['shift_id' => $shift->id])
            ->sum('jumlah');

        $shift->total_pengeluaran = $total_pengeluaran ?? 0;

        // ===============================
        // HITUNG SALDO SISTEM
        // ===============================
        $shift->saldo_akhir_sistem =
            $shift->modal_awal +
            $shift->total_cash_shift -
            $shift->total_pengeluaran;

        $shift->saldo_akhir_fisik = $saldo_fisik;

        // ===============================
        // SELISIH
        // ===============================
        $shift->selisih =
            $shift->saldo_akhir_fisik -
            $shift->saldo_akhir_sistem;

        $shift->status = 'closed';
        $shift->tanggal_tutup = date('Y-m-d H:i:s');

        $shift->save(false);

        Yii::$app->session->setFlash('success', 'Kasir berhasil ditutup');
        return $this->redirect(['site/index']);
    }

    return $this->render('tutup', [
        'shift' => $shift
    ]);
}		

		public function actionPrint($id)
{
    $shift = KasirShift::findOne($id);

    if (!$shift) {
        throw new \yii\web\NotFoundHttpException();
    }

    // Total semua
    $total_penjualan = Nota::find()
        ->where(['shift_id' => $shift->id])
        ->sum('grand_total');

    // Total cash
    $total_cash = Nota::find()
        ->alias('n')
        ->joinWith('paymentMethod p')
        ->where([
            'n.shift_id' => $shift->id,
            'p.code' => 'TN'
        ])
        ->sum('n.grand_total');

    // Breakdown metode
    $breakdown = Nota::find()
        ->alias('n')
        ->select([
            'p.code as metode',
            'SUM(n.grand_total) as total'
        ])
        ->joinWith('paymentMethod p')
        ->where(['n.shift_id' => $shift->id])
        ->groupBy('p.code')
        ->asArray()
        ->all();

    return $this->renderPartial('print', [
        'shift' => $shift,
        'total_penjualan' => $total_penjualan ?? 0,
        'total_cash' => $total_cash ?? 0,
        'breakdown' => $breakdown
    ]);
}

	public function actionLaporanHarian()
{
	//untuk Owner , Supervisor
    $tanggal = Yii::$app->request->get('tanggal', date('Y-m-d'));

    $shifts = KasirShift::find()
        ->where(['status' => 'closed'])
        ->andWhere(['between', 'tanggal_buka',
            $tanggal.' 00:00:00',
            $tanggal.' 23:59:59'
        ])
        ->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
        ->all();

    $totalOmset = 0;
    $totalCash = 0;
    $totalNonCash = 0;
    $totalSelisih = 0;
    $totalShift = count($shifts);

    foreach ($shifts as $shift) {
        $totalOmset += $shift->total_penjualan;
        $totalCash += $shift->total_cash_shift;
        $totalSelisih += $shift->selisih;
    }

    $totalNonCash = $totalOmset - $totalCash;

    return $this->render('laporan-harian', compact(
        'tanggal',
        'totalOmset',
        'totalCash',
        'totalNonCash',
        'totalSelisih',
        'totalShift',
        'shifts'
    ));
}
	public function actionLaporanBulanan()
{
    $bulan = Yii::$app->request->get('bulan', date('m'));
    $tahun = Yii::$app->request->get('tahun', date('Y'));

    $start = "$tahun-$bulan-01";
    $end = date("Y-m-t", strtotime($start));

    $shifts = KasirShift::find()
        ->where(['status' => 'closed'])
        ->andWhere(['between', 'tanggal_buka',
            $start.' 00:00:00',
            $end.' 23:59:59'
        ])
        ->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
        ->all();

    $totalOmset = 0;
    $totalCash = 0;
    $totalSelisih = 0;

    $harian = [];

    foreach ($shifts as $shift) {

        $tgl = date('Y-m-d', strtotime($shift->tanggal_buka));

        $totalOmset += $shift->total_penjualan;
        $totalCash += $shift->total_cash_shift;
        $totalSelisih += $shift->selisih;

        if (!isset($harian[$tgl])) {
            $harian[$tgl] = 0;
        }

        $harian[$tgl] += $shift->total_penjualan;
    }

    ksort($harian);

    $labels = array_keys($harian);
    $data = array_values($harian);

    return $this->render('laporan-bulanan', compact(
        'bulan','tahun',
        'totalOmset','totalCash','totalSelisih',
        'labels','data'
    ));
}
	
	public function actionMarginBulanan()
{
    $bulan = Yii::$app->request->get('bulan', date('m'));
    $tahun = Yii::$app->request->get('tahun', date('Y'));

    $start = "$tahun-$bulan-01";
    $end = date("Y-m-t", strtotime($start));

    $notas = Nota::find()
        ->where(['between','tanggal',$start,$end])->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
        ->all();

    $harianOmset = [];
    $harianHpp = [];

    $totalOmset = 0;
    $totalHpp = 0;

    foreach ($notas as $nota) {

        $tgl = $nota->tanggal;

        if (!isset($harianOmset[$tgl])) {
            $harianOmset[$tgl] = 0;
            $harianHpp[$tgl] = 0;
        }

        foreach ($nota->items as $item) {

            $omset = $item->subtotal;
            $hpp = $item->qty * $item->barang->harga_beli;

            $harianOmset[$tgl] += $omset;
            $harianHpp[$tgl] += $hpp;

            $totalOmset += $omset;
            $totalHpp += $hpp;
        }
    }

    ksort($harianOmset);

    $labels = [];
    $dataMargin = [];

    foreach ($harianOmset as $tgl => $omset) {

        $hpp = $harianHpp[$tgl];
        $profit = $omset - $hpp;

        $margin = $omset > 0 ? round(($profit/$omset)*100,2) : 0;

        $labels[] = date('d M', strtotime($tgl));
        $dataMargin[] = $margin;
    }

    $totalProfit = $totalOmset - $totalHpp;
    $marginPercent = $totalOmset > 0
        ? round(($totalProfit/$totalOmset)*100,2)
        : 0;

    return $this->render('margin-bulanan', compact(
        'bulan','tahun',
        'totalOmset','totalHpp','totalProfit','marginPercent',
        'labels','dataMargin'
    ));
}

	public function actionPerbandinganBulanan()
{
    $bulanIni = date('m');
    $tahunIni = date('Y');

    $bulanLaluDate = date('Y-m-01', strtotime('-1 month'));
    $bulanLalu = date('m', strtotime($bulanLaluDate));
    $tahunLalu = date('Y', strtotime($bulanLaluDate));

    // Helper function hitung data
    $hitung = function($bulan, $tahun) {

        $start = "$tahun-$bulan-01";
        $end = date("Y-m-t", strtotime($start));

        $notas = Nota::find()
            ->where(['between','tanggal',$start,$end])->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            ->all();

        $omset = 0;
        $hpp = 0;

        foreach ($notas as $nota) {
            foreach ($nota->items as $item) {

                $omset += $item->subtotal;
                $hpp += $item->qty * $item->barang->harga_beli;
            }
        }

        $profit = $omset - $hpp;
        $margin = $omset > 0 ? round(($profit/$omset)*100,2) : 0;

        return [
            'omset' => $omset,
            'hpp' => $hpp,
            'profit' => $profit,
            'margin' => $margin
        ];
    };

    $dataBulanIni = $hitung($bulanIni, $tahunIni);
    $dataBulanLalu = $hitung($bulanLalu, $tahunLalu);

    // Growth %
    $growthOmset = $dataBulanLalu['omset'] > 0
        ? round((($dataBulanIni['omset'] - $dataBulanLalu['omset'])
            / $dataBulanLalu['omset']) * 100, 2)
        : 0;

    return $this->render('perbandingan-bulanan', compact(
        'dataBulanIni',
        'dataBulanLalu',
        'growthOmset',
        'bulanIni','tahunIni',
        'bulanLalu','tahunLalu'
    ));
}
    
    public function actionPengeluaran()
{
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

    $shift_id = Yii::$app->request->post('shift_id');
    $keterangan = Yii::$app->request->post('keterangan');
    $jumlah = Yii::$app->request->post('jumlah');

    if(!$shift_id || !$jumlah){
        return [
            'success' => false,
            'message' => 'Data kosong'
        ];
    }

    $model = new \nota\models\KasirPengeluaran();
    $model->shift_id = $shift_id;
    $model->keterangan = $keterangan;
    $model->jumlah = $jumlah;
    $model->tanggal = date('Y-m-d H:i:s');
    $model->user_id = Yii::$app->user->id;
    $model->idCluster = Yii::$app->user->identity->idCluster;

    if($model->save()){
        return [
            'success' => true
        ];
    }

    return [
        'success' => false,
        'message' => $model->errors
    ];
}


}
