<?php

namespace App\Http\Controllers\Product;

use App\Http\Controllers\Controller;
use App\Models\MenuModelPermission;
use App\Models\Product;
use App\Models\ProductFeature;
use Illuminate\Http\Request;

class ProductFeaturesController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:product-feature-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        // $data = ProductFeature::select([
        //     'product_features.id',
        //     'product_features.product_code',
        //     'product_features.module_code',
        //     'product_features.details',
        //     'product_features.status'
        // ])
        $data = Product::select([
            'id',
            'name',
            'brand_id',
            'category_id',
        ])
            ->with('getProductBrand')
            ->with('getProductCategory')
            ->with('getProductGroup')
            ->paginate(10);

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

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

            return view('product-features.table', compact('data'));
        } else {
            return view('product-features.index', compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $module_code = MenuModelPermission::select('id', 'code')->get();
        $product_code = Product::select('id', 'shortcode')->get();
        return view('product-features.create', compact('module_code', 'product_code'));
    }

    /**
     * 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(), [
            // 'product_code' => 'required'
        ]);

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

        foreach ($request->module_code as $key => $value) {
            $data = [
                'module_code' => $value,
                'product_code' => $request->product_code
            ];

            ProductFeature::firstOrcreate($data);
        }

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Test packages linked successfully',
            ]);
        }
        return redirect()->back()
            ->with('success', 'Test packages linked successfully');
    }

    public function addAllModules(Request $request)
    {
        if (isset($request->code) && $request->code != '') {
            ProductFeature::where('product_code', $request->code)->delete();

            $module_code = MenuModelPermission::select('id', 'code')->get();
            foreach ($module_code as $key => $record) {
                $data = [
                    'module_code'  => $record->id,
                    'product_code' => $request->code,
                    'status'       => '0'
                ];

                ProductFeature::create($data);
            }

            return response()->json(['status' => 'success']);
        }
    }

    /**
     * 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)
    {
        $module_code = MenuModelPermission::select('id', 'menu_name')->get();
        $product_code = Product::select('id', 'shortcode')->get();
        $product_features = ProductFeature::find($id);

        return view('product-features.edit', compact('product_features', 'product_code', 'module_code'));
    }

    /**
     * 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(), [
            'module_code' => 'required',
            'product_code' => 'required',
        ]);

        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'
        ]);

        $source = ProductFeature::find($id);

        if (!$source) {
            return redirect()->route('product-features.index')
                ->with('error', 'Product Features not found!');
        }

        $source->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Product Features updated successfully',
                'data' => $source
            ]);
        }

        return redirect()->route('product-features.index')
            ->with('success', 'Product Features updated successfully');
    }

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

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

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

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Product Features status successfully change'],
                    'data' => [
                        'redirect' => '/users/',
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }

    public function changedefault(Request $request)
    {
        if ($request->ajax()) {
            $data = array('is_default' => $request->status);
            $count = ProductFeature::where(['is_default' => $request->status])->count();

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default Product Features!'],
                    'data' => []
                ]);
            }

            $Update = ProductFeature::where('id', '=', $request->id)->update($data);

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Product Features default status successfully changed.'],
                    'data' => [
                        'redirect' => '/users/',
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change default'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }
    public function productFeatureModule(Request $request, $id, $code = '')
    {
        $data = ProductFeature::select([
            'id',
            'product_code',
            'module_code',
            'details',
            'status'
        ])
            ->where('product_code', $code)
            ->with('getModuleCode')
            ->with('getProductCode')
            ->paginate(10);

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

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

            return view('product-feature-modules.table', compact('data'));
        } else {

            return view('product-feature-modules.index', compact('data', 'id'));
        }
    }
    public function productFeatureModuleCreate(Request $request, $id)
    {
        $module = MenuModelPermission::select('id', 'menu_name')->get();

        return view('product-feature-modules.create', compact('module', 'id'));
    }
    public function getSelectedProductFeatureModule(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;
        }
    }
}
