<?php

namespace App\Http\Controllers\Api;

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

class DepartmentController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();

        $query = Department::with(['company', 'manager', 'employees']);

        if (!$user->isSuperAdmin()) {
            $query->forCompany($user->company_id);
        }

        $departments = $query->when($request->company_id, function ($q) use ($request) {
            $q->where('company_id', $request->company_id);
        })
        ->when($request->search, function ($q) use ($request) {
            $q->where('name', 'like', "%{$request->search}%")
              ->orWhere('code', 'like', "%{$request->search}%");
        })
        ->when($request->status, function ($q) use ($request) {
            $q->where('status', $request->status);
        })
        ->orderBy($request->get('sort_by', 'name'), $request->get('sort_order', 'asc'))
        ->paginate($request->get('per_page', 15));

        return response()->json($departments);
    }

    public function store(Request $request)
    {
        $user = $request->user();

        $request->validate([
            'company_id' => 'required|exists:companies,id',
            'name' => 'required|string|max:255',
            'code' => 'nullable|string|max:50',
            'description' => 'nullable|string',
            'manager_id' => 'nullable|exists:users,id',
        ]);

        if (!$user->canAccessCompany($request->company_id)) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $department = Department::create($request->all());

        activity()
            ->performedOn($department)
            ->log('Department created');

        return response()->json([
            'department' => $department->load(['company', 'manager']),
            'message' => 'Department created successfully',
        ], 201);
    }

    public function show($id, Request $request)
    {
        $user = $request->user();

        $department = Department::with(['company', 'manager', 'employees'])
            ->findOrFail($id);

        if (!$user->canAccessCompany($department->company_id)) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        return response()->json($department);
    }

    public function update(Request $request, $id)
    {
        $user = $request->user();

        $department = Department::findOrFail($id);

        if (!$user->canAccessCompany($department->company_id)) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $request->validate([
            'name' => 'sometimes|string|max:255',
            'code' => 'sometimes|nullable|string|max:50',
            'description' => 'sometimes|nullable|string',
            'manager_id' => 'sometimes|nullable|exists:users,id',
            'status' => 'sometimes|in:active,inactive',
        ]);

        $department->update($request->all());

        activity()
            ->performedOn($department)
            ->log('Department updated');

        return response()->json([
            'department' => $department->fresh(['company', 'manager']),
            'message' => 'Department updated successfully',
        ]);
    }

    public function destroy($id, Request $request)
    {
        $user = $request->user();

        $department = Department::findOrFail($id);

        if (!$user->canAccessCompany($department->company_id)) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $department->delete();

        activity()
            ->performedOn($department)
            ->log('Department deleted');

        return response()->json(['message' => 'Department deleted successfully']);
    }
}
