<?php

namespace App\Http\Controllers;

use App\Models\Menu;
use App\Models\MenuGroup;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class LoginController extends Controller
{
    public function index()
    {
        return view('admin.login');
    }

    public function login(Request $request)
    {
        $request->validate([
            'phone'    => 'required|regex:/^\+?[0-9]{10,15}$/',
            'password' => 'required'
        ]);

        $user = User::where('phone', $request->phone)->where('status', 1)->first();
        if (!$user || ! $user->password) {
            return apiResponse('error','invalid credentials','');

        }
        Auth::login($user);

        $menuGroup = MenuGroup::find($user->menu_grp);
        $menuIds = [];
        if ($menuGroup && $menuGroup->menu_name)
        {
            $menuIds = json_decode($menuGroup->menu_name, true); // returns array

        }

        $nestedMenus = $this->buildNestedMenus($menuIds);

        // Get landing URL
        $redirectUrl = $this->getLandingUrl($nestedMenus);


        Session::put('user_id',$user->id);
        Session::put('user_name',$user->name);
        Session::put('user_menus', $nestedMenus);
        Session::put('user_district', $user->district);

        if ($redirectUrl) {
            return apiResponse('success','successfully',['url' => $redirectUrl]);
        } else {
            return apiResponse('error',"You don't have enough permission to login.","",'');

        }
    }

    public function buildNestedMenus(array $ids)
    {
        // Step 1: fetch menus + parents recursively
        $allMenus = collect();
        $menus = Menu::whereIn('id', $ids)->get();
        $allMenus = $allMenus->merge($menus);

        $parentIds = $menus->pluck('parent_id')->filter()->unique();

        while ($parentIds->isNotEmpty()) {
            $parents = Menu::whereIn('id', $parentIds)->get();
            $allMenus = $allMenus->merge($parents);
            $parentIds = $parents->pluck('parent_id')->filter()->unique();
        }

        // Remove duplicates and sort
        $allMenus = $allMenus->unique('id')->sortBy('sort_order')->values();

        // Step 2: build nested structure
        $nested = $allMenus->where('parent_id', 0)->values();

        foreach ($nested as $parent) {
            $children = $allMenus->where('parent_id', $parent->id)->sortBy('sort_order')->values();
            $parent->children = $children; // attach children
        }

        return $nested;
    }



    public function getLandingUrl($menus, $default = 'dashboard.index')
    {
        foreach ($menus as $menu) {
            // If menu has a valid route
            if (!empty($menu->route) && $menu->route !== '#') {
                return route($menu->route);
            }

            // Check children
            if ($menu->children->isNotEmpty()) {
                $child = $menu->children->first(function ($child) {
                    return !empty($child->route) && $child->route !== '#';
                });

                if ($child) {
                    return route($child->route);
                }
            }
        }

        return route($default);
    }

    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->flush();

        return redirect()->to('/');
    }
}
