<?php

namespace App\Http\Controllers;

use App\Models\Department;
use App\Models\MovementStock;
use App\Exports\AnnualReportExport;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class AnnualReportController extends Controller
{
    public function index(Request $request)
    {
        if (!auth()->user()->hasPermissionTo('movement_stocks.view')) {
            abort(403, 'Vous n\'êtes pas autorisé à accéder à cette page.');
        }

        $year = $request->get('year', now()->year);
        $departmentId = $request->get('department_id');

        $query = MovementStock::with(['product', 'department', 'user'])
            ->whereDeletedAt(null)
            ->whereYear('created_at', $year)
            ->orderBy('created_at', 'desc');

        if ($departmentId) {
            $query->where('department_id', $departmentId);
        }

        $movements = $query->paginate(20)->withQueryString();
        $departments = Department::orderBy('name')->whereNull('deleted_at')->get();

        $years = range(now()->year, now()->year - 5);

        return view('annual-report.index', compact('movements', 'departments', 'years', 'year', 'departmentId'));
    }

    public function export(Request $request)
    {
        if (!auth()->user()->hasPermissionTo('movement_stocks.view')) {
            abort(403, 'Vous n\'êtes pas autorisé à exporter les données.');
        }

        $year = (int) ($request->get('year', now()->year));
        $departmentId = $request->get('department_id') ? (int) $request->get('department_id') : null;

        $export = new AnnualReportExport($year, $departmentId);

        $filename = 'rapport_annuel_' . $year . '_' . now()->format('Y-m-d_His') . '.xlsx';

        return Excel::download($export, $filename);
    }
}
