<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\DepositPackage;
use Illuminate\Http\Request;

class DepositPackageController extends Controller
{
    public function index(Request $request)
    {
        $q = trim((string) $request->get('q'));
        $status = $request->get('status');

        $packages = DepositPackage::when($q, fn($qb) => $qb->where('title','like',"%{$q}%"))
            ->when($status, fn($qb) => $qb->where('status',$status))
            ->orderBy('sort_order')->orderBy('id')
            ->paginate(20)->withQueryString();

        return view('admin.deposit_packages.index', compact('packages','q','status'));
    }

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

    public function store(Request $request)
    {
        $data = $request->validate([
            'title'            => ['required','string','max:255'],
            'principal_amount' => ['required','numeric','min:1'],
            'bonus_percent'    => ['required','numeric','min:0','max:100'],
            'badge_text'       => ['nullable','string','max:20'],
            'status'           => ['required','in:active,inactive'],
            'sort_order'       => ['nullable','integer','min:0'],
        ]);

        if (!$data['badge_text']) {
            $data['badge_text'] = rtrim(rtrim(number_format($data['bonus_percent'], 2, '.', ''), '0'), '.').'%';
        }

        DepositPackage::create($data);
        return redirect()->route('admin.packages.index')->with('success','Package created.');
    }

    public function edit(DepositPackage $package)
    {
        return view('admin.deposit_packages.edit', compact('package'));
    }

    public function update(Request $request, DepositPackage $package)
    {
        $data = $request->validate([
            'title'            => ['required','string','max:255'],
            'principal_amount' => ['required','numeric','min:1'],
            'bonus_percent'    => ['required','numeric','min:0','max:100'],
            'badge_text'       => ['nullable','string','max:20'],
            'status'           => ['required','in:active,inactive'],
            'sort_order'       => ['nullable','integer','min:0'],
        ]);

        if (!$data['badge_text']) {
            $data['badge_text'] = rtrim(rtrim(number_format($data['bonus_percent'], 2, '.', ''), '0'), '.').'%';
        }

        $package->update($data);
        return redirect()->route('admin.packages.index')->with('success','Package updated.');
    }

    public function destroy(DepositPackage $package)
    {
        $package->delete();
        return redirect()->route('admin.packages.index')->with('success','Package deleted.');
    }
}
