<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\CategoryAtributes;
use App\Models\CategoryAtributesValue;
use App\Models\CategoryField;
use App\Models\FieldCondition;
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 CategoryController extends Controller
{
    public function index()
    {
        
        $categories = Category::orderBy('created_at', 'desc')->get();
        
        return view('admin.category.index', compact('categories'));

    }

    public function getCategoryList(Request $request) 
    {
        $sqlBuilder = Category::select([
            'categories.id',
            'categories.name',
            'categories.name_ar',
            'categories.status',
            'categories.parent_id',
            'categories.icon',
        ])->with('parent');

        return DataTables::of($sqlBuilder)
            ->filter(function ($query) use ($request) {
            if ($request->has('search') && !empty($request->search['value'])) {
                $query->where('categories.name', 'ilike', "%" . $request->search['value'] . "%");
            }
            })
            ->editColumn('icon', function ($data) {
                $icon = !empty($data->icon) ? $data->icon : asset('assets/images/camera_placeholder.png');
                return '<div style="text-align:center;"><img src="' . $icon . '" class="rounded-circle avatar-xs" alt="icon"></div>';
                
            })
            ->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.categories.status', ['id' => $data->id]) .'" data-id="'.$data->id.'" '.(!empty($data->status) && $data->status == 1 ? 'checked' : '').' />
                    </div>
                </div>';
            })
            ->addColumn('parent_category_name', function ($data) {
            return !empty($data->parent_category_name)?$data->parent_category_name:'N/A'; 
            })
            ->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.categories.edit', ['id' => $data->id]) . '">Edit</a></li>
                            <li><a class="dropdown-item" href="'.route('admin.categories.formfields', $data->id).'">Form Fields</a></li>
                            <li><a class="dropdown-item" href="'.route('admin.ads', ['category_page_id' => encrypt($data->id)]).'">Total Ads ('.$data->ads()->count().')</a></li>
                            <li><a class="dropdown-item delete-btn" data-url="' . route('admin.categories.destroy', ['id' => $data->id]) . '">Delete</a></li>
                        </ul>
                        </div>';
            return $html;
            })
            ->rawColumns(['status','action','icon'])
            ->make(true);
    }

    public function getCategoryMinimalList(Request $request)
    {
        $categories = Category::select('id', 'name');
        if($request->has('parent_id')){
            $categories->where('parent_id', $request->parent_id);
        }
        $categories = $categories->where('status',1)->get();

        return response()->json($categories);
    }

    public function create(){
        $categories = Category::get();

        return view('admin.category.create', compact('categories'));

    }

    public function store(Request $request)
    {
        $rules = [
            'name' => 'required|string|max:255',
            'name_ar' => 'required|string|max:255',
            'parent_id' => 'nullable|integer',
            'status' => 'required|in:0,1',
            'icon' => 'nullable|image|mimes:jpeg,png,jpg',
        ];
    
        $validator = Validator::make($request->all(), $rules);
    
        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'errors' => $validator->errors(),
            ], 422);
        }

        if($request->parent_id == 0){
            $request->parent_id = null;
        }
    
        if ($request->id) {
            $category = Category::find($request->id);
    
            if (!$category) {
                return response()->json(['status' => 'error', 'message' => 'Category not found'], 404);
            }
    
            $existingCategory = Category::where('name', $request->name)
                ->where('id', '!=', $request->id)
                ->first();
    
            if ($existingCategory) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The Category name already exists.']
                    ]
                ], 422);
            }
    
            $category->name = $request->name;
            $category->name_ar = $request->name_ar;
            $category->status = $request->status;
            $category->parent_id = $request->parent_id??null;
            if ($request->hasFile('icon')) {
                $file = $request->file('icon');
                    if ($file->isValid()) {
                        $storedPath = $file->store('category_icon', 'public');
                        $storedFilename = basename($storedPath);
                        $category->icon = $storedFilename;
                    }
            }
            $category->save();
    
            return response()->json(['status' => 'success', 'message' => 'Category updated successfully']);
        } else {
            $existingCategory = Category::where('name', $request->name)->first();
    
            if ($existingCategory) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The Category name already exists.']
                    ]
                ], 422);
            }
    
            $category = Category::create([
                'name' => $request->name, 
                'name_ar' => $request->name_ar, 
                'status' => $request->status,
                'parent_id' => $request->parent_id??null,
            ]);
            if ($request->hasFile('icon')) {
                $file = $request->file('icon');
                    if ($file->isValid()) {
                        $storedPath = $file->store('category_icon', 'public');
                        $storedFilename = basename($storedPath);
                        $category->icon = $storedFilename;
                    }
            }
    
            return response()->json(['status' => 'success', 'message' => 'Category added successfully', 'category' => $category]);
        }
    }
    
    public function edit($id) {
        $category = Category::findOrFail($id);
        $categories = Category::whereNot('id',$id)->get();
        $categories = $categories->filter(function ($cat) use ($id) {
            $current = $cat;
            while ($current) {
            if ($current->parent_id == $id) {
                return false;
            }
            $current = $current->parent;
            }
            return true;
        });

        return view('admin.category.create', compact('category','categories'));
    }

    public function destroy($id): JsonResponse
    {
        try {
            $category = Category::findOrFail($id);
            // Check if the category has any child categories
            $childCategories = Category::where('parent_id', $category->id)->get();
            if ($childCategories->isNotEmpty()) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Cannot delete this category because it has child categories.'
                ], 422);
            }
            // Check if the category has any ads
            $ads = $category->ads()->count();
            if ($ads > 0) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Cannot delete this category because it has ads.'
                ], 422);
            }
            // Check if the category has any fields
            $fields = CategoryField::where('category_id', $category->id)->count();
            if ($fields > 0) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Cannot delete this category because it has fields.'
                ], 422);
            }           
            $category->delete();
            return response()->json([
                'status' => 'success',
                'message' => 'Category deleted successfully.'
            ], 200);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Category 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) {
        $category = Category::find($id);

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

    public function formfields($id) {
        
        $category = Category::with(['parent'])->find($id);
        $category_fields = CategoryField::where('category_id',$id)->get();
        $conditions_fields = FieldCondition::where('category_id',$id)->get();
        $categoryatributes = CategoryAtributes::where('category_id',$id)->where('status',1)->orderBy('created_at', 'desc')->get();
        $attributeValues = CategoryAtributesValue::where('category_id', $id)->where('status', 1)->get()->groupBy('attribute_id');
        
        return view('admin.category.formfields', compact('category', 'categoryatributes','category_fields','attributeValues','conditions_fields'));
    }

    public function storeformfields($id,Request $request)
    {
        // Validation rules for the incoming request
        $rules = $request->validate([
            'category_fields' => 'required|array',
            'category_fields.*.type' => 'required|string',
            'category_fields.*.label' => 'required|string',
            'category_fields.*.name' => 'required|string',
            'category_fields.*.options' => 'nullable|string',  // For radio/checkbox options
            'category_fields.*.attribute_id' => 'nullable', // For select attribute
            'category_fields.*.file_types' => 'nullable|string', // For file upload types
            'category_fields.*.required' => 'nullable|string',
            'category_fields.*.order' => 'nullable|string',
            'category_fields.*.existing_field_id' => 'nullable|exists:category_fields,id',
            'conditions' => 'nullable|array',
            'conditions.*.attribute_id' => 'nullable|integer',
            'conditions.*.operator' => 'required|string',
            'conditions.*.value' => 'required|string',  // Or 'required|integer' based on the expected value type
            'conditions.*.field_id' => 'required|string'
        ]);

        $validation = Validator::make($request->all(), $rules);
        if ($validation->fails()) {
            return response()->json([
                'status' => 'error',
                'errors' => $validation->errors(),
            ], 422);
        }

        $formFields = $request->category_fields;
        $existingFieldIds = [];

        foreach ($formFields as $field) {
            if (isset($field['existing_field_id']) && $field['existing_field_id'] != null) {
                $existingFieldIds[] = $field['existing_field_id'];
                CategoryField::where('id',$field['existing_field_id'])->update(
                    [
                        'category_id' => $request->id, 
                        'field_id' => $field['field_id'],
                        'name' => $field['name'],
                        'name_ar' => $field['name_ar'],
                        'type' => $field['type'],
                        'label' => $field['label'],
                        'label_ar' => $field['label_ar'],
                        'options' => $field['options'] ?? null,
                        'attribute_id' => $field['attribute_id'] ?? null,
                        'file_types' => $field['file_types'] ?? null,
                        'order' => $field['order'] ?? null,
                        'required' => $field['required'] ?? null,
                        'section' => $field['section'] ?? null,
                    ]
                );
            } else {
                $existingFieldIds[] = CategoryField::create(
                    [
                        'category_id' => $request->id, 
                        'field_id' => $field['field_id'],
                        'name' => $field['name'],
                        'name_ar' => $field['name_ar'],
                        'type' => $field['type'],
                        'label' => $field['label'],
                        'label_ar' => $field['label_ar'],
                        'options' => $field['options'] ?? null,
                        'attribute_id' => $field['attribute_id'] ?? null,
                        'file_types' => $field['file_types'] ?? null,
                        'order' => $field['order'] ?? null,
                        'required' => $field['required'] ?? null,
                        'section' => $field['section'] ?? null,
                    ]
                )->id;
            }
        }
 
        CategoryField::where('category_id', $request->id)->whereNotIn('id', $existingFieldIds)->delete();

        FieldCondition::where('category_id', $request->id)->delete();

        if (!empty($request->conditions)) {
            foreach ($request->conditions as $condition) {
                $targetFieldId = CategoryField::where('category_id', $request->id)->where('field_id', $condition['field_id'])->value('id');
                $sourceFieldId = CategoryField::where('category_id', $request->id)->where('attribute_id', $condition['attribute_id'])->value('id');

                FieldCondition::create(
                    [
                        'category_id' => $request->id,
                        'field_id' => $condition['field_id'],
                        'attribute_id' => $condition['attribute_id'] ?? null,
                        'operator' => $condition['operator'],
                        'value' => $condition['value'],
                        'target_field_id' => $targetFieldId?? null,
                        'source_field_id' => $sourceFieldId?? null,
                    ]
                );
            }
        }

        return response()->json([
            'message' => 'Category fields have been successfully saved or updated.',
        ]);
    }
}
