<?php

namespace App\Http\Controllers\LicenseManagement;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\IndustryType;
use App\Models\MenuModelPermission;
use App\Models\PlaneAndPackages;
use App\Models\PlanModuleMapping;
use App\Models\PlanProductMapping;
use App\Models\Product;

class PlanAndPackageContoller extends Controller
{
    function __construct()
    {
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = PlaneAndPackages::select(
            'id',
            'plan_name',
            'industry_type_id',
            'plan_code',
            'features_details',
            'status',
        )->with('industryType');

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('plan_name', 'like', '%'.$search_query.'%');
            })
            ->orderBy('id','ASC')
            ->groupBy('id')
            ->paginate($sort_by);

            return view('plan-and-packages.table', compact('data'));
        } else {
            $data = $data->groupBy('id')
                ->orderBy('id','ASC')
                ->paginate(10);

            return view('plan-and-packages.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $industry = IndustryType::select('id','name')->where('status',1)->get();
        return view('plan-and-packages.create',compact('industry'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'plan_name'        => 'required|max:64',
            'industry_type_id' => 'required',
            'plan_code'        => 'required|unique:plane_and_packages',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except(['_token']);

        $data = PlaneAndPackages::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Plan and Package created successfully',
                'data'    => $data
            ]);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = PlaneAndPackages::find($id);
        $industry = IndustryType::select('id','name')->get();

        return view('plan-and-packages.edit', compact('data','industry'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'plan_name'        => 'required|max:64',
            'industry_type_id' => 'required|integer',
            'plan_code'        => 'required|unique:plane_and_packages,plan_code,' . $id . ',id',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except(['_token', '_method']);

        $data['status'] = isset($request->status) && $request->status == 'on' ? 1 : 0;
        $data = PlaneAndPackages::whereId($id)->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Plan And Packages updated successfully',
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        PlanProductMapping::where('plan_id', $request->id)->delete();
        PlanModuleMapping::where('plan_id', $request->id)->delete();
        PlaneAndPackages::find($request->id)->delete();

        return response()->json([
            'success' => true,
            'message' => ['Plan And Packages Deleted successfully'],
        ]);
    }

    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('status' => $request->status);
            $Update = PlaneAndPackages::where('id', '=', $request->id)->update($data);

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Plan and packages status successfully change'],
                    'data' => [
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                    ]
                ]);
            }
        }
    }

    public function planModuleMapping(Request $request, $id, $code = '')
    {
        $plan = PlaneAndPackages::find($id);

        if (!$plan) {
            return redirect()->route('plan-and-packages.index')->with('error', "Plan and package not found!");
        }

        $mapped_modules = PlanModuleMapping::select('module_code')->where(['plan_id'=> $id])
            ->where('module_code','<>', null)
            ->get();

        $mapped_modules = $mapped_modules->pluck('module_code')->mapWithKeys(function ($module) {
            return [$module => $module];
        })->toArray();

        $data = MenuModelPermission::select('id', 'menu_name', 'code')
            ->where('parent_id', null);

        if ($request->ajax()) {
            $sort_by = $request->get('sortby') ?? 10;
            $sort_type = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('menu_name', 'like', '%' . $search_query . '%');
            })
            ->paginate($sort_by);

            return view('plan-module-mapping.table', compact('data', 'id', 'mapped_modules'));
        } else {
            $data = $data->paginate(10);

            return view('plan-module-mapping.index', compact('data', 'id', 'mapped_modules', 'plan'));
        }
    }
    public function planModuleMappingCreate(Request $request, $id)
    {
        $query = PlanModuleMapping::where(['plan_id'=> $id])->where('module_code','<>', null)->get()->pluck('module_code');

        $module = MenuModelPermission::select('id', 'menu_name')->whereNotIn('code', $query)->get();

        return view('plan-module-mapping.create', compact('module'));
    }
    public function getSelectedModules(Request $request)
    {
        if (isset($request->id) && !empty($request->id)) {
            $menuModule = MenuModelPermission::select(['id', 'menu_name'])->whereIn('id', $request->id)->get();

            $sno = 1;
            $row = '';
            foreach ($menuModule as $module) {

                $row .= '
                <tr>
                    <td>' . $sno++ . '</td>
                    <td>' . ucfirst($module->menu_name) . '</td>
                    <td>
                        <a class="remove-btn itme_id btn-sm btn-danger" data-value="' . $module->id . '">
                        <i class="bi bi-trash-fill text-white"></i></a>
                    </td>
                </tr>';
            }

            return $row;
        }
    }
    public function storeSelectedModules(Request $request, $id)
    {
        $modules = $request->module_code ?? [];

        if (count($modules) < 1) {
            return response()->json([
                'success' => false,
                'message' => 'No Modules Selected! Please select modules to map.'
            ]);
        }

        $priority = PlanModuleMapping::max('priority');
        $priority = $priority != '' ? $priority : 0;

        foreach($modules as $key => $value) {
            $module = MenuModelPermission::with('parentModule')->find($value);

            $data = PlanModuleMapping::firstOrCreate([
                'plan_id'            => $id,
                'module_code'        => $module->code,
                'parent_module_code' => ($module->parentModule->code ??  null),
            ],[
                'priority'           => ($priority + 1 + $key)
            ]);
        }

        return response()->json([
            'success' => true,
            'message' => 'Modules mapped with this plan successfully.'
        ]);
    }

    public function changeStatusPlanModuleMapping(Request $request)
    {
        if ($request->ajax()) {
            if ($request->status == '1') {
                $modules = MenuModelPermission::select('menu_model_permissios.code')
                    ->leftjoin('menu_model_permissios as parent_model', 'parent_model.id', 'menu_model_permissios.parent_id')
                    ->where('parent_model.code', $request->module)
                    ->orWhere('menu_model_permissios.code', $request->module)
                    ->get();

                foreach ($modules as $key => $value) {
                    PlanModuleMapping::create([
                        'plan_id'     => $request->id,
                        'module_code' => $value->code,
                        'status'      => '1',
                    ]);
                }

            } else {
                PlanModuleMapping::where([
                    'plan_id'     => $request->id,
                    'module_code' => $request->module,
                ])->delete();
            }

            return response()->json([
                'success' => true,
                'message' => ['Plan and module mapping successfully updated'],
                'data' => [
                ]
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function removePlanModuleMapping(Request $request)
    {
        PlanModuleMapping::find($request->id)->delete();

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
        ]);
    }

    /**
     * Product Mapping
     */

    public function planProductMapping(Request $request, $id, $code = '')
    {
        $plan = PlaneAndPackages::find($id);

        if (!$plan) {
            return redirect()->route('plan-and-packages.index')->with('error', "Plan and package not found!");
        }

        $data = PlanProductMapping::select([
            'id',
            'plan_id',
            'product_id',
            'priority',
            'status'
        ])
        ->with('product')
        ->where('plan_id', $id)
        ->where('product_id', '<>', null);

        if ($request->ajax()) {
            $sort_by = $request->get('sortby') ?? 10;
            $sort_type = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->whereHas('product', function ($q) use ($search_query) {
                    $q->where('name', 'like', '%' . $search_query . '%');
                });
            })
            ->paginate($sort_by);

            return view('plan-product-mapping.table', compact('data'));
        } else {
            $data = $data->paginate(10);

            return view('plan-product-mapping.index', compact('data', 'id'));
        }
    }
    public function planProductMappingCreate(Request $request, $id)
    {
        $modules = PlanProductMapping::where(['plan_id' => $id])->where('product_id', '<>', null)->get()->pluck('product_id');

        $products = Product::select('id', 'name')->whereNotIn('id', $modules)->get();

        return view('plan-product-mapping.create', compact('products'));
    }
    public function getSelectedProducts(Request $request)
    {
        if (isset($request->id) && !empty($request->id)) {
            $products = Product::select(['id', 'name'])->whereIn('id', $request->id)->get();

            $sno = 1;
            $row = '';
            foreach ($products as $product) {

                $row .= '
                <tr>
                    <td>' . $sno++ . '</td>
                    <td>' . ucfirst($product->name) . '</td>
                    <td>
                        <a class="remove-btn itme_id btn-sm btn-danger" data-value="' . $product->id . '">
                        <i class="bi bi-trash-fill text-white"></i></a>
                    </td>
                </tr>';
            }

            return $row;
        }
    }
    public function storeSelectedProducts(Request $request, $id)
    {
        $products = $request->product_id ?? [];

        if (count($products) < 1) {
            return response()->json([
                'success' => false,
                'message' => 'No Products Selected! Please select modules to map.'
            ]);
        }

        $priority = PlanProductMapping::max('priority');
        $priority = $priority != '' ? $priority : 0;

        foreach($products as $key => $value) {
            $data = PlanProductMapping::firstOrCreate([
                'plan_id'            => $id,
                'product_id'        => $value,
            ],[
                'priority'           => ($priority + 1 + $key)
            ]);
        }

        return response()->json([
            'success' => true,
            'message' => 'Products mapped with this plan successfully.'
        ]);
    }

    public function changeStatusPlanProductMapping(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('status' => $request->status);
            $Update = PlanProductMapping::where('id', '=', $request->id)->update($data);

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Plan and product mapping status successfully change'],
                    'data' => [
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                    ]
                ]);
            }
        }
    }

    public function removePlanProductMapping(Request $request)
    {
        PlanProductMapping::find($request->id)->delete();

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
        ]);
    }

    public function planChildModuleMapping(Request $request, $id, $parent_id)
    {
        $plan = PlaneAndPackages::find($id);

        if (!$plan) {
            return redirect()->route('plan-and-packages.index')->with('error', "Plan and package not found!");
        }

        $mapped_modules = PlanModuleMapping::select('module_code')->where(['plan_id'=> $id])
            ->where('module_code','<>', null)
            ->get();

        $mapped_modules = $mapped_modules->pluck('module_code')->mapWithKeys(function ($module) {
            return [$module => $module];
        })->toArray();

        $parent = MenuModelPermission::select('id', 'menu_name', 'code')
            ->find($parent_id);

        $data = MenuModelPermission::select('id', 'menu_name', 'code')
            ->where('parent_id', $parent_id);

        if ($request->ajax()) {
            $sort_by = $request->get('sortby') ?? 10;
            $sort_type = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('menu_name', 'like', '%' . $search_query . '%');
            })
            ->paginate($sort_by);

            return view('plan-module-mapping.child-table', compact('data', 'id', 'parent_id', 'mapped_modules'));
        } else {
            $data = $data->paginate(10);

            return view('plan-module-mapping.child-index', compact('data', 'id', 'parent_id', 'mapped_modules', 'plan', 'parent'));
        }
    }
}
