<?php

namespace App\Http\Controllers;

use App\Models\Obat;
use App\Models\ObatMasuk;
use App\Models\ObatKeluar;
use Carbon\Carbon;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function index(Request $request)
    {
        // Get filter month and year for chart (default to current month)
        $filterMonth = $request->get('chart_month', now()->month);
        $filterYear = $request->get('chart_year', now()->year);
        
        // Create date object for the selected month
        $selectedDate = Carbon::createFromDate($filterYear, $filterMonth, 1);

        // Statistics
        $totalJenisObat = ObatMasuk::count();
        $obatMasukBulanIni = ObatMasuk::whereMonth('tanggal_penerimaan', now()->month)
            ->whereYear('tanggal_penerimaan', now()->year)
            ->count();
        $obatKeluarBulanIni = ObatKeluar::whereMonth('tanggal_pengeluaran', now()->month)
            ->whereYear('tanggal_pengeluaran', now()->year)
            ->count();
        $kadaluarsaDekat = ObatMasuk::where('tanggal_kadaluarsa', '<=', now()->addMonths(4))
            ->where('tanggal_kadaluarsa', '>=', now())
            ->count();

        // Chart data - daily data for selected month (line chart)
        $daysInMonth = $selectedDate->daysInMonth;
        $labels = [];
        $obatMasukData = [];
        $obatKeluarData = [];

        for ($i = 1; $i <= $daysInMonth; $i++) {
            $date = Carbon::create($filterYear, $filterMonth, $i);
            $labels[] = $i;
            
            $obatMasukData[] = ObatMasuk::whereDate('tanggal_penerimaan', $date)->count();
            $obatKeluarData[] = ObatKeluar::whereDate('tanggal_pengeluaran', $date)->count();
        }

        // Generate month options for filter (last 12 months)
        $monthOptions = [];
        for ($i = 0; $i < 12; $i++) {
            $date = now()->subMonths($i);
            $monthOptions[] = [
                'value' => $date->format('Y-m'),
                'label' => $date->translatedFormat('F Y'),
                'month' => $date->month,
                'year' => $date->year,
            ];
        }

        // Expiring medicines
        $obatKadaluarsa = ObatMasuk::where('tanggal_kadaluarsa', '<=', now()->addMonths(4))
            ->with('obat')
            ->orderBy('tanggal_kadaluarsa', 'asc')
            ->limit(10)
            ->get();

        return view('dashboard.index', compact(
            'totalJenisObat',
            'obatMasukBulanIni',
            'obatKeluarBulanIni',
            'kadaluarsaDekat',
            'labels',
            'obatMasukData',
            'obatKeluarData',
            'obatKadaluarsa',
            'monthOptions',
            'filterMonth',
            'filterYear',
            'selectedDate'
        ));
    }
}

