<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Badge;
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 BadgeController extends Controller
{
    public function index()
    {
        $badges = [];
        
        return view('admin.badges.index', compact('badges'));

    }

    public function getBadgeList(Request $request) 
    {
        $sqlBuilder = Badge::select([
            'badges.id',
            'badges.name',
            'badges.name_ar',
            'badges.type',
            'badges.icon',
            'badges.status',
        ]);

        return DataTables::of($sqlBuilder)
            ->filter(function ($query) use ($request) {
                if ($request->has('search') && !empty($request->search['value'])) {
                    $query->where('badges.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="profile-image"></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.badges.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.badges.edit', ['id' => $data->id]) . '">Edit</a></li>
                                            <li><a class="dropdown-item delete-btn" data-url="' . route('admin.badges.destroy', ['id' => $data->id]) . '">Delete</a></li>
                                        </ul>
                                    </div>';
            return $html;
            })
            ->rawColumns(['icon','status','action'])
            ->make(true);
    }

    public function create(){
        $badge = "";
        return view('admin.badges.create', compact('badge'));

    }

    public function store(Request $request)
    {
        $rules = [
            'name' => 'required|string|max:255',
            'name_ar' => 'required|string|max:255',
            'type' => 'required|string',
            'description' => 'required|string|max:255',
            'description_ar' => 'required|string|max:255',
            'icon' => empty($request->id)?'required|':''.'image|mimes:jpeg,png,jpg|max:2048',
            'status' => 'required|in:0,1',
        ];
    
        $validator = Validator::make($request->all(), $rules);
    
        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'errors' => $validator->errors(),
            ], 422);
        }
    
        if ($request->id) {
            $badge = Badge::find($request->id);
    
            if (!$badge) {
                return response()->json(['status' => 'error', 'message' => 'Badge not found'], 404);
            }
    
            $existingBadge = Badge::where('name', $request->name)
                ->where('id', '!=', $request->id)
                ->first();
    
            if ($existingBadge) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The Badge name already exists.']
                    ]
                ], 422);
            }
    
            $badge->name = $request->name;
            $badge->name_ar = $request->name_ar;
            $badge->type = $request->type;
            $badge->description = $request->description;
            $badge->description_ar = $request->description_ar;
            $badge->status = $request->status;
            $badge->save();

            if ($request->hasFile('icon')) {
                $file = $request->file('icon');
                    if ($file->isValid()) {
                        $response = file_save($file, config('global.badge_image_upload_dir'));
                        if(isset($response['status']) && $response['status'] == true){
                            $badge->icon = $response['link'];
                            $badge->save();
                        }
                    }
            }
    
            return response()->json(['status' => 'success', 'message' => 'Badge updated successfully']);
        } else {
            $existingBadge = Badge::where('name', $request->name)->first();
    
            if ($existingBadge) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The Badge name already exists.']
                    ]
                ], 422);
            }
    
            $badge = Badge::create([
                'name' => $request->name,
                'name_ar' => $request->name_ar,
                'type' => $request->type,
                'description' => $request->description,
                'description_ar' => $request->description_ar,
                'status' => $request->status,
            ]);

            if ($request->hasFile('icon')) {
                $file = $request->file('icon');
                    if ($file->isValid()) {
                        $response = file_save($file, config('global.badge_image_upload_dir'));
                        if(isset($response['status']) && $response['status'] == true){
                            $badge->icon = $response['link'];
                            $badge->save();
                        }
                    }
            }
    
            return response()->json(['status' => 'success', 'message' => 'Badge added successfully', 'emirate' => $badge]);
        }
    }
    
    public function edit($id) {
        $badge = Badge::findOrFail($id);
        return view('admin.badges.create', compact('badge'));
    }

    public function destroy($id): JsonResponse
    {
        try {
            $emirate = Badge::findOrFail($id);           
            $emirate->delete();
            return response()->json([
                'status' => 'success',
                'message' => 'Badge deleted successfully.'
            ], 200);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Badge 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) {
        $badge = Badge::find($id);

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