<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;

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

class RewardSettingController extends Controller
{
    public function index()
    {
        $rewardSettings = RewardSetting::latest()->paginate(10);
        return view('admin.reward_settings.index', compact('rewardSettings'));
    }

    public function create()
    {
        return view('admin.reward_settings.create');
    }

    public function store(Request $request)
    {
        $data = $this->validated($request);
        // Checkbox -> boolean
        $data['is_active'] = $request->boolean('is_active');

        RewardSetting::create($data);

        return redirect()
            ->route('reward-settings.index')
            ->with('success', 'Reward setting created.');
    }

    public function show(RewardSetting $reward_setting)
    {
        return view('admin.reward_settings.show', ['rewardSetting' => $reward_setting]);
    }

    public function edit(RewardSetting $reward_setting)
    {
        return view('admin.reward_settings.edit', ['rewardSetting' => $reward_setting]);
    }

    public function update(Request $request, RewardSetting $reward_setting)
    {
        $data = $this->validated($request);
        $data['is_active'] = $request->boolean('is_active');

        $reward_setting->update($data);

        return redirect()
            ->route('reward-settings.index')
            ->with('success', 'Reward setting updated.');
    }

    public function destroy(RewardSetting $reward_setting)
    {
        $reward_setting->delete();

        return redirect()
            ->route('reward-settings.index')
            ->with('success', 'Reward setting deleted.');
    }

    /**
     * Central validation so rules are consistent for store/update.
     */
    protected function validated(Request $request): array
    {
        return $request->validate([
            'add_money_comm'       => ['required','numeric','min:0'],
            'send_money_comm'      => ['required','numeric','min:0'],
            'drive_offer_comm'     => ['required','numeric','min:0'],
            'mobile_recharge_comm' => ['required','numeric','min:0'],
            'paybills_comm'        => ['required','numeric','min:0'],
            'mobile_banking_comm'  => ['required','numeric','min:0'],
            'bank_trans_comm'      => ['required','numeric','min:0'],
            'is_active'            => ['nullable'], // handled as boolean() above
        ]);
    }
}
