<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\DataPenjualan;
use App\Models\HasilPrediksi;
use App\Models\Helpdesk;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class DashboardControllers extends Controller
{
    public function index()
    {
        $userId = Auth::id();
        $besok = Carbon::tomorrow()->format('Y-m-d');

        $totalPenjualan = DataPenjualan::where('user_id', $userId)->sum('jumlah');
        $estimasiBesok = HasilPrediksi::where('user_id', $userId)->where('tanggal', $besok)->first();
        $jumlahRiwayat = HasilPrediksi::where('user_id', $userId)
            ->selectRaw('YEAR(tanggal) as year, MONTH(tanggal) as month')
            ->groupBy('year', 'month')->get()->count();
        $jumlahHelpdesk = Helpdesk::where('user_id', $userId)->count();

        $chartHistori = DataPenjualan::where('user_id', $userId)->orderBy('tanggal', 'desc')->take(7)->get()->reverse();
        $chartPrediksi = HasilPrediksi::where('user_id', $userId)->orderBy('tanggal', 'asc')->take(15)->get();

        $penjualan = DataPenjualan::where('user_id', $userId)->get();
        $distribusi = [
            'Rendah (<10)' => $penjualan->where('jumlah', '<', 10)->count(),
            'Sedang (10-15)' => $penjualan->whereBetween('jumlah', [10, 15])->count(),
            'Tinggi (>15)' => $penjualan->where('jumlah', '>', 15)->count(),
        ];

        return view('user.dashboard.index', compact(
            'totalPenjualan', 'estimasiBesok', 'jumlahRiwayat', 'jumlahHelpdesk',
            'chartHistori', 'chartPrediksi', 'distribusi'
        ));
    }
}