<?php


namespace App\Http\Controllers\backend;

use App\Http\Controllers\Controller;

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

class DepositPackageController extends Controller
{
    public function index(Request $request)
    {
        $q = DepositPackage::query();

        if ($s = $request->get('q')) {
            $q->where('title', 'like', "%{$s}%");
        }
        if ($st = $request->get('status')) {
            $q->where('status', $st);
        }

        $packages = $q->orderBy('sort_order')->orderByDesc('id')->paginate(12)->withQueryString();
        return view('backend.deposit_packages.index', compact('packages'));
    }

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

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

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

    public function show($id)
    {
        $package = DepositPackage::findOrFail($id);
        return view('backend.deposit_packages.show', compact('package'));
    }

    public function edit($id)
    {
        $package = DepositPackage::findOrFail($id);
        return view('backend.deposit_packages.edit', compact('package'));
    }

    public function update(Request $request, $id)
    {
        $package = DepositPackage::findOrFail($id);

        $data = $request->validate([
            'title'            => 'required|string|max:255',
            'principal_amount' => 'required|numeric|min:0',
            'bonus_percent'    => 'required|numeric|min:0',
            'badge_text'       => 'nullable|string|max:50',
            'status'           => 'required|in:active,inactive',
            'sort_order'       => 'nullable|integer|min:0',
        ]);
        $data['sort_order'] = $data['sort_order'] ?? 0;

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

    public function destroy($id)
    {
        DepositPackage::findOrFail($id)->delete();
        return redirect(url('/admin/deposit-packages'))->with('success', 'Package deleted.');
    }

    public function toggle($id)
    {
        $p = DepositPackage::findOrFail($id);
        $p->update(['status' => $p->status === 'active' ? 'inactive' : 'active']);
        return back()->with('success', 'Status toggled.');
    }
}
