<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Package;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class ResellerController extends Controller
{
    public function create()
    {
        $packages = Package::where('is_active', true)->orderBy('blogs_count')->get();
        return view('admin.resellers.create', compact('packages'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name'        => 'required|string|max:255',
            'username'    => 'required|alpha_dash|min:3|unique:users,username',
            'email'       => 'required|email|unique:users,email',
            'password'    => 'required|min:8',
            'blogs_quota' => 'required|integer|min:1',
        ]);

        User::create([
            'name'        => $data['name'],
            'username'    => $data['username'],
            'email'       => $data['email'],
            'password'    => Hash::make($data['password']),
            'role'        => 'reseller',
            'status'      => 'active',
            'blogs_quota' => $data['blogs_quota'],
            'blogs_used'  => 0,
        ]);

        return redirect()->route('admin.users.index', ['role' => 'reseller'])
            ->with('success', 'Reseller created with ' . $data['blogs_quota'] . ' blog quota.');
    }

    public function editQuota(User $user)
    {
        if (!$user->isReseller()) abort(404);
        return view('admin.resellers.quota', compact('user'));
    }

    public function updateQuota(Request $request, User $user)
    {
        if (!$user->isReseller()) abort(404);
        $data = $request->validate([
            'blogs_quota' => 'required|integer|min:0',
            'reason'      => 'nullable|string|max:255',
        ]);
        $user->update(['blogs_quota' => $data['blogs_quota']]);
        return back()->with('success', 'Quota updated.');
    }
}
