<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Category;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Validator;

class CategoryController extends Controller
{
    public function create()
    {
        return view('dashboard.categories.create');
    }

    // Store a new category
public function store(Request $request)
{
  
    // Validate the request
    $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'icon' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        if ($validator->fails()) {
            dd($validator->errors()->all()); // This will dump all validation errors
            // Or return back with errors (standard Laravel behavior)
            return redirect()->back()->withErrors($validator)->withInput();
        }

    try {
        $data = $request->only('name', 'description');
        
        // Handle icon upload
        if ($request->hasFile('icon')) {
            $publicPath = public_path();
            $iconsDir = $publicPath.'/uploads/category_icons';
            
            // Create directory if it doesn't exist
            if (!file_exists($iconsDir)) {
                mkdir($iconsDir, 0755, true);
            }
            
            // Upload icon
            $icon = $request->file('icon');
            $iconName = time().'_'.Str::slug($icon->getClientOriginalName());
            $icon->move($iconsDir, $iconName);
            $data['icon'] = '/uploads/category_icons/'.$iconName;
        }

        Category::create($data);

        return redirect()
            ->route('categories.index')
            ->with('success', 'Book category created successfully!');

    } catch (ValidationException $e) {
        // This will automatically return with validation errors
        throw $e;
        
    } catch (Exception $e) {
        return redirect()
            ->back()
            ->withInput()
            ->with('error', 'Error creating category: '.$e->getMessage());
    }
}
    // Display all categories
    public function index()
    {
        $categories = Category::all();
        return view('dashboard.categories.index', compact('categories'));
    }

    // Show edit form
    public function edit($id)
    {
        $category = Category::findOrFail($id);
        return view('dashboard.categories.edit', compact('category'));
    }

    // Update a category
    public function update(Request $request, $id)
    {
        // Validate the request
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'icon' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        try {
            $category = Category::findOrFail($id);
            $data = $request->only('name', 'description');
            
            // Handle icon upload
            if ($request->hasFile('icon')) {
                $publicPath = public_path();
                $iconsDir = $publicPath.'/uploads/category_icons';
                
                // Create directory if it doesn't exist
                if (!file_exists($iconsDir)) {
                    mkdir($iconsDir, 0755, true);
                }
                
                // Delete old icon if exists
                if ($category->icon && file_exists(public_path($category->icon))) {
                    unlink(public_path($category->icon));
                }
                
                // Upload new icon
                $icon = $request->file('icon');
                $iconName = time().'_'.Str::slug($icon->getClientOriginalName());
                $icon->move($iconsDir, $iconName);
                $data['icon'] = '/uploads/category_icons/'.$iconName;
            }

            $category->update($data);

            return redirect()
                ->route('categories.index')
                ->with('success', 'Book category updated successfully!');

        } catch (\Exception $e) {
            return redirect()
                ->back()
                ->withInput()
                ->with('error', 'Error updating category: '.$e->getMessage());
        }
    }

    // Delete a category
    public function destroy($id)
    {
        try {
            $category = Category::findOrFail($id);
            
            // Check if category has books
            if ($category->books()->count() > 0) {
                return redirect()
                    ->route('categories.index')
                    ->with('error', 'Cannot delete book category. It has associated books. Please remove or reassign books first.');
            }
            
            // Delete icon file if exists
            if ($category->icon && file_exists(public_path($category->icon))) {
                unlink(public_path($category->icon));
            }
            
            $category->delete();

            return redirect()
                ->route('categories.index')
                ->with('success', 'Book category deleted successfully!');

        } catch (\Exception $e) {
            return redirect()
                ->route('categories.index')
                ->with('error', 'Error deleting category: '.$e->getMessage());
        }
    }
}
