<?php

namespace App\Http\Controllers\Admin;

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

class ReferralController extends Controller
{
  public function __construct()
    {
        $this->middleware('permission:view referrals', ['only' => ['index', 'show']]);
        $this->middleware('permission:create referrals', ['only' => ['create', 'store']]);
        $this->middleware('permission:update referrals', ['only' => ['edit', 'update']]);
        $this->middleware('permission:delete referrals', ['only' => ['destroy']]);
    }

    public function index()
    {
        $referrals = Referral::with(['referrer', 'referredUser'])->latest()->paginate(20);

        return view('admin.referrals.index', compact('referrals'));
    }

    public function create()
    {
        return redirect()->route('admin.referrals.index');
    }

    public function store(Request $request)
    {
        abort(405);
    }

    public function show(Referral $referral)
    {
        return redirect()->route('admin.referrals.edit', $referral);
    }

    public function edit(Referral $referral)
    {
        return view('admin.referrals.edit', compact('referral'));
    }

    public function update(Request $request, Referral $referral)
    {
        $data = $request->validate([
            'status' => ['required', 'in:pending,completed,cancelled'],
            'reward_amount' => ['nullable', 'numeric', 'min:0'],
        ]);

        $referral->update($data);

        return redirect()->route('admin.referrals.index')->with('status', 'Referral updated successfully.');
    }

    public function destroy(Referral $referral)
    {
        $referral->delete();

        return redirect()->route('admin.referrals.index')->with('status', 'Referral deleted.');
    }
}
