<?php
class DepartmentController extends Controller
{
    public function index(Request $request): void
    {
        $db = $this->db();
        $departments = $db->fetchAll("SELECT d.*, p.name_en as parent_name, u.full_name_en as manager_name FROM departments d LEFT JOIN departments p ON d.parent_id = p.id LEFT JOIN auth_users u ON d.manager_user_id = u.id ORDER BY d.sort_order, d.name_en");
        $users = $db->fetchAll("SELECT id, full_name_en FROM auth_users WHERE is_active = 1 AND is_deleted = 0 ORDER BY full_name_en");

        $this->view('departments/index', [
            'title' => lang('admin.departments'),
            'breadcrumbs' => [
                ['label' => lang('admin.administration'), 'url' => '/admin/departments'],
                ['label' => lang('admin.departments')]
            ],
            'departments' => $departments,
            'users' => $users,
        ]);
    }

    public function datatable(Request $request): void
    {
        $db = $this->db();
        $draw = (int)$request->post('draw', 1);
        $rows = $db->fetchAll(
            "SELECT d.*, p.name_en as parent_name, u.full_name_en as manager_name,
                    (SELECT COUNT(*) FROM staff s WHERE s.department_id = d.id AND s.is_deleted = 0) as staff_count
             FROM departments d
             LEFT JOIN departments p ON d.parent_id = p.id
             LEFT JOIN auth_users u ON d.manager_user_id = u.id
             ORDER BY d.sort_order, d.name_en"
        );
        $data = [];
        foreach ($rows as $r) {
            $actions = '<div class="btn-group btn-group-sm">';
            $actions .= '<button class="btn btn-outline-primary btn-edit-dept" data-id="' . $r['id'] . '" data-code="' . e($r['department_code']) . '" data-name-en="' . e($r['name_en']) . '" data-name-ar="' . e($r['name_ar']) . '" data-parent="' . ($r['parent_id'] ?? '') . '" data-manager="' . ($r['manager_user_id'] ?? '') . '" data-active="' . $r['is_active'] . '"><i class="fas fa-edit"></i></button>';
            $actions .= '<button class="btn btn-outline-danger btn-delete-dept" data-id="' . $r['id'] . '"><i class="fas fa-trash"></i></button>';
            $actions .= '</div>';
            $data[] = [
                'code' => e($r['department_code']),
                'name' => e($r['name_en']),
                'name_ar' => e($r['name_ar']),
                'parent' => e($r['parent_name'] ?? '-'),
                'manager' => e($r['manager_name'] ?? '-'),
                'staff_count' => $r['staff_count'],
                'active' => $r['is_active'] ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>',
                'actions' => $actions,
            ];
        }
        $this->json(['draw' => $draw, 'recordsTotal' => count($rows), 'recordsFiltered' => count($rows), 'data' => $data]);
    }

    public function store(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid CSRF'], 403); return; }
        $validator = new Validator($request->all(), [
            'department_code' => 'required|string|max:20',
            'name_en' => 'required|string|max:200',
            'name_ar' => 'required|string|max:200',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }

        $id = $this->db()->insert('departments', [
            'department_code' => $request->post('department_code'),
            'name_en' => $request->post('name_en'),
            'name_ar' => $request->post('name_ar'),
            'parent_id' => $request->post('parent_id') ?: null,
            'manager_user_id' => $request->post('manager_user_id') ?: null,
            'is_active' => $request->post('is_active', 1) ? 1 : 0,
        ]);
        $this->audit('create', 'departments', $id, 'Created department: ' . $request->post('name_en'));
        $this->json(['success' => true, 'message' => 'Department created']);
    }

    public function update(Request $request): void
    {
        $id = (int)$request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid CSRF'], 403); return; }
        $this->db()->update('departments', [
            'name_en' => $request->post('name_en'),
            'name_ar' => $request->post('name_ar'),
            'parent_id' => $request->post('parent_id') ?: null,
            'manager_user_id' => $request->post('manager_user_id') ?: null,
            'is_active' => $request->post('is_active', 1) ? 1 : 0,
        ], 'id = ?', [$id]);
        $this->audit('update', 'departments', $id, 'Updated department');
        $this->json(['success' => true, 'message' => 'Department updated']);
    }

    public function destroy(Request $request): void
    {
        $id = (int)$request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid CSRF'], 403); return; }
        $childCount = $this->db()->fetchColumn("SELECT COUNT(*) FROM departments WHERE parent_id = ?", [$id]);
        if ($childCount > 0) { $this->json(['success' => false, 'message' => 'Cannot delete department with children'], 400); return; }
        $this->db()->delete('departments', 'id = ?', [$id]);
        $this->audit('delete', 'departments', $id, 'Deleted department');
        $this->json(['success' => true, 'message' => 'Department deleted']);
    }
}