<?php


namespace App\Http\Controllers\backend;

use App\Http\Controllers\Controller;

use App\Models\BillerCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

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

        if ($s = $request->get('q')) {
            $q->where(function($w) use ($s){
                $w->where('name','like',"%{$s}%")
                  ->orWhere('slug','like',"%{$s}%");
            });
        }
        if ($st = $request->get('status')) {
            $q->where('status', $st);
        }

        $cats = $q->orderBy('sort_order')->orderBy('name')->paginate(12)->withQueryString();
        return view('backend.billers.categories.index', compact('cats'));
    }

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

    public function store(Request $request)
    {
        $data = $request->validate([
            'name'       => 'required|string|max:255',
            'slug'       => 'nullable|string|max:255|unique:biller_categories,slug',
            'icon'       => 'nullable|string|max:255', // emoji/text or external URL
            'icon_file'  => 'nullable|image|mimes:jpg,jpeg,png,webp,svg|max:2048',
            'status'     => 'required|in:active,inactive',
            'sort_order' => 'nullable|integer|min:0',
        ]);

        // auto slug if empty
        $data['slug'] = $data['slug'] ?: Str::slug($data['name']);
        $data['sort_order'] = $data['sort_order'] ?? 0;

        // file has priority
        if ($request->hasFile('icon_file')) {
            $data['icon'] = $request->file('icon_file')->store('uploads/billers', 'public'); // stored path
        }

        BillerCategory::create($data);
        return redirect(url('/admin/biller-categories'))->with('success', 'Category created.');
    }

    public function show($id)
    {
        $cat = BillerCategory::findOrFail($id);
        return view('backend.billers.categories.show', compact('cat'));
    }

    public function edit($id)
    {
        $cat = BillerCategory::findOrFail($id);
        return view('backend.billers.categories.edit', compact('cat'));
    }

    public function update(Request $request, $id)
    {
        $cat  = BillerCategory::findOrFail($id);

        $data = $request->validate([
            'name'       => 'required|string|max:255',
            'slug'       => 'nullable|string|max:255|unique:biller_categories,slug,'.$cat->id,
            'icon'       => 'nullable|string|max:255',
            'icon_file'  => 'nullable|image|mimes:jpg,jpeg,png,webp,svg|max:2048',
            'remove_icon'=> 'nullable|boolean',
            'status'     => 'required|in:active,inactive',
            'sort_order' => 'nullable|integer|min:0',
        ]);

        $data['slug'] = $data['slug'] ?: Str::slug($data['name']);
        $data['sort_order'] = $data['sort_order'] ?? 0;

        // remove old stored file if requested
        if ($request->boolean('remove_icon') && $cat->icon) {
            if (Storage::disk('public')->exists($cat->icon)) {
                Storage::disk('public')->delete($cat->icon);
            }
            $data['icon'] = null;
        }

        // new upload overrides text
        if ($request->hasFile('icon_file')) {
            $path = $request->file('icon_file')->store('uploads/billers','public');
            // delete previous if it was a stored file
            if ($cat->icon && Storage::disk('public')->exists($cat->icon)) {
                Storage::disk('public')->delete($cat->icon);
            }
            $data['icon'] = $path;
        }

        $cat->update($data);
        return redirect(url('/admin/biller-categories'))->with('success', 'Category updated.');
    }

    public function destroy($id)
    {
        $cat = BillerCategory::findOrFail($id);
        if ($cat->icon && Storage::disk('public')->exists($cat->icon)) {
            Storage::disk('public')->delete($cat->icon);
        }
        $cat->delete();
        return redirect(url('/admin/biller-categories'))->with('success', 'Category deleted.');
    }

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