<?php

namespace App\Http\Controllers;

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

class CategoryController extends Controller
{
    public function addcategory(Request $request)
    {
        // Validate inputs
        $request->validate([
            'name'       => 'required|string|max:255',
            'country'    => 'required|array',           // Accept multiple countries
            'country.*'  => 'exists:countries,id',
            'photo'      => 'nullable|image|mimes:jpg,jpeg,png|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/category/');

            if (!File::exists($uploadPath)) {
                File::makeDirectory($uploadPath, 0755, true);
            }

            $image->move($uploadPath, $imageName);
            $imagePath = 'assets/upload/category/' . $imageName;
        }

        // Create category
        $category = Category::create([
            'name'  => ucfirst($request->name),
            'slug'  => $slug,
            'image' => $imagePath,
        ]);

        // Attach multiple countries
        $category->countries()->attach($request->country);

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


    public function getCategory()
    {
        $categories = Category::with('countries')->orderBy('id', 'DESC')->get();

        return DataTables::of($categories)
            ->addIndexColumn()
            ->addColumn('name', fn($data) => $data->name)
            ->addColumn('country', function ($data) {
                return $data->countries->pluck('name')->implode(', '); // Multiple countries
            })
            ->addColumn('image', function ($data) {
                return '<img src="' . asset($data->image) . '" class="avatar-md">';
            })
            ->addColumn('action', function ($row) {
                return '<a href="" class="btn btn-sm btn-purple editcategory" data-id="' . $row->id . '">Edit</a>
                    <a href="" class="btn btn-sm btn-danger deletecategory" data-id="' . $row->id . '">Delete</a>';
            })
            ->escapeColumns([])
            ->make(true);
    }


    // Delete category (AJAX)
    public function destroy($id)
    {
        $category = Category::findOrFail($id);

        // Delete image from folder if exists
        if ($category->image && File::exists(public_path($category->image))) {
            File::delete(public_path($category->image));
        }

        $category->delete();
        return response()->json(['success' => 'Category deleted successfully.']);
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'name'       => 'required|string|max:100',
            'country'    => 'required|array',
            'country.*'  => 'exists:countries,id',
            'photo'      => 'nullable|image|mimes:jpg,jpeg,png|max:4096',
        ]);

        $category = Category::findOrFail($id);
        $slug = Str::slug($request->name);

        // Image upload
        if ($request->hasFile('photo')) {
            $image = $request->file('photo');
            $imageName = time() . '-' . rand(100, 999) . '.' . $image->extension();
            $uploadPath = public_path('assets/upload/category/');

            if (!File::exists($uploadPath)) {
                File::makeDirectory($uploadPath, 0755, true);
            }

            $image->move($uploadPath, $imageName);
            $category->image = 'assets/upload/category/' . $imageName;
        }

        // Update category
        $category->update([
            'name' => ucfirst($request->name),
            'slug' => $slug,
        ]);

        // Sync multiple selected countries
        $category->countries()->sync($request->country);

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