<?php

namespace App\Http\Controllers;

use App\Http\Requests\ItemCategory\StoreItemCategoryRequest;
use App\Http\Requests\ItemCategory\UpdateItemCategoryRequest;
use App\Models\Business;
use App\Models\ItemCategory;
use App\Traits\LogsActivity;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class ItemCategoryController extends Controller
{
	use LogsActivity;
    public function index(Request $request)
    {
        if($request->ajax()) {

        $query = ItemCategory::query()->with('parent')->select('item_categories.*');

        // Filters
        if ($request->filled('parent_id')) {
            $query->where('parent_category_id', $request->string('parent_id'));
        }
        if ($request->filled('date_from') && $request->filled('date_to')) {
            $query->whereBetween('created_at', [$request->string('date_from').' 00:00:00', $request->string('date_to').' 23:59:59']);
        }

        return DataTables::of($query)
            ->addColumn('parent_name', function (ItemCategory $category) {
                return optional($category->parent)->name ?: '-';
            })
            ->editColumn('created_at', function (ItemCategory $category) {
                $business = Business::first();
                $business->timezone;
                return $category->created_at->setTimezone('Asia/Karachi')->format('Y-m-d H:i:s');
            })
            ->addColumn('status_badge', function (ItemCategory $category) {
                $badgeClass = match($category->status) {
                    'active' => 'success',
                    'inactive' => 'secondary',
                    'draft' => 'warning',
                    'archived' => 'dark',
                    default => 'secondary'
                };
                return '<span class="badge bg-'.$badgeClass.'">'.ucfirst($category->status).'</span>';
            })
            ->addColumn('actions', function (ItemCategory $category) {
                $editUrl = route('item-categories.edit', $category);
                $deleteUrl = route('item-categories.destroy', $category);
                $toggleUrl = route('item-categories.toggle-status', $category);
                $csrf = csrf_field();
                $method = method_field('DELETE');
                $toggleMethod = method_field('PATCH');

                $actions = '<div class="d-flex gap-2">';
                $actions .= '<a href="'.$editUrl.'" class="btn btn-sm btn-outline-primary">Edit</a>';

                // Toggle status button
                $toggleText = $category->status === 'active' ? 'Deactivate' : 'Activate';
                $toggleClass = $category->status === 'active' ? 'warning' : 'success';
                $actions .= '<form action="'.$toggleUrl.'" method="POST" style="display:inline;">';
                $actions .= $csrf.$toggleMethod.'<button type="submit" class="btn btn-sm btn-outline-'.$toggleClass.'">'.$toggleText.'</button></form>';

                // Delete button (only if no items linked)
                if ($category->items()->count() === 0) {
                    $actions .= '<form action="'.$deleteUrl.'" method="POST" onsubmit="return confirm(\'Delete this category?\')" style="display:inline;">';
                    $actions .= $csrf.$method.'<button type="submit" class="btn btn-sm btn-outline-danger">Delete</button></form>';
                }

                $actions .= '</div>';
                return $actions;
            })
            ->rawColumns(['status_badge', 'actions'])
            ->toJson();

        }

        return view('item_categories.index');
    }


    public function create(): View
    {
        $categories = ItemCategory::query()->orderBy('name')->pluck('name', 'id');
        return view('item_categories.create', compact('categories'));
    }

    public function store(StoreItemCategoryRequest $request): RedirectResponse
    {
        try {
            DB::transaction(function () use ($request) {
                ItemCategory::create($request->validated());
            });
            return redirect()->route('item-categories.index')->with('success', 'Category created successfully.');
        } catch (\Throwable $e) {
            report($e);
            return back()->withInput()->withErrors(['error' => 'Failed to create category.']);
        }
    }

    public function edit(ItemCategory $item_category): View
    {
        $categories = ItemCategory::query()
            ->where('id', '!=', $item_category->id)
            ->orderBy('name')
            ->pluck('name', 'id');

        return view('item_categories.edit', [
            'itemCategory' => $item_category,
            'categories' => $categories,
        ]);
    }

    public function update(UpdateItemCategoryRequest $request, ItemCategory $item_category): RedirectResponse
    {
        try {
            // If category has items, only allow soft fields (none for now), otherwise block
            if ($item_category->items()->exists()) {
                throw ValidationException::withMessages([
                    'error' => 'This Category has linked items and cannot be edited.'
                ]);
            }
            DB::transaction(function () use ($request, $item_category) {
                $item_category->update($request->validated());
            });
            return redirect()->route('item-categories.index')->with('success', 'Category updated successfully.');
        } catch (ValidationException $e) {
            throw $e;
        } catch (\Throwable $e) {
            report($e);
            return back()->withInput()->withErrors(['error' => 'Failed to update category.']);
        }
    }

    public function destroy(ItemCategory $item_category): RedirectResponse
    {
        try {
            if ($item_category->items()->exists()) {
                throw ValidationException::withMessages([
                    'error' => 'This Category has linked items and cannot be deleted.'
                ]);
            }
            if (!$item_category->canDelete()) {
                return back()->withErrors(['error' => 'This Category cannot be deleted. Use deactivation instead.']);
            }
            DB::transaction(function () use ($item_category) {
                $item_category->delete();
            });
            return redirect()->route('item-categories.index')->with('success', 'Category deleted successfully.');
        } catch (ValidationException $e) {
            throw $e;
        } catch (\Throwable $e) {
            report($e);
            return back()->withErrors(['error' => 'Failed to delete category.']);
        }
    }

    public function toggleStatus(ItemCategory $item_category): RedirectResponse
    {
        try {
            $nextStatus = $item_category->status === 'active' ? 'inactive' : 'active';
            DB::transaction(function () use ($item_category, $nextStatus) {
                $item_category->update(['status' => $nextStatus]);
            });
            return back()->with('success', 'Category status updated to '.$nextStatus.'.');
        } catch (\Throwable $e) {
            report($e);
            return back()->withErrors(['error' => 'Failed to toggle status.']);
        }
    }

    public function search(Request $request)
	{
		$q = (string) $request->get('q', '');
		$vendors = ItemCategory::query()
        ->when($q !== '', function($query) use ($q){
            $query->where(function($sub) use ($q){
					$sub->where('name', 'like', "%{$q}%");
				});
			})
			->orderBy('name')
			->limit(20)
			->get(['id','name']);

		return response()->json([
			'results' => $vendors->map(fn($v) => ['id' => $v->id, 'text' => $v->name]),
		]);
	}
}
