<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\TransaksiParkir;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class LaporanController extends Controller
{
    
    private function getTrans() {
        // $query = TransaksiParkir::all();

        // return $query;
        return TransaksiParkir::query();
    }
    
    public function daily(Request $request)
    {
        $tanggal = $request->query('tanggal');
        $shift   = $request->query('shift');
        $harian  = $request->query('harian');
        $report  = $request->input('report');

        Log::info($request->all());
        // Tentukan field tanggal
        $dateField = $this->resolveDateField($shift, $harian);

        // Config jenis report
        $reportConfig = [
            'harian' => [
                'select' => 'jm.id, jm.nama as vehicle, COUNT(*) as jml, SUM(bayar_keluar) as total_bayar',
                'group'  => 'jm.id, jm.nama',
                'order'  => 'jm.id, jm.nama',
                'join'   => [['jenis_mobil as jm', 'jm.id', 'transaksi_parkir.id_kendaraan']],
            ],
            'vehicle' => [
                'select' => 'jm.id, jm.nama as vehicle, COUNT(*) as jml, SUM(bayar_keluar) as total_bayar',
                'group'  => 'jm.id, jm.nama',
                'order'  => 'jm.id, jm.nama',
                'join'   => [['jenis_mobil as jm', 'jm.id', 'transaksi_parkir.id_kendaraan']],
            ],
            'gate' => [
                'select' => 'np.id, np.nama as gate, COUNT(*) as jml, SUM(bayar_keluar) as total_bayar',
                'group'  => 'np.id, np.nama',
                'order'  => 'np.id, np.nama',
                'join'   => [['nama_pos as np', 'np.id', 'transaksi_parkir.id_pintu_keluar']],
            ],
            'operator' => [
                'select' => 'p.nomer, p.nama as operator, COUNT(*) as jml, SUM(bayar_keluar) as total_bayar',
                'group'  => 'p.nomer, p.nama',
                'order'  => 'p.nomer, p.nama',
                'join'   => [['pegawai as p', 'p.nomer', 'transaksi_parkir.id_op_keluar']],
            ],
            'payment' => [
                'select' => 'rep_bank as payment, COUNT(*) as jml, SUM(bayar_keluar) as total_bayar',
                'group'  => 'rep_bank',
                'order'  => 'rep_bank',
                'join'   => [],
            ],
        ];
        Log::info(json_encode($reportConfig[$report], JSON_PRETTY_PRINT));

        if (!isset($reportConfig[$report])) {
            return response()->json([
                'status' => 'failed',
                'desc'   => 'Jenis report tidak valid'
            ], 400);
        }

        $config = $reportConfig[$report];
        // $koneKemana = $this->connecTo($parameter);

        // Function helper bikin query dasar
        $buildQuery = function ($paymentType) use ($config, $tanggal, $dateField) {
            $query = $this->getTrans()
                ->selectRaw($config['select']);

            // Apply join
            foreach ($config['join'] as $join) {
                $query->leftJoin($join[0], $join[1], '=', $join[2]);
            }

            // Filter tanggal
            if ($tanggal) {
                $query->whereDate($dateField, '=', $tanggal);
            }

            // Filter cara bayar
            $query->where(function ($q) use ($paymentType) {
                if ($paymentType === 'cash') {
                    $q->whereRaw('cara_bayar <> 3')
                    ->orWhereRaw('cara_bayar is null');
                } else { // cashless
                    $q->where('cara_bayar', 3);
                }
            });

            return $query
                ->groupByRaw($config['group'])
                ->orderByRaw($config['order']);
        };

        // Eksekusi cash & cashless
        $resultCash     = $buildQuery('cash')->get();
        $resultCashless = $buildQuery('cashless')->get();

        // Hitung total
        $jmlTotal    = $resultCash->sum('jml') + $resultCashless->sum('jml');
        $incomeTotal = $resultCash->sum('total_bayar') + $resultCashless->sum('total_bayar');

        return response()->json([
            'status' => 'success',
            'result' => [
                'cash'     => $resultCash,
                'cashless' => $resultCashless,
            ],
            'total' => [
                'jumlah' => $jmlTotal,
                'income' => $incomeTotal,
            ]
        ]);
    }

    /**
     * Tentukan field tanggal yang dipakai
     */
    private function resolveDateField($shift, $harian): string
    {
        $isShift  = ($shift !== null && $shift !== 0 && $shift !== '0' && $shift !== false);
        $isHarian = ($harian !== null && $harian !== 0 && $harian !== '0' && $harian !== false);

        if ($isHarian) {
            return 'waktu_keluar';
        } elseif ($isShift) {
            return 'pklogin';
        }
        return 'waktu_keluar';
    }

    
    public function harian(Request $request)
    {

        // $method = $request->input('tanggal');

        if (!$request->input('tanggal')) {
            return response()->json([
                'status' => 'failed',
                'desc' => 'harap masuk kan metode pencarian'
            ]);
        }

        $tanggal = $request->input('tanggal');
        $shift = $request->input('shift');
        $harian = $request->input('harian');
        Log::info($shift);
        // $cashless = $request->input('cashless');

        $cash = [];
        $cashless = [];

        // Mulai query dengan select dasar
        $payment = ['cash', 'cashless'];
        // Tentukan kolom tanggal berdasarkan input shift
        // $dateField = ($shift == 1) ? 'pklogin' : 'waktu_keluar';
        // $query = TransaksiParkir::selectRaw('jm.id, jm.nama as vehicle, COUNT(*) as jml, SUM(bayar_keluar) as VALUE')
        // ->leftJoin('jenis_mobil as jm','jm.id','=','transaksi_parkir.id_kendaraan');
        // $query->selectRaw("DATE($dateField) as tanggal");

        // Terapkan filter tanggal berdasarkan input
        $totalTrans = 0;
        $totalIncome = 0;

        // if ($shift === null || $shift === 0 || $shift === '0' || $shift === false) {
        //     $dateField = 'pklogin';
        // } else { 
        //     $dateField = 'waktu_keluar' ;
        // }

        // if ($harian === null || $harian === 0 || $harian === '0' || $harian === false) {
        //     $dateField = 'waktu_keluar' ;
        // } else { 
        //     $dateField = 'pklogin';
        // }

        $isShift = ($shift !== null && $shift !== 0 && $shift !== '0' && $shift !== false);
        $isHarian = ($harian !== null && $harian !== 0 && $harian !== '0' && $harian !== false);

        if ($isHarian) {
            $dateField = 'waktu_keluar'; // harian aktif → pklogin
        } elseif ($isShift) {
            $dateField = 'pklogin'; // shift aktif → waktu_keluar
        } else {
            $dateField = 'waktu_keluar'; // default
        }
        // Log::info('Memproses permintaan dengan perhitungan : ' . $dateField);
        // Cash payment initialize
        $queryCash = $this->getTrans()->selectRaw('jm.id, jm.nama as vehicle, COUNT(*) as jml, SUM(bayar_keluar) as total_bayar')
                ->leftJoin('jenis_mobil as jm','jm.id','=','transaksi_parkir.id_kendaraan');

        if ($tanggal) {
            $queryCash->whereDate($dateField, '=', $tanggal);
        }
        Log::info('Find cash transaksi with params date : ' . $tanggal . ', and : ' . $dateField);
        $resultCash = $queryCash
            ->where(function ($q) {
                $q->whereRaw('cara_bayar <> 3')
                    ->orWhereRaw('cara_bayar is null');
                })
                // ->where(function ($q) {
                //     $q->where('status_transaksi', '-0')
                //     ->orWhere('status_transaksi', '3');
                // })
            ->groupByRaw("jm.id, jm.nama")
            ->orderByRaw("jm.id, jm.nama")
            ->get();
        // Log::info($resultCash->toSql());

        $jmlCash = 0;
        $incomeCash = 0;
        foreach ($resultCash as $row) {
            $jmlCash += $row->jml;
            $incomeCash += $row->total_bayar;
        }

        // Cashless payment initialize
        $queryCashless = $this->getTrans()->selectRaw('jm.id, jm.nama as vehicle, COUNT(*) as jml, SUM(bayar_keluar) as total_bayar')
                            ->leftJoin('jenis_mobil as jm','jm.id','=','transaksi_parkir.id_kendaraan');

        if ($tanggal) {
            $queryCashless->whereDate($dateField, '=', $tanggal);
        }
        Log::info(' Cari data cashless dengan tanggal : ' . $tanggal);

        $resultCashless = $queryCashless
            // ->where(function ($q) {
            //     $q->where('status_transaksi', '-0')
            //         ->orWhere('status_transaksi','3');
            // })
            ->where('cara_bayar', 3) 
            ->groupByRaw("jm.id, jm.nama")
            ->orderByRaw("jm.id, jm.nama")
            ->get();

        Log::info($resultCashless);
        $jmlCashless = 0;
        $incomeCashless = 0;

        foreach ($resultCashless as $row) {
            $jmlCashless += $row->jml;
            $incomeCashless += $row->total_bayar;
        }


        $totalTrans = $jmlCash + $jmlCashless;
        $totalIncome = $incomeCash + $incomeCashless;
        // Log::info($incomeCashless);
        
        return response()->json([
            'status' => 'success',
            'result' => [
                'cash' => $resultCash,
                'cashless' => $resultCashless,
            ],
            'total' => [
                'jumlah' => $totalTrans,
                'income' => $totalIncome,
            ]
        ]);
    }

    public function payment(Request $request)
    {
        if (!$request->input('tanggal')) {
            return response()->json([
                'status' => 'failed',
                'desc' => 'harap masuk kan metode pencarian'
            ]);
        }

        $tanggal = $request->input('tanggal');
        $shift = $request->input('shift');
        $harian = $request->input('harian');
        Log::info($shift);

        $cash = [];
        $cashless = [];

        // Mulai query dengan select dasar
        $payment = ['cash', 'cashless'];
        $totalTrans = 0;
        $totalIncome = 0;

        $isShift = ($shift !== null && $shift !== 0 && $shift !== '0' && $shift !== false);
        $isHarian = ($harian !== null && $harian !== 0 && $harian !== '0' && $harian !== false);

        if ($isHarian) {
            $dateField = 'waktu_keluar'; // harian aktif → pklogin
        } elseif ($isShift) {
            $dateField = 'pklogin'; // shift aktif → waktu_keluar
        } else {
            $dateField = 'waktu_keluar'; // default
        }

        $queryCash = $this->getTrans()->selectRaw('rep_bank as payment, COUNT(*) as jml, SUM(bayar_keluar) as total_bayar');
        if ($tanggal) {
            $queryCash->whereDate($dateField, '=', $tanggal);
        }
        Log::info('Find cash transaksi with params date : ' . $tanggal . ', and : ' . $dateField);
        $resultCash = $queryCash
            ->where(function ($q) {
                $q->whereRaw('cara_bayar <> 3')
                    ->orWhereRaw('cara_bayar is null');
                })
            ->groupByRaw("rep_bank")
            ->orderByRaw("rep_bank")
            ->get();

        $jmlCash = 0;
        $incomeCash = 0;
        foreach ($resultCash as $row) {
            $jmlCash += $row->jml;
            $incomeCash += $row->total_bayar;
        }

        // Cashless payment initialize
        $queryCashless = $this->getTrans()->selectRaw('rep_bank as payment, COUNT(*) as jml, SUM(bayar_keluar) as total_bayar');
        if ($tanggal) {
            $queryCashless->whereDate($dateField, '=', $tanggal);
        }
        Log::info(' Cari data cashless dengan tanggal : ' . $tanggal);

        $resultCashless = $queryCashless
            ->where('cara_bayar', 3) 
            ->groupByRaw("rep_bank")
            ->orderByRaw("rep_bank")
            ->get();

        Log::info($resultCashless);
        $jmlCashless = 0;
        $incomeCashless = 0;

        foreach ($resultCashless as $row) {
            $jmlCashless += $row->jml;
            $incomeCashless += $row->total_bayar;
        }


        $totalTrans = $jmlCash + $jmlCashless;
        $totalIncome = $incomeCash + $incomeCashless;
        // Log::info($incomeCashless);
        
        return response()->json([
            'status' => 'success',
            'result' => [
                'cash' => $resultCash,
                'cashless' => $resultCashless,
            ],
            'total' => [
                'jumlah' => $totalTrans,
                'income' => $totalIncome,
            ]
        ]);
    }

    public function operator(Request $request)
    {
        if (!$request->input('tanggal')) {
            return response()->json([
                'status' => 'failed',
                'desc' => 'harap masuk kan metode pencarian'
            ]);
        }
        
        $tanggal = $request->input('tanggal');
        $shift = $request->input('shift');
        $harian = $request->input('harian');
        Log::info($shift);

        $cash = [];
        $cashless = [];

        // Mulai query dengan select dasar
        $payment = ['cash', 'cashless'];
        $totalTrans = 0;
        $totalIncome = 0;

        $isShift = ($shift !== null && $shift !== 0 && $shift !== '0' && $shift !== false);
        $isHarian = ($harian !== null && $harian !== 0 && $harian !== '0' && $harian !== false);

        if ($isHarian) {
            $dateField = 'waktu_keluar'; // harian aktif → pklogin
        } elseif ($isShift) {
            $dateField = 'pklogin'; // shift aktif → waktu_keluar
        } else {
            $dateField = 'waktu_keluar'; // default
        }

        $queryCash = $this->getTrans()->selectRaw('id_op_keluar as operator, p.nama, COUNT(*) as jml, SUM(bayar_keluar) as total_bayar')
                        ->leftJoin('pegawai as p','p.nomer','=','transaksi_parkir.id_op_keluar');
        if ($tanggal) {
            $queryCash->whereDate($dateField, '=', $tanggal);
        }
        Log::info('Find cash transaksi with params date : ' . $tanggal . ', and : ' . $dateField);
        $resultCash = $queryCash
            ->where(function ($q) {
                $q->whereRaw('cara_bayar <> 3')
                    ->orWhereRaw('cara_bayar is null');
                })
            ->groupByRaw("id_op_keluar, p.nama")
            ->orderByRaw("id_op_keluar, p.nama")
            ->get();

        $jmlCash = 0;
        $incomeCash = 0;
        foreach ($resultCash as $row) {
            $jmlCash += $row->jml;
            $incomeCash += $row->total_bayar;
        }

        // Cashless payment initialize
        $queryCashless = $this->getTrans()->selectRaw('id_op_keluar as operator, p.nama, COUNT(*) as jml, SUM(bayar_keluar) as total_bayar')
                        ->leftJoin('pegawai as p','p.nomer','=','transaksi_parkir.id_op_keluar');

        if ($tanggal) {
            $queryCashless->whereDate($dateField, '=', $tanggal);
        }
        Log::info(' Cari data cashless dengan tanggal : ' . $tanggal);

        $resultCashless = $queryCashless
            ->where('cara_bayar', 3) 
            ->groupByRaw("id_op_keluar, p.nama")
            ->orderByRaw("id_op_keluar, p.nama")
            ->get();

        Log::info($resultCashless);
        $jmlCashless = 0;
        $incomeCashless = 0;

        foreach ($resultCashless as $row) {
            $jmlCashless += $row->jml;
            $incomeCashless += $row->total_bayar;
        }


        $totalTrans = $jmlCash + $jmlCashless;
        $totalIncome = $incomeCash + $incomeCashless;
        // Log::info($incomeCashless);
        
        return response()->json([
            'status' => 'success',
            'result' => [
                'cash' => $resultCash,
                'cashless' => $resultCashless,
            ],
            'total' => [
                'jumlah' => $totalTrans,
                'income' => $totalIncome,
            ]
        ]);
    }

    public function gate(Request $request)
    {
        
        if (!$request->input('tanggal')) {
            return response()->json([
                'status' => 'failed',
                'desc' => 'harap masuk kan metode pencarian'
            ]);
        }
        
        $tanggal = $request->input('tanggal');
        $shift = $request->input('shift');
        $harian = $request->input('harian');
        Log::info($shift);

        $cash = [];
        $cashless = [];

        // Mulai query dengan select dasar
        $payment = ['cash', 'cashless'];
        $totalTrans = 0;
        $totalIncome = 0;

        $isShift = ($shift !== null && $shift !== 0 && $shift !== '0' && $shift !== false);
        $isHarian = ($harian !== null && $harian !== 0 && $harian !== '0' && $harian !== false);

        if ($isHarian) {
            $dateField = 'waktu_keluar'; // harian aktif → pklogin
        } elseif ($isShift) {
            $dateField = 'pklogin'; // shift aktif → waktu_keluar
        } else {
            $dateField = 'waktu_keluar'; // default
        }

        $queryCash = $this->getTrans()->selectRaw('id_pintu_keluar as gate, np.nama, COUNT(*) as jml, SUM(bayar_keluar) as total_bayar')
                        ->leftJoin('nama_pos as np','np.id','=','transaksi_parkir.id_pintu_keluar');
        if ($tanggal) {
            $queryCash->whereDate($dateField, '=', $tanggal);
        }
        Log::info('Find cash transaksi with params date : ' . $tanggal . ', and : ' . $dateField);
        $resultCash = $queryCash
            ->where(function ($q) {
                $q->whereRaw('cara_bayar <> 3')
                    ->orWhereRaw('cara_bayar is null');
                })
            ->groupByRaw("id_pintu_keluar, np.nama")
            ->orderByRaw("id_pintu_keluar, np.nama")
            ->get();

        $jmlCash = 0;
        $incomeCash = 0;
        foreach ($resultCash as $row) {
            $jmlCash += $row->jml;
            $incomeCash += $row->total_bayar;
        }

        // Cashless payment initialize
        $queryCashless = $this->getTrans()->selectRaw('id_pintu_keluar as gate, np.nama, COUNT(*) as jml, SUM(bayar_keluar) as total_bayar')
                        ->leftJoin('nama_pos as np','np.id','=','transaksi_parkir.id_pintu_keluar');

        if ($tanggal) {
            $queryCashless->whereDate($dateField, '=', $tanggal);
        }
        Log::info(' Cari data cashless dengan tanggal : ' . $tanggal);

        $resultCashless = $queryCashless
            ->where('cara_bayar', 3) 
            ->groupByRaw("id_pintu_keluar, np.nama")
            ->orderByRaw("id_pintu_keluar, np.nama")
            ->get();

        Log::info($resultCashless);
        $jmlCashless = 0;
        $incomeCashless = 0;

        foreach ($resultCashless as $row) {
            $jmlCashless += $row->jml;
            $incomeCashless += $row->total_bayar;
        }


        $totalTrans = $jmlCash + $jmlCashless;
        $totalIncome = $incomeCash + $incomeCashless;
        // Log::info($incomeCashless);
        
        return response()->json([
            'status' => 'success',
            'result' => [
                'cash' => $resultCash,
                'cashless' => $resultCashless,
            ],
            'total' => [
                'jumlah' => $totalTrans,
                'income' => $totalIncome,
            ]
        ]);
    }
}    

    // $tanggal = $request->input('tanggal');
        // $shift = $request->input('shift');
        // $cashless = $request->input('cashless');

        // $query = TransaksiParkir::selectRaw('COUNT (*) as jml, SUM(bayar_keluar) as VALUE');
        // $dateField = ($shift == 1) ? 'pklogin' : 'waktu_keluar';
        // $query->selectRaw("DATE($dateField) as tanggal");
        
        // if ($tanggal) { 
        //     $query->whereDate($dateField, '=', $tanggal);
        // }

        // if ($cashless == 1) {
        //     $query->where('cara_bayar', 3);
        // } else {
        //     $query->where('cara_bayar', 2);
        // }
        
        // $query->groupBy('tanggal')
        //         ->orderBy('tanggal');
        // $result = $query->get();

        // return response()->json([
        //     'status' => 'success',
        //     'result' => $result,
        // ]);

