<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\Department;
use App\Models\User;
use Spatie\Permission\Models\Role;
use Auth;
use Illuminate\Support\Facades\Schema;
use Jenssegers\Agent\Agent;
use Torann\GeoIP\Facades\GeoIP;
use App\Models\EmployeeActivity;

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

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

        $departments = Department::latest();
        $searchTerm = $request['filter'] ?? null;
        $perPage    = $request['per_page'] ?? 15;
        $page       = $request['page'] ?? 1;

        if ($searchTerm) {
            $departments->where(function ($query) use ($searchTerm) {
                $columns = Schema::getColumnListing('departments');
                foreach ($columns as $column) {
                    $query->orWhere($column, 'LIKE', "%{$searchTerm}%");
                }
            });
        }
        $items = $departments->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 create(Request $request)
    {
        $validate = Department::find($request->id);
        if (!$validate) {

            $request->validate([

                'departmentname' => 'required|max:255|unique:departments',

            ]);
        }
        if ($validate) {
            if ($request->departmentname == $validate->departmentname) {

                $request->validate([

                    'departmentname' => 'required|max:255',

                ]);
            } else {

                $request->validate([

                    'departmentname' => 'required|max:255|unique:departments',

                ]);
            }
        }

        $department = Department::updateOrCreate(['id' => $request->id], ['departmentname' => $request->departmentname, 'status' => $request->status]);
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = $request->id ? 'updated department ' : 'created department';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        $message = $request->id ? lang('Department updated successfully.', 'alerts') : lang('Department created successfully.', 'alerts');
        return response()->json(['code' => 200, 'success' =>  $message, 'data' => $department], 200);
    }

    public function edit($id)
    {
        $this->authorize('Department Edit');
        $department = Department::find($id);
        return response()->json($department);
    }

    public function delete($id)
    {
        $this->authorize('Department Delete');
        $department = Department::find($id);
        $department->delete();

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

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

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

        $departments = Department::whereIn('id', $id_array)->get();

        foreach ($departments as $department) {
            $department->delete();
        }
        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Deleted multiple departments';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();
        return response()->json(['success' => 'The Department has been successfully deleted.']);
    }

    public function status(Request $request, $id)
    {
        $this->authorize('Department Edit');

        $calID = Department::find($id);
        $calID->status = $request->status;
        $calID->save();

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

        return response()->json(['code' => 200, 'success' => 'Updated Successfully'], 200);
    }
}
