<?php

namespace App\Http\Controllers\Admin\Units;

use App\Http\Controllers\Controller;
use App\Http\Requests\Unit\UnitStoreRequest;
use App\Http\Requests\Unit\UnitUpdateRequest;
use App\Models\productAttribute;
use App\Models\Units;
use App\Service\Units\UnitService;
use Illuminate\Http\Request;
use Inertia\Inertia;

class UnitsController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {

        return Inertia::render('Units/Unit');
    }

    public function view(Request $request)
    {
        // Check if pagination is requested (ServerSideDataTable)
        $isPaginationRequest = $request->filled('page') || $request->filled('perPage') || $request->filled('search');

        if ($isPaginationRequest) {
            $page = (int) $request->get('page', 1);
            $perPage = (int) $request->get('perPage', 10);
            $search = (string) $request->get('search', '');

            $allUnits = Units::with('Parent')
                ->when($search !== '', function ($q) use ($search) {
                    $q->where(function ($sub) use ($search) {
                        $sub->where('name', 'LIKE', "%{$search}%")
                            ->orWhere('short_name', 'LIKE', "%{$search}%")
                            ->orWhere('base_unit', 'LIKE', "%{$search}%");
                    });
                })
                ->orderByDesc('id')
                ->get();

            // If searching, include parents of matching children
            if ($search !== '') {
                $matchingChildParentIds = $allUnits->whereNotNull('parent_id')->pluck('parent_id')->unique()->values();
                if ($matchingChildParentIds->count() > 0) {
                    $parents = Units::with('Parent')
                        ->whereIn('id', $matchingChildParentIds)
                        ->orderByDesc('id')
                        ->get();
                    $allUnits = $allUnits->concat($parents)->unique('id')->values();
                }
            }

            // Build hierarchical list: parent then children (both ordered by id desc)
            $hierarchical = [];
            $parents = $allUnits->whereNull('parent_id')->sortByDesc('id');

            foreach ($parents as $parent) {
                $hierarchical[] = $parent;
                $children = $allUnits->where('parent_id', $parent->id)->sortByDesc('id');
                foreach ($children as $child) {
                    $hierarchical[] = $child;
                }
            }

            // Orphan children (if parent missing in dataset), append at end
            $orphanChildren = $allUnits
                ->whereNotNull('parent_id')
                ->filter(function ($child) use ($parents) {
                    return ! $parents->contains('id', $child->parent_id);
                })
                ->sortByDesc('id');
            foreach ($orphanChildren as $child) {
                $hierarchical[] = $child;
            }

            // Manual pagination over the hierarchical list
            $total = count($hierarchical);
            $offset = max(0, ($page - 1) * $perPage);
            $paginated = array_slice($hierarchical, $offset, $perPage);

            return response()->json([
                'data' => $paginated,
                'total' => $total,
            ]);
        }

        // Non-pagination request: return parent dropdown data
        $parent = Units::whereNull('parent_id')->orderByDesc('id')->get();

        return response()->json(['parent' => $parent]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(UnitStoreRequest $request)
    {

        UnitService::UnitCreate(request()->all());

        return response()->json(['success' => 'Units create successfully', 'all' => Units::orderByDesc('id')->with('Parent')->get(), 'parent' => Units::whereNull('parent_id')->orderByDesc('id')->get()]);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UnitUpdateRequest $request, string $id)
    {

        UnitService::UnitUpdate(request()->all(), $id);

        return response()->json(['success' => 'Unit Update successfully', 'all' => Units::orderByDesc('id')->with('Parent')->get(), 'parent' => Units::whereNull('parent_id')->orderByDesc('id')->get()]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        // Find the category by ID

        $unite = Units::findOrFail($id);
        $parent = Units::where('parent_id', $id)->first();

        $attr = productAttribute::where('unit_id', $unite->id)->first();
        if ($parent) {
            return response()->json(['error' => 'This Unit have a child'], 422);
        } elseif ($attr) {
            return response()->json(['error' => 'This Unit already use'], 422);
        }

        // Delete the category
        $unite->delete();

        return response()->json(['success' => 'Unite Delete successfully', 'all' => Units::orderByDesc('id')->with('Parent')->get(), 'parent' => Units::whereNull('parent_id')->orderByDesc('id')->get()]);
    }
}
