<?php

namespace App\Http\Controllers;

use App\TailoringCategory;
use Auth;
use Illuminate\Contracts\Validation\Rule;
use Spatie\Permission\Models\Role;

use Illuminate\Http\Request;

class TailoringCategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $role = Role::find(Auth::user()->role_id);
        if ($role->hasPermissionTo('category')) {
            $categories = TailoringCategory::where([['is_active', true], ['name', 'Curtain']])->get();
            return view('backend.tailoringCategory.create', compact('categories'));
        } else
            return redirect()->back()->with('not_permitted', 'Sorry! You are not allowed to access this module');
    }

    public function categoryData(Request $request)
    {
        $columns = array(
            0 => 'id',
            1 => 'name',
            3 => 'is_active',
        );
        $totalData = TailoringCategory::where([['is_active', true], ['name', 'Curtain']])->count();
        $totalFiltered = $totalData;
        if (empty($request->input('search.value'))) {

            $categories = TailoringCategory::where([['is_active', true], ['name', 'Curtain']])
                ->get();
        } else {
            $search = $request->input('search.value');
            $categories =  TailoringCategory::where([
                ['name', 'LIKE', "%{$search}%"],
                ['is_active', true],
                ['name', 'Curtain']
            ])->get();

            $totalFiltered = TailoringCategory::where([
                ['name', 'LIKE', "%{$search}%"],
                ['is_active', true],
                ['name', 'Curtain']
            ])->count();
        }
        $data = array();
        if (!empty($categories)) {
            foreach ($categories as $key => $category) {
                $nestedData['id'] = $category->id;
                $nestedData['key'] = $key;

                $nestedData['name'] = $category->name;

                // $nestedData['number_of_product'] = $category->product()->where('is_active', true)->count();
                // $nestedData['stock_qty'] = $category->product()->where('is_active', true)->sum('qty');
                // $total_price = $category->product()->where('is_active', true)->sum(DB::raw('price * qty'));
                // $total_cost = $category->product()->where('is_active', true)->sum(DB::raw('cost * qty'));

                // if (config('currency_position') == 'prefix')
                //     $nestedData['stock_worth'] = config('currency') . ' ' . $total_price . ' / ' . config('currency') . ' ' . $total_cost;
                // else
                //     $nestedData['stock_worth'] = $total_price . ' ' . config('currency') . ' / ' . $total_cost . ' ' . config('currency');

                $nestedData['options'] = '<div class="btn-group">
                            <button type="button" class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">' . trans("file.action") . '
                              <span class="caret"></span>
                              <span class="sr-only">Toggle Dropdown</span>
                            </button>
                            <ul class="dropdown-menu edit-options dropdown-menu-right dropdown-default" user="menu">
                                <li>
                                    <button type="button" data-id="' . $category->id . '" class="open-EditCategoryDialog btn btn-link" data-toggle="modal" data-target="#editModal" ><i class="dripicons-document-edit"></i> ' . trans("file.edit") . '</button>
                                </li>
                                <li class="divider"></li>' .
                    \Form::open(["route" => ["category.destroy", $category->id], "method" => "DELETE"]) . '
                                <li>
                                  <button type="submit" class="btn btn-link" onclick="return confirmDelete()"><i class="dripicons-trash"></i> ' . trans("file.delete") . '</button>
                                </li>' . \Form::close() . '
                            </ul>
                        </div>';
                $data[] = $nestedData;
            }
        }
        $json_data = array(
            "draw"            => intval($request->input('draw')),
            "recordsTotal"    => intval($totalData),
            "recordsFiltered" => intval($totalFiltered),
            "data"            => $data
        );
        echo json_encode($json_data);
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->name = preg_replace('/\s+/', ' ', $request->name);
        if ($request->name !== 'Curtain') {
            return back()->with('not_permitted', 'Only Curtain category is available for this store.');
        }
        $this->validate($request, [
            'name' => [
                'max:255',
                'unique:tailoring_categories'

            ],
        ]);
        $lims_category_data['name'] = $request->name;
        TailoringCategory::create($lims_category_data);
        return back()->with('message', 'Category inserted successfully');
    }

    /**
     * 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)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {

        $request->name = preg_replace('/\s+/', ' ', $request->name);
        $this->validate($request, [
            'name' => [
                'max:255',
                'unique:tailoring_categories,name,' . $id

            ],
        ]);

        $input['name'] = $request->name;
        $lims_category_data = TailoringCategory::findOrFail($id);
        $lims_category_data->update($input);
        return back()->with('message', 'Category updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $lims_category_data = TailoringCategory::findOrFail($id);
        $lims_category_data->is_active = false;
        $lims_category_data->save();
        return back()->with('not_permitted', 'Category deleted successfully');
    }
}
