<?php

namespace App\Http\Controllers\TestManager;

use App\Http\Controllers\Controller;
use App\Models\StyleType;
use App\Models\FontFamily;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class StyleTypesController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:style-type-list', ['only' => ['index']]);
    }

    public function index(Request $request)
    {
        $data = StyleType::select([
                    'style_types.id',
                    'style_types.name',
                    'style_types.code',
                    'style_types.font_color',
                    'style_types.bg_color',
                    'style_types.font_family',
                    'style_types.text_decoration',
                    'style_types.font_size',
                    'style_types.font_style',
                    'style_types.font_weight',
                    'style_types.font_padding',
                    'style_types.flag',
                    'style_types.is_default',
                    'style_types.status',
                    'font_families.font_name',
                ])
                ->leftJoin('font_families', 'font_families.id', '=', 'style_types.font_family')
                ->orderBy('style_types.name', 'ASC');

        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('style_types.name', 'like', '%'.$search_query.'%')
                    ->orWhere('style_types.text_decoration', 'like', '%'.$search_query.'%')
                    ->orWhere('style_types.font_size', 'like', '%'.$search_query.'%')
                    ->orWhere('style_types.font_style', 'like', '%'.$search_query.'%')
                    ->orWhere('style_types.font_weight', 'like', '%'.$search_query.'%')
                    ->orWhere('style_types.font_padding', 'like', '%'.$search_query.'%')
                    ->orWhere('style_types.flag', 'like', '%'.$search_query.'%')
                    ->orWhere('style_types.code', 'like', '%'.$search_query.'%')
                    ->orWhere('font_families.font_name', 'like', '%'.$search_query.'%');
            })
            ->paginate($sort_by);

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

            return view('style-types.index', compact('data'));
        }
    }

    public function create()
    {
        $fonts = FontFamily::get();

        return view('style-types.create', compact('fonts'));
    }

    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:style_types,name,NULL,id,deleted_at,NULL',
        ]);

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

        $default_check = StyleType::where(['is_default' => 1,'status' => 1])->first();

        if (!$default_check) {
            $data['is_default'] = 1;
        }

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

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Style Type created successfully.',
                'data'    => $StyleType
            ]);
        }
    }

    public function edit($id)
    {
        $data = StyleType::find($id);
        $fonts = FontFamily::get();

        return view('style-types.edit',compact('data', 'fonts'));
    }

    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:style_types,name,'.$id.',id,deleted_at,NULL',
        ]);

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

        $StyleType = StyleType::find($id);

        if (!$StyleType) {
            return redirect()->back()
                ->with('error','Style Type not found!');
        }

        $StyleType->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Style Type Updated successfully',
                'data'    => $StyleType
            ]);
        }
    }

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

            $Redirect = 'style-types';

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

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

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default style type!'],
                    'data'    => []
                ]);
            } else {
                $Update = StyleType::where('id', '=', $request->id)->update($data);

                if($Update){
                    return response()->json([
                        'success'=>true,
                        'message'=>['Style Type default status successfully changed.'],
                        'data'=>[
                        ]
                    ]);
                } else {
                    return response()->json([
                       'success'=>false,
                       'message'=>['Error for change default'],
                       'data'=>[
                           'redirect'=>'',
                       ]
                    ]);
                }
            }
        }
    }

    public function destroy(Request $request)
    {
        $data = StyleType::find($request->id);

        if ($data->is_default == '1') {
            return response()->json([
                'success' => false,
                'message' => ['Default record can not be deleted.']
            ]);
        }

        $data->delete();

        $Redirect = 'style-types';

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