<?php

namespace App\Http\Controllers;

use App\Models\Client;
use Illuminate\Http\Request;

class DiscountController extends Controller
{
    /**
     * Store a newly created discount in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $clientId
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request, $clientId)
    {
        $client = Client::findOrFail($clientId);

        $validated = $request->validate([
            'amount' => 'required|numeric|min:0.01',
            'reason' => 'nullable|string|max:255',
            'date' => 'nullable|date',
        ]);

        $discount = $client->applyDiscount(
            $validated['amount'],
            $validated['reason'] ?? null
        );

        // Set date if provided
        if (isset($validated['date'])) {
            $discount->date = $validated['date'];
            $discount->save();
        }

        return redirect()->back()->with('message', 'Remise appliquée avec succès.');
    }
}
