<?php

namespace Modules\Product\Http\Controllers;

use App\Functions\Upload;
use App\Http\Controllers\BasicController;
use Illuminate\Http\Request;
use Modules\Category\Entities\Model as Category;
use Modules\Product\Entities\Model;
use Modules\Product\Entities\ModelReview;
use Yajra\DataTables\DataTables;

class WebController extends BasicController
{
    public function index(Request $request)
    {
        return view('product::index');
    }

    public function datatable(Request $request)
    {
        $query = Model::query()
            ->with('Images', 'Rates')
            ->when(request()->sort_column && request()->sort_direction, function ($query) {
                return $query->orderBy(request()->sort_column, request()->sort_direction);
            });

        return DataTables::of($query)
            ->addColumn('actions', function ($Model) {
                return view('product::layouts.actions', ['Model' => $Model]);
            })
            ->editColumn('title_ar', function ($Model) {
                return view('product::layouts.title_ar', ['Model' => $Model]);
            })
            ->editColumn('title_en', function ($Model) {
                return view('product::layouts.title_en', ['Model' => $Model]);
            })
            ->addColumn('status', function ($Model) {
                return view('product::layouts.status', ['Model' => $Model]);
            })
            ->addColumn('image', function ($Model) {
                return view('product::layouts.image', ['Model' => $Model]);
            })
            ->addIndexColumn()
            ->rawColumns(['status', 'actions'])
            ->make(true);
    }

    public function create()
    {
        $Categories = $this->renderCategoryOptions();

        return view('product::create', compact('Categories'));
    }

    public function store(Request $request)
    {

        $Model = Model::create($request->only('code', 'price' , 'weight' ,'pre_order', 'title_ar', 'title_en', 'desc_ar', 'desc_en', 'quantity', 'VAT', 'discount', 'from', 'to', 'discount_type'));
        $Model->Categories()->sync($request->categories);

        if ($request->sections) {
            foreach ($request->sections as $section_html) {
                if ($section_html['title_ar'] && $section_html['title_en']) {
                    $Section = $Model->Sections()->create([
                        'product_id' => $Model->id,

                        'title_ar' => $section_html['title_ar'],
                        'title_en' => $section_html['title_en'],

                        'select_type' => $section_html['select_type'],
                        'required' => $section_html['required'],
                    ]);
                    foreach ($section_html['items'] as $items_html) {
                        $Section->Items()->create([

                            'section_id' => $Section->id,

                            'title_ar' => $items_html['title_ar'],
                            'title_en' => $items_html['title_en'],

                            'price' => $items_html['price'],
                            'show' => $items_html['show'],

                            'quantity'=> $items_html['quantity'],

                        ]);
                    }
                }
            }
        }

        if ($request->images) {
            foreach (Upload::uploadFiles($request->images, 'products') as $image) {
                $Model->Images()->create([
                    'image' => $image,
                ]);
            }
        }
        $Model->save();

        alert()->success(__('trans.addedSuccessfully'));

        return redirect()->back();
    }

    public function show($id)
    {
        abort(404);
    }

    public function edit($id)
    {
        $Model = Model::where('id', $id)->with('Categories')->firstorfail();
        $Categories = $this->renderCategoryOptions($Model->Categories->pluck('id')->toarray());

        return view('product::edit', compact('Model', 'Categories'));
    }

    public function update(Request $request, $id)
    {
        $Model = Model::where('id', $id)->firstorfail();

        $Model->update($request->only('code', 'price', 'weight' , 'title_ar', 'pre_order','title_en', 'desc_ar', 'desc_en', 'quantity', 'VAT', 'discount', 'from', 'to','discount_type'));
        $Model->Categories()->sync($request->categories);

        $collect_sections = collect($request->sections);
        $Model->Sections()->whereNotIn('id', $collect_sections->pluck('id'))->delete();

        if ($request->images) {
            foreach (Upload::uploadFiles($request->images, 'products') as $image) {
                $Model->Images()->create([
                    'image' => $image,
                ]);
            }
        }

        if ($request->sections) {

            foreach ($request->sections as $section_html) {
                if ($section_html['title_ar'] && $section_html['title_en']) {
                    if (isset($section_html['id'])) {
                        $Model->Sections()->where('id', $section_html['id'])->update([
                            'product_id' => $Model->id,

                            'title_ar' => $section_html['title_ar'],
                            'title_en' => $section_html['title_en'],

                            'select_type' => $section_html['select_type'],
                            'required' => $section_html['required'],
                        ]);
                        $Section = $Model->Sections()->where('id', $section_html['id'])->first();
                    } else {
                        $Section = $Model->Sections()->create([
                            'product_id' => $Model->id,

                            'title_ar' => $section_html['title_ar'],
                            'title_en' => $section_html['title_en'],

                            'select_type' => $section_html['select_type'],
                            'required' => $section_html['required'],
                        ]);
                    }
                    $collect_items = collect($section_html['items']);
                    $Section->Items()->whereNotIn('id', $collect_items->pluck('id'))->delete();
                    foreach ($section_html['items'] as $items_html) {
                        if (isset($items_html['id'])) {
                            $Section->Items()->where('id', $items_html['id'])->update([

                                'section_id' => $Section->id,

                                'title_ar' => $items_html['title_ar'],
                                'title_en' => $items_html['title_en'],

                                'price' => $items_html['price'],
                                'show' => isset($items_html['show']) ? $items_html['show'] : 0,

                                'quantity'=> $items_html['quantity'],

                            ]);
                        } else {
                            $Section->Items()->create([

                                'section_id' => $Section->id,

                                'title_ar' => $items_html['title_ar'],
                                'title_en' => $items_html['title_en'],

                                'price' => $items_html['price'],
                                'show' => $items_html['show'],

                                'quantity'=> $items_html['quantity'],

                            ]);
                        }
                    }
                }
            }

        }
        $Model->save();

        alert()->success(__('trans.updatedSuccessfully'));

        return redirect()->back();
    }

    public function destroy($id)
    {
        $Model = Model::where('id', $id)->delete();
    }

    public function sort(Request $request)
    {
        $request_categories = $request->categories;
        $Categories = \Modules\Category\Entities\Model::whereHas('Products')->with('Products')->withCount('Products')->having('products_count', '>', 1)->get();
        $CatSort = 1;
        \Modules\Category\Entities\Model::query()->update(['arrangement' => null]);
        foreach ($request_categories as $CategoryId => $Data) {
            \Modules\Category\Entities\Model::where('id', $CategoryId)->update(['arrangement' => $CatSort]);
            $CatSort++;
            $Category = $Categories->where('id', $CategoryId)->first();
            $ProductSort = 1;
            if ($Category && isset($Data) && is_array($Data)) {
                foreach ($Data as $ProductId) {
                    $Category->Products()->where('products.id', $ProductId)->update(['arrangement' => $ProductSort]);
                    $ProductSort++;
                }
            }
        }
        alert()->success(__('trans.updatedSuccessfully'));

        return back();
    }

    public function renderCategoryOptions($selectedCategoryIds = [], $path = '', $Categories = null)
    {
        if ($Categories === null) {
            $Categories = Category::get();
        }

        $html = '';
        foreach ($Categories as $Category) {
            $currentPath = $path ? $path.' - '.$Category->title() : $Category->title();

            if ($Category->children && $Category->children->isNotEmpty()) {
                $html .= $this->renderCategoryOptions($selectedCategoryIds, $currentPath, $Category->children);
            } else {
                $isSelected = in_array($Category->id, $selectedCategoryIds) ? 'selected' : '';
                $html .= '<option value="'.$Category->id.'" '.$isSelected.'>'.$currentPath.'</option>';
            }
        }

        return $html;
    }
    
    
    public function reviews(Request $request)
    {
        if ($request->ajax()) {
            $query = ModelReview::with(['Product.Images', 'Client']);
    
            return DataTables::of($query)
                ->addColumn('actions', function ($Model) {
                    return view('product::layouts.delete-review', ['Model' => $Model]);
                })
                ->addColumn('product', function ($Model) {
                    return view('product::layouts.title_' . lang(), ['Model' => $Model->Product]);
                })
                ->addColumn('client', function ($Model) {
                    return $Model->Client ? $Model->Client->name : '-';
                })
                ->addColumn('image', function ($Model) {
                    return view('product::layouts.image', ['Model' => $Model->Product]);
                })
                ->addColumn('rate', function ($Model) {
                    return $Model->rate;
                })
                ->addIndexColumn()
                ->rawColumns(['actions', 'product', 'image'])
                ->make(true);
        } else {
            return view('product::reviews');
        }
    }


    public function DeleteReview($id)
    {
        $ModelReview = ModelReview::where('id', $id)->delete();
    }
}
