<?php

namespace App\Http\Controllers\Admin;

use App\Models\AddSpace;
use Jenssegers\Agent\Agent;
use Illuminate\Http\Request;
use Torann\GeoIP\Facades\GeoIP;
use App\Models\EmployeeActivity;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Spatie\Permission\Models\Role;

class AddSpaceController extends Controller
{
    public function index(Request $request)
    {

        $this->authorize('Addspace Access');

        $customer = AddSpace::query();
        $searchTerm = $request['filter'] ?? null;
        $perPage    = $request['per_page'] ?? 15;
        $page       = $request['page'] ?? 1;
        if ($searchTerm) {
            $customer->where(function ($query) use ($searchTerm) {
                $query->where(function ($query) use ($searchTerm) {
                    $columns = Schema::getColumnListing('add_spaces');
                    foreach ($columns as $column) {
                        $query->orWhere($column, 'LIKE', "%{$searchTerm}%");
                    }
                });
            });
        }
        $items = $customer->paginate($perPage);

        $data['queryList'] = $items;


        $user = User::with('usetting')->findOrFail(Auth::user()->id);
        $role = Role::where('name', $user->getRoleNames()[0])->get();
        foreach ($role as $roles) {
            $data['permissions'] = $roles->getPermissionNames();
        }


        return $data;
    }


    public function storeAddSpace(Request $req)
    {
        $status = filter_var($req->status, FILTER_VALIDATE_BOOLEAN);
        $rules = [
            'addSpaceTitle' => 'required|string|max:255|unique:add_spaces,title,' . $req->id,
            'addSpaceLink' => 'required|string',
        ];

        if (!$req->id) {
            $rules['addspaceImage'] = 'required|mimes:jpg,jpeg,png,svg|max:5120';
        } else {
            $rules['addspaceImage'] = 'nullable|mimes:jpg,jpeg,png,svg|max:5120';
        }

        // Validate the request with the defined rules
        $validator = Validator::make($req->all(), $rules);
        // Check if validation fails
        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()]);
        }

        $addSpaceImage = null;

        // Handle file upload
        if ($req->hasFile('addspaceImage')) {
            $file = $req->file('addspaceImage');

            if ($file->isValid()) {
                $destinationPath = public_path('/uploads/addspace/');
                if (!File::exists($destinationPath)) {
                    File::makeDirectory($destinationPath, 0777, true);
                }
                $addSpaceImage = date('YmdHis') . "." . $file->getClientOriginalExtension();
                $file->move($destinationPath, $addSpaceImage);
            } else {
                return response()->json(['error' => 'The uploaded file is invalid or empty.'], 500);
                // return response()->json(['error' => lang('.', 'alerts')]);
            }
        }

        // Use updateOrCreate
        $addspace = AddSpace::updateOrCreate(
            ['id' => $req->id],
            [
                'title' => $req->addSpaceTitle,
                'status' => ($req->status == 'on' || $status == true) ? 1 : 0,
                'link' => $req->addSpaceLink,
                'image' => $addSpaceImage ?? ($req->id ? DB::table('add_spaces')->where('id', $req->id)->value('image') : null),
            ]
        );

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = $req->id ? 'Updated an addspace' . ' ' . $req->addSpaceTitle : 'created an addspace' . $req->addSpaceTitle;
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        $message = $addspace->wasRecentlyCreated ? 'Addspace created successfully.' : 'Addspace updated successfully.';

        // Return success response
        return response()->json(['success' => $message, 'data' => $addspace]);
    }

    public function deleteAddSpace($id)
    {
        $this->authorize('Addspace Delete');
        $AddSpace = AddSpace::find($id);
        $AddSpace->delete();

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Deleted an addspace' . ' ' . $AddSpace->title;
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['success' => 'The AddSpace has been successfully deleted.']);
    }

    public function deleteall(Request $request)
    {
        $this->authorize('Addspace Delete');
        $id_array = $request->input('id');

        $Addspace = AddSpace::whereIn('id', $id_array)->get();

        foreach ($Addspace as $add) {
            $add->delete();
        }

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Deleted multiple addspace' . ' ';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['success' => 'AddSpace has been successfully deleted.']);
    }

    public function changeStatus(Request $request, $id)
    {
        try {
            $this->authorize('AddSpace Edit');
            $supID = AddSpace::find($id);
            $supID->status = $request->status;
            $supID->save();

            $geolocation = GeoIP::getLocation(request()->getClientIp());
            $agent = new Agent();
            $activity = new EmployeeActivity();
            $activity->user_id = Auth::user()->id;
            $activity->activity_type = 'Changed Addspace Status' . ' ' . $supID->title;
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();

            return response()->json(['code' => 200, 'success' => 'Updated successfully'], 200);
        } catch (\Throwable $th) {
            return response()->json(['exception' => $th->getMessage()]);
        }
    }
}
