<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\HasilPrediksi;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\PrediksiExport;
use Carbon\Carbon;
use Illuminate\Http\Request;

class RiwayatControllers extends Controller
{
    public function index()
    {
        $riwayat = HasilPrediksi::where('user_id', Auth::id())
            ->selectRaw('YEAR(tanggal) as year, MONTH(tanggal) as month, count(*) as total_hari')
            ->groupBy('year', 'month')
            ->orderBy('year', 'asc')
            ->orderBy('month', 'asc')
            ->get();

        return view('user.riwayat.index', compact('riwayat'));
    }

    public function exportExcel($year, $month)
    {
        $year  = (int) $year;
        $month = (int) $month;

        $nama_bulan = Carbon::create()->month($month)->locale('id')->monthName;
        $nama_file  = "Laporan_Prediksi_{$nama_bulan}_{$year}.xlsx";

        return Excel::download(new PrediksiExport($year, $month), $nama_file);
    }

    public function destroy($year, $month)
    {
        try {
            $year  = (int) $year;
            $month = (int) $month;

            HasilPrediksi::where('user_id', Auth::id())
                ->whereRaw('YEAR(tanggal) = ?', [$year])
                ->whereRaw('MONTH(tanggal) = ?', [$month])
                ->delete();

            return response()->json(['success' => 'Data prediksi bulan tersebut berhasil dihapus.']);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Gagal menghapus data.'], 500);
        }
    }
}