<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Department;
use App\Models\UserActivity;
use Illuminate\Http\Request;

class DepartmentController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware(function ($request, $next) {
            if (!auth()->user()->hasPermission('manage_departments')) {
                abort(403, 'Unauthorized access to department management');
            }
            return $next($request);
        });
    }

    /**
     * Display departments listing
     */
    public function index()
    {
        $departments = Department::withCount('users')->latest()->get();
        return view('admin.departments.index', compact('departments'));
    }

    /**
     * Store a new department
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:departments,name',
            'description' => 'nullable|string|max:500',
            'code' => 'nullable|string|max:50|unique:departments,code',
            'manager_name' => 'nullable|string|max:255',
            'manager_email' => 'nullable|email|max:255'
        ]);

        $validated['is_active'] = $request->has('is_active');

        $department = Department::create($validated);

        // Log activity
        UserActivity::create([
            'user_id' => auth()->id(),
            'action' => 'created_department',
            'description' => "Created department: {$department->name}",
            'properties' => ['department_id' => $department->id],
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent()
        ]);

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Department created successfully!',
                'department' => $department
            ]);
        }

        return redirect()->route('admin.departments')->with('success', 'Department created successfully!');
    }

    /**
     * Update a department
     */
    public function update(Request $request, Department $department)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:departments,name,' . $department->id,
            'description' => 'nullable|string|max:500',
            'code' => 'nullable|string|max:50|unique:departments,code,' . $department->id,
            'manager_name' => 'nullable|string|max:255',
            'manager_email' => 'nullable|email|max:255'
        ]);

        $validated['is_active'] = $request->has('is_active');

        $department->update($validated);

        // Log activity
        UserActivity::create([
            'user_id' => auth()->id(),
            'action' => 'updated_department',
            'description' => "Updated department: {$department->name}",
            'properties' => ['department_id' => $department->id],
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent()
        ]);

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Department updated successfully!'
            ]);
        }

        return redirect()->route('admin.departments')->with('success', 'Department updated successfully!');
    }

    /**
     * Delete a department
     */
    public function destroy(Request $request, Department $department)
    {
        // Check if department has users
        if ($department->users()->exists()) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Cannot delete department with assigned users'
                ], 400);
            }
            return redirect()->route('admin.departments')->with('error', 'Cannot delete department with assigned users');
        }

        $departmentName = $department->name;
        $department->delete();

        // Log activity
        UserActivity::create([
            'user_id' => auth()->id(),
            'action' => 'deleted_department',
            'description' => "Deleted department: {$departmentName}",
            'properties' => [],
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent()
        ]);

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Department deleted successfully!'
            ]);
        }

        return redirect()->route('admin.departments')->with('success', 'Department deleted successfully!');
    }
}