<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Activity;
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 ActivityController extends Controller
{
    public function index()
    {
        $activities = Activity::orderBy('created_at', 'desc')->get();

        return view('admin.activities.index', compact('activities'));
    }

    public function getActivityList(Request $request)
    {
        $sqlBuilder = Activity::select([
            'activities.id',
            'activities.name',
            'activities.name_ar',
            'activities.status',
            'activities.image',
        ]);

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

    public function create()
    {
        $activity = "";

        return view('admin.activities.create', compact('activity'));
    }

    public function store(Request $request)
    {
        $rules = [
            'name' => 'required|string|max:255',
            'name_ar' => 'required|string|max:255',
            'status' => 'required|in:0,1',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ];

        $validator = Validator::make($request->all(), $rules);

        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'errors' => $validator->errors(),
            ], 422);
        }

        if ($request->id) {
            $activity = Activity::find($request->id);

            if (!$activity) {
                return response()->json(['status' => 'error', 'message' => 'Activity not found'], 404);
            }

            $activity->name = $request->name;
            $activity->name_ar = $request->name_ar;
            $activity->status = $request->status;
            $activity->save();

            if($request->file("image")){
                $response = image_upload($request,config('global.activity_image_upload_dir'),'image');
                if($response['status']){
                    $activity->image = $response['link'];
                    $activity->save();
                }
            }

            return response()->json(['status' => 'success', 'message' => 'Activity updated successfully']);
        } else {
            $alreadyExists = Activity::where('name', $request->name)->orWhere('name_ar', $request->name_ar)->first();
            if ($alreadyExists) {
                return response()->json(['status' => 'error', 'message' => 'Activity already exists'], 422);
            }
            $activity = Activity::create([
                'name' => $request->name,
                'name_ar' => $request->name_ar,
                'status' => $request->status,
            ]);

            if($request->file("image")){
                $response = image_upload($request,config('global.activity_image_upload_dir'),'image');
                if($response['status']){
                    $activity->image = $response['link'];
                    $activity->save();
                }
            }

            return response()->json(['status' => 'success', 'message' => 'Activity added successfully', 'activity' => $activity]);
        }
    }

    public function edit($id)
    {
        $activity = Activity::findOrFail($id);

        return view('admin.activities.create', compact('activity'));
    }

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

    public function statusChange(Request $request, $id)
    {
        $activity = Activity::find($id);

        if (!$activity) {
            return response()->json([
                'status' => 'error',
                'message' => 'Activity not found.'
            ], 404);
        }

        $activity->status = $request->status;
        $activity->save();

        return response()->json([
            'status' => 'success',
            'message' => 'Activity status updated successfully.'
        ]);
    }
}
