<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use App\Models\SubCategory;
use App\Models\Category;
use Yajra\DataTables\Facades\DataTables;

class SubCategoryController extends Controller
{
    public function addSubCategory(Request $request)
    {
        $request->validate([
            'category_id' => 'required|exists:categories,id',
            'name'        => 'required|string|max:255',
            'photo'       => 'nullable|image|mimes:jpg,jpeg,png,webp|max:4096',
        ]);

        $slug = Str::slug($request->name);
        $imagePath = null;

        if ($request->hasFile('photo')) {
            $image = $request->photo;
            $imageName = time() . '-' . rand(100,999) . '.' . $image->extension();
            $uploadPath = public_path('assets/upload/subcategory/');
            if (!File::exists($uploadPath)) File::makeDirectory($uploadPath, 0755, true);
            $image->move($uploadPath, $imageName);
            $imagePath = 'assets/upload/subcategory/' . $imageName;
        }

        SubCategory::create([
            'category_id' => $request->category_id,
            'name'        => ucfirst($request->name),
            'slug'        => $slug,
            'image'       => $imagePath,
            'is_active'   => 1,
        ]);

        return response()->json(['success' => 'Sub Category added successfully!']);
    }

    public function getSubCategory()
    {
        $subcats = SubCategory::with('category')->orderBy('id', 'DESC')->get();

        return DataTables::of($subcats)
            ->addIndexColumn()
            ->addColumn('category', fn($data) => $data->category?->name)
            ->addColumn('image', fn($data) => $data->image ? '<img src="'.asset($data->image).'" class="avatar-md rounded">' : '-')
            ->addColumn('status', function($data){
                $checked = $data->is_active ? 'checked' : '';
                return '
                    <div class="form-check form-switch">
                        <input class="form-check-input toggleStatus" data-id="'.$data->id.'" type="checkbox" '.$checked.'>
                    </div>';
            })
            ->addColumn('action', function ($row) {
                return '
                    <button class="btn btn-sm btn-primary editSubCategory" data-id="'.$row->id.'" data-name="'.$row->name.'" data-category="'.$row->category_id.'">Edit</button>
                    <button class="btn btn-sm btn-danger deleteSubCategory" data-id="'.$row->id.'">Delete</button>';
            })
            ->escapeColumns([])
            ->make(true);
    }

    public function update(Request $request, $id)
    {
        $subcategory = SubCategory::findOrFail($id);

        $request->validate([
            'name' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'photo' => 'nullable|image|mimes:jpg,jpeg,png,webp|max:4096',
        ]);

        $imagePath = $subcategory->image;
        if ($request->hasFile('photo')) {
            if ($imagePath && File::exists(public_path($imagePath))) {
                File::delete(public_path($imagePath));
            }
            $image = $request->photo;
            $imageName = time() . '-' . rand(100,999) . '.' . $image->extension();
            $uploadPath = public_path('assets/upload/subcategory/');
            if (!File::exists($uploadPath)) File::makeDirectory($uploadPath, 0755, true);
            $image->move($uploadPath, $imageName);
            $imagePath = 'assets/upload/subcategory/' . $imageName;
        }

        $subcategory->update([
            'name' => ucfirst($request->name),
            'slug' => Str::slug($request->name),
            'category_id' => $request->category_id,
            'image' => $imagePath,
        ]);

        return response()->json(['success' => 'Sub Category updated successfully!']);
    }

    public function destroy($id)
    {
        $subcat = SubCategory::findOrFail($id);
        if ($subcat->image && File::exists(public_path($subcat->image))) {
            File::delete(public_path($subcat->image));
        }
        $subcat->delete();
        return response()->json(['success' => 'Sub Category deleted successfully.']);
    }

    public function toggleStatus($id)
    {
        $subcat = SubCategory::findOrFail($id);
        $subcat->is_active = !$subcat->is_active;
        $subcat->save();

        return response()->json(['success' => 'Status updated successfully!']);
    }
}
