<?php

namespace App\Http\Controllers;

use App\Models\ObatMasuk;
use App\Models\Kategori;
use App\Models\Satuan;
use App\Models\Supplier;
use Illuminate\Http\Request;
use Carbon\Carbon;

class ObatMasukController extends Controller
{
    public function index(Request $request)
    {
        $query = ObatMasuk::query();

        // Search
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('nama_obat', 'like', "%{$search}%")
                  ->orWhere('kode_batch', 'like', "%{$search}%");
            });
        }

        // Filter by category
        if ($request->filled('kategori')) {
            $query->where('kategori_id', $request->kategori);
        }

        // Filter by status
        if ($request->filled('status')) {
            if ($request->status === 'tersedia') {
                $query->where('stok', '>', 0);
            } else if ($request->status === 'habis') {
                $query->where('stok', 0);
            }
        }

        $obatMasuks = $query->with(['kategori', 'satuan', 'supplier'])
            ->orderBy('tanggal_penerimaan', 'desc')
            ->paginate(10);
        $kategoris = Kategori::all();

        // Get filter month and year (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);

        // Pie chart data - Medicine trend (top 5 medicines by stock received) for selected month
        $medicineTrend = ObatMasuk::selectRaw('nama_obat, SUM(stok) as total_stok')
            ->whereMonth('tanggal_penerimaan', $filterMonth)
            ->whereYear('tanggal_penerimaan', $filterYear)
            ->groupBy('nama_obat')
            ->orderByDesc('total_stok')
            ->limit(5)
            ->get();
        
        $pieLabels = $medicineTrend->pluck('nama_obat')->toArray();
        $pieData = $medicineTrend->pluck('total_stok')->toArray();
        $totalStock = array_sum($pieData);

        // 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,
            ];
        }

        return view('obat-masuk.index', compact(
            'obatMasuks', 
            'kategoris',
            'pieLabels',
            'pieData',
            'totalStock',
            'monthOptions',
            'filterMonth',
            'filterYear',
            'selectedDate'
        ));
    }

    public function create()
    {
        $kategoris = Kategori::orderBy('nama')->get();
        $satuans = Satuan::orderBy('nama')->get();
        $suppliers = Supplier::orderBy('nama')->get();
        
        return view('obat-masuk.create', compact('kategoris', 'satuans', 'suppliers'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'nama_obat' => 'required|string|max:200',
            'kategori_id' => 'required|exists:kategoris,id',
            'satuan_id' => 'required|exists:satuans,id',
            'sumber_dana' => 'nullable|string|max:200',
            'kode_batch' => 'required|string|max:50',
            'barcode' => 'nullable|string|max:100',
            'stok' => 'required|integer|min:1',
            'tanggal_penerimaan' => 'required|date',
            'tanggal_kadaluarsa' => 'required|date|after:tanggal_penerimaan',
            'no_faktur' => 'nullable|string|max:50',
            'no_sbbk' => 'nullable|string|max:100',
            'catatan' => 'nullable|string',
        ]);

        $validated['user_id'] = auth()->id();

        ObatMasuk::create($validated);

        return redirect()->route('obat-masuk.index')->with('success', 'Data obat masuk berhasil ditambahkan');
    }

    public function show(ObatMasuk $obatMasuk)
    {
        $obatMasuk->load(['kategori', 'satuan', 'supplier', 'user']);
        return view('obat-masuk.show', compact('obatMasuk'));
    }

    public function edit(ObatMasuk $obatMasuk)
    {
        $kategoris = Kategori::orderBy('nama')->get();
        $satuans = Satuan::orderBy('nama')->get();
        $suppliers = Supplier::orderBy('nama')->get();
        
        return view('obat-masuk.edit', compact('obatMasuk', 'kategoris', 'satuans', 'suppliers'));
    }

    public function update(Request $request, ObatMasuk $obatMasuk)
    {
        $validated = $request->validate([
            'nama_obat' => 'required|string|max:200',
            'kategori_id' => 'required|exists:kategoris,id',
            'satuan_id' => 'required|exists:satuans,id',
            'sumber_dana' => 'nullable|string|max:200',
            'kode_batch' => 'required|string|max:50',
            'barcode' => 'nullable|string|max:100',
            'stok' => 'required|integer|min:0',
            'tanggal_penerimaan' => 'required|date',
            'tanggal_kadaluarsa' => 'required|date|after:tanggal_penerimaan',
            'no_faktur' => 'nullable|string|max:50',
            'no_sbbk' => 'nullable|string|max:100',
            'catatan' => 'nullable|string',
        ]);

        $obatMasuk->update($validated);

        return redirect()->route('obat-masuk.index')->with('success', 'Data obat masuk berhasil diperbarui');
    }

    public function destroy(ObatMasuk $obatMasuk)
    {
        $obatMasuk->delete();
        return redirect()->route('obat-masuk.index')->with('success', 'Data obat masuk berhasil dihapus');
    }
}
