<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\DataPenjualan;
use App\Exports\DataPenjualanExport;
use App\Exports\DataPenjualanRekapExport;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class DataPenjualanUserControllers extends Controller
{
    public function index()
    {
        // Mengambil semua pangkalan dengan total hari log datanya
        $pangkalanList = User::where(['role' => 'user'])
            ->withCount('dataPenjualan')
            ->get();

        // Menghitung status perhatian secara real-time untuk setiap pangkalan di halaman index
        foreach ($pangkalanList as $pangkalan) {
            $monthlyData = DataPenjualan::where(['user_id' => $pangkalan->id])
                ->select(DB::raw("DATE_FORMAT(tanggal, '%Y-%m') as bulan"), DB::raw("SUM(jumlah) as total"))
                ->groupBy('bulan')
                ->get();

            if ($monthlyData->isEmpty()) {
                $pangkalan->status_perhatian = 'Belum Ada Transaksi';
                continue;
            }

            $totals = $monthlyData->pluck('total');
            $average = $totals->avg();

            // Hitung Standar Deviasi
            $variance = 0;
            foreach ($totals as $t) {
                $variance += pow(($t - $average), 2);
            }
            $stdDev = sqrt($variance / $totals->count());

            // Hitung Koefisien Variasi (CV)
            $coefficentOfVariation = $average > 0 ? ($stdDev / $average) : 0;

            // Aturan sinkronisasi threshold indikator CV
            if ($coefficentOfVariation > 0.30) {
                $pangkalan->status_perhatian = 'PERLU PERHATIAN KHUSUS';
            } else if ($coefficentOfVariation > 0.15) {
                $pangkalan->status_perhatian = 'Pantauan Berkala';
            } else {
                $pangkalan->status_perhatian = 'Stabil (Aman)';
            }
        }

        return view('admin.data-penjualan-user.index', compact('pangkalanList'));
    }

    public function show(Request $request, $id)
    {
        Carbon::setLocale('id');

        $pangkalan = User::where(['role' => 'user'])->findOrFail($id);
        
        $filterBulanTahun = $request->get('bulan_tahun'); 
        $sortOrder = $request->get('sort', 'desc');

        $query = DataPenjualan::where('user_id', $id);

        if ($filterBulanTahun) {
            $yearMonth = explode('-', $filterBulanTahun);
            if (count($yearMonth) === 2) {
                $query->whereYear('tanggal', $yearMonth[0])
                      ->whereMonth('tanggal', $yearMonth[1]);
            }
        }

        $data_penjualan = $query->orderBy('tanggal', $sortOrder)->get();

        $availableMonths = DataPenjualan::where('user_id', $id)
            ->selectRaw('YEAR(tanggal) as year, MONTH(tanggal) as month')
            ->groupBy('year', 'month')
            ->orderBy('year', 'desc')
            ->orderBy('month', 'desc')
            ->get()
            ->map(function ($item) {
                $date = Carbon::createFromDate($item->year, $item->month, 1)->locale('id');
                return [
                    'value' => $date->format('Y-m'),
                    'label' => $date->translatedFormat('F Y')
                ];
            });

        // HITUNG ALASAN DETAIL EVALUASI MATRIKS UNTUK DITAMPILKAN DI PANEL VIEW SHOW
        $allMonthlyData = DataPenjualan::where(['user_id' => $id])
            ->select(DB::raw("DATE_FORMAT(tanggal, '%Y-%m') as bulan"), DB::raw("SUM(jumlah) as total"))
            ->groupBy('bulan')
            ->get();

        $statusPenting = 'Stabil (Aman)';
        $alasanAnalisis = 'Pola permintaan pasar konstan. Alokasi kuota tetap dapat dipertahankan.';
        $cvPersen = '0%';

        if ($allMonthlyData->isNotEmpty()) {
            $totals = $allMonthlyData->pluck('total');
            $average = $totals->avg();

            $variance = 0;
            foreach ($totals as $t) {
                $variance += pow(($t - $average), 2);
            }
            $stdDev = sqrt($variance / $totals->count());
            $cv = $average > 0 ? ($stdDev / $average) : 0;
            $cvPersen = round($cv * 100, 1) . '%';

            if ($cv > 0.30) {
                $statusPenting = 'PERLU PERHATIAN KHUSUS';
                $alasanAnalisis = 'Kesenjangan penjualan antarbulan sangat tinggi. Distribusi kuota wajib disesuaikan secara dinamis untuk menghindari kelangkaan atau penumpukan.';
            } else if ($cv > 0.15) {
                $statusPenting = 'Pantauan Berkala';
                $alasanAnalisis = 'Penjualan mengalami fluktuasi tingkat sedang. Diperlukan monitoring per kuartal secara rutin.';
            }
        }

        return view('admin.data-penjualan-user.show', compact(
            'pangkalan', 
            'data_penjualan', 
            'availableMonths', 
            'filterBulanTahun', 
            'sortOrder',
            'statusPenting',
            'alasanAnalisis',
            'cvPersen'
        ));
    }

    public function export(Request $request, $id)
    {
        $pangkalan = User::where(['role' => 'user'])->findOrFail($id);
        $filterBulanTahun = $request->get('bulan_tahun');

        if ($filterBulanTahun) {
            $bulanIndo = Carbon::parse($filterBulanTahun . '-01')->locale('id')->translatedFormat('F_Y');
            $filename = 'Data_Penjualan_' . str_replace(' ', '_', $pangkalan->name) . '_' . $bulanIndo . '.xlsx';
        } else {
            $filename = 'Data_Penjualan_' . str_replace(' ', '_', $pangkalan->name) . '_Keseluruhan.xlsx';
        }
        
        return Excel::download(new DataPenjualanExport($id, $filterBulanTahun), $filename);
    }

    public function exportRekapMassal()
    {
        $tanggalUnduh = Carbon::now()->format('d-m-Y');
        $filename = 'Rekap Data Penjualan Pangkalan_Diunduh tgl ' . $tanggalUnduh . '.xlsx';
        
        return Excel::download(new DataPenjualanRekapExport, $filename);
    }
}