<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\CategoryAtributes;
use App\Models\CategoryAtributesValue;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\JsonResponse;
use Yajra\DataTables\Facades\DataTables;

class CategoryAttributesValueController extends Controller
{
    public function index()
    {
        $categoryatributes = CategoryAtributesValue::with(['categories','attribute'])->orderBy('created_at', 'desc')->get();
        
        return view('admin.categoryatributesvalue.index', compact('categoryatributes'));

    }

    public function getCategoryAttributeValueList(Request $request)
    {
        $sqlBuilder = CategoryAtributesValue::select('category_atributes_value.*')
        ->with(['categories','attribute'])
        ->join('categories', 'category_atributes_value.category_id', '=', 'categories.id');

        return DataTables::of($sqlBuilder)
        ->filter(function ($query) use ($request) {
            if ($request->has('search') && !empty($request->search['value'])) {
                $query->where('category_atributes_value.name', 'ilike', "%" . $request->search['value'] . "%")
                    ->orWhere('category_atributes_value.name_ar', 'ilike', "%" . $request->search['value'] . "%")
                    ->orWhere('categories.name', 'ilike', "%" . $request->search['value'] . "%");
            }
        })
        ->editColumn('category_name', function ($data) {
            return $data->categories->name_with_parent_category_name ?? '';
        })
        ->editColumn('attribute_name', function ($data) {
            return $data->attribute->name ?? '';
        })
        ->editColumn('status', function ($data) {
            return '<div class="status">
            <div class="form-check form-switch ">
                <input class="form-check-input status-checkbox" type="checkbox" role="switch" id="SwitchCheck4" data-url="'. route('admin.category_atributes_value.status', ['id' => $data->id]) .'" data-id="'.$data->id.'" '.(!empty($data->status) && $data->status == 1 ? 'checked' : '').' />
            </div>
            </div>';
        })
        ->addColumn('action', function ($data) {
            $html = '<div class="dropdown">
                <a href="#" class="btn btn-soft-secondary btn-sm" role="button" id="dropdownMenuLink5" data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="ri-more-2-fill"></i>
                </a>
                <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink5">
                    <li><a class="dropdown-item" href="' . route('admin.category_atributes_value.edit', ['id' => $data->id]) . '">Edit</a></li>
                    <li><a class="dropdown-item delete-btn" data-url="' . route('admin.category_atributes_value.destroy', ['id' => $data->id]) . '">Delete</a></li>
                </ul>
                </div>';
            return $html;
        })
        ->rawColumns(['category_name', 'attribute_name', 'status', 'action'])
        ->make(true);
    }

    public function getAttributes(Request $request)
    {
        $category_id = $request->input('category_id');
        
        $attributes = CategoryAtributes::where('category_id', $category_id)->where('status',1)->get();

        
        return response()->json($attributes);
    }
    public function create(){
        $categoryatribute = "";
        $categories = Category::orderBy('id', 'desc')->whereNotNull('parent_id')->where('status', 1)->get();
        return view('admin.categoryatributesvalue.create', compact('categoryatribute','categories'));

    }

    public function store(Request $request)
    {
        $rules = [
            'name' => 'required|string|max:255',
            'name_ar' => 'required|string|max:255',
            'status' => 'required|in:0,1',
            'category_id' => 'required',
            'attribute_id' => 'required',
        ];
    
        $validator = Validator::make($request->all(), $rules);
    
        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'errors' => $validator->errors(),
            ], 422);
        }
    
        if ($request->id) {
            $emirate = CategoryAtributesValue::find($request->id);
    
            if (!$emirate) {
                return response()->json(['status' => 'error', 'message' => 'Category Atribute not found'], 404);
            }
    
            $existingEmirate = CategoryAtributesValue::where('name', $request->name)
                ->where('id', '!=', $request->id)
                ->where('category_id', $request->category_id)
                ->where('attribute_id', $request->attribute_id)
                ->first();
    
            if ($existingEmirate) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The Category Atribute value  already exists.']
                    ]
                ], 422);
            }
    
            $emirate->name = $request->name;
            $emirate->name_ar = $request->name_ar;
            $emirate->category_id = $request->category_id;
            $emirate->attribute_id = $request->attribute_id;
            $emirate->status = $request->status;
            $emirate->save();
    
            return response()->json(['status' => 'success', 'message' => 'Category Atribute value updated successfully']);
        } else {
            $existingCategoryAtributes = CategoryAtributesValue::where('name', $request->name)->where('category_id', $request->category_id)->where('attribute_id', $request->attribute_id)->first();
    
            if ($existingCategoryAtributes) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The Category Atribute name already exists.']
                    ]
                ], 422);
            }
    
            $emirate = CategoryAtributesValue::create([
                'name' => $request->name,
                'name_ar' => $request->name_ar,
                'category_id' => $request->category_id,
                'attribute_id' => $request->attribute_id,
                'status' => $request->status,
            ]);
    
            return response()->json(['status' => 'success', 'message' => 'Category Atribute value added successfully', 'emirate' => $emirate]);
        }
    }
    


  
    public function edit($id) {
        $categoryatribute = CategoryAtributesValue::with('categories')->findOrFail($id);
        $categories = Category::orderBy('id', 'desc')->whereNotNull('parent_id')->where('status', 1)->get();
        return view('admin.categoryatributesvalue.create', compact('categoryatribute','categories'));
    }

    public function destroy($id): JsonResponse
    {
        try {
            $categoryatribute = CategoryAtributesValue::findOrFail($id);           
            $categoryatribute->delete();
            return response()->json([
                'status' => 'success',
                'message' => 'Category Atribute value deleted successfully.'
            ], 200);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Category Atribute  not found.'
            ], 404);
        } catch (Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while deleting the company.'
            ], 500);
        }
    }

    public function statusChange(Request $request, $id) {
        $categoryatribute = CategoryAtributesValue::find($id);

        if (!$categoryatribute) {
            return response()->json([
                'status' => 'error',
                'message' => 'Category Atribute  not found.'
            ], 404);
        }
    
        $categoryatribute->status = $request->status;
        $categoryatribute->save();
    
        return response()->json([
            'status' => 'success',
            'message' => 'Category Atribute value status updated successfully.'
        ]);
    }
}
