<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LoyaltyController extends Controller
{
    public function settings()
    {
        $ratio = DB::table('settings')->where('key', 'loyalty_points_ratio')->first();
        $redemption = DB::table('settings')->where('key', 'loyalty_points_redemption')->first();

        return view('loyalty.settings', [
            'ratio' => $ratio ? $ratio->value : 1,
            'redemption' => $redemption ? $redemption->value : 1,
        ]);
    }

    public function updateSettings(Request $request)
    {
        $request->validate([
            'ratio' => 'required|numeric|min:0.01',
            'redemption' => 'required|numeric|min:0.01',
        ]);

        DB::table('settings')->updateOrInsert(
            ['key' => 'loyalty_points_ratio'],
            ['value' => $request->ratio]
        );

        DB::table('settings')->updateOrInsert(
            ['key' => 'loyalty_points_redemption'],
            ['value' => $request->redemption]
        );

        return back()->with('success', 'Loyalty settings updated successfully.');
    }

    public static function getPointsRatio()
    {
        $setting = DB::table('settings')->where('key', 'loyalty_points_ratio')->first();

        return $setting ? (float) $setting->value : 1;
    }

    public static function getRedemptionRatio()
    {
        $setting = DB::table('settings')->where('key', 'loyalty_points_redemption')->first();

        return $setting ? (float) $setting->value : 1;
    }

    public static function calculatePointsEarned(float $total): int
    {
        $ratio = self::getPointsRatio();

        return floor($total * $ratio);
    }

    public static function calculateRedemptionValue(int $points): float
    {
        $ratio = self::getRedemptionRatio();

        return $points * $ratio;
    }
}
