<?php

namespace App\Http\Controllers\Admin;

use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use App\Http\Controllers\Controller;

class CategoryController extends Controller
{
    // ...

    public function index()
    {
        $categories = Category::latest()->paginate(10);
        $randomNumber = $this->generateRandomNumber(); // Generate the random number
        if (request()->ajax()) {
            return view('admin.categories.list', compact('categories', 'randomNumber'));
        }

        return view('admin.categories.index', compact('categories', 'randomNumber'));
    }
    public function generateRandomNumber()
    {   
        $randomNumber = 'CAT' . str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
        return $randomNumber;
    }

    public function store(Request $request)
    {
        $category = new Category();

        // Set category attributes based on the request
        $category->category_code = $request->input('category_code');
        $category->category_name = $request->input('category_name');

        // Process and store the uploaded image
        if ($request->hasFile('image')) {
            $image = $request->file('image');
            $imagePath = $this->uploadImage($image);
            $category->image = $imagePath;
        }

        $category->save();

        if (request()->ajax()) {
            $categories = Category::paginate(10);
            return view('admin.categories.list', compact('categories'));
        }

        return redirect()->route('admin.categories.index')->with('success', 'Category added successfully.');

    }
    private function uploadImage($image)
    {
        $filename = time() . '.' . $image->getClientOriginalExtension();
        $image->move(public_path('category_images'), $filename);
        return 'category_images/' . $filename;
    }

    public function destroy(Category $category)
    {
        $category->delete();

        return redirect()->route('admin.categories.index')->with('success', 'Category deleted successfully.');
    }



}
