<?php
class StaffController extends Controller
{
    public function index(Request $request): void
    {
        $this->view('staff/index', [
            'title' => lang('admin.staff'),
            'breadcrumbs' => [['label' => lang('admin.administration'), 'url' => '/admin/staff'], ['label' => lang('admin.staff')]],
        ]);
    }

    public function datatable(Request $request): void
    {
        $db = $this->db();
        $draw = (int)$request->post('draw', 1);
        $start = (int)$request->post('start', 0);
        $length = (int)$request->post('length', 25);
        $search = trim($request->post('search')['value'] ?? '');

        $where = "s.is_deleted = 0";
        $params = [];
        if ($search !== '') {
            $where .= " AND (s.staff_number LIKE ? OR s.first_name_en LIKE ? OR s.last_name_en LIKE ? OR s.phone LIKE ?)";
            $w = "%{$search}%";
            $params = [$w, $w, $w, $w];
        }

        $statusFilter = $request->post('status_filter');
        if ($statusFilter) { $where .= " AND s.status = ?"; $params[] = $statusFilter; }
        $deptFilter = $request->post('dept_filter');
        if ($deptFilter) { $where .= " AND s.department_id = ?"; $params[] = (int)$deptFilter; }

        $total = (int)$db->fetchColumn("SELECT COUNT(*) FROM staff s WHERE s.is_deleted = 0");
        $filtered = (int)$db->fetchColumn("SELECT COUNT(*) FROM staff s WHERE {$where}", $params);
        $rows = $db->fetchAll(
            "SELECT s.*, d.name_en as dept_name, sp.title_en as position_name
             FROM staff s LEFT JOIN departments d ON s.department_id = d.id
             LEFT JOIN staff_positions sp ON s.position_id = sp.id
             WHERE {$where} ORDER BY s.id DESC LIMIT {$length} OFFSET {$start}", $params
        );

        $data = [];
        foreach ($rows as $r) {
            $data[] = [
                'id' => $r['id'],
                'staff_number' => e($r['staff_number']),
                'name' => e($r['first_name_en'] . ' ' . $r['last_name_en']),
                'department' => e($r['dept_name'] ?? '-'),
                'position' => e($r['position_name'] ?? '-'),
                'phone' => e($r['phone'] ?? '-'),
                'status' => status_badge($r['status']),
                'hire_date' => format_date($r['hire_date']),
                'actions' => '<div class="btn-group btn-group-sm"><a href="/admin/staff/' . $r['id'] . '" class="btn btn-outline-info"><i class="fas fa-eye"></i></a><a href="/admin/staff/' . $r['id'] . '/edit" class="btn btn-outline-primary"><i class="fas fa-edit"></i></a></div>',
            ];
        }
        $this->json(['draw' => $draw, 'recordsTotal' => $total, 'recordsFiltered' => $filtered, 'data' => $data]);
    }

    public function create(Request $request): void
    {
        $db = $this->db();
        $this->view('staff/form', [
            'title' => 'Create Staff',
            'breadcrumbs' => [['label' => lang('admin.administration'), 'url' => '/admin/staff'], ['label' => lang('admin.staff'), 'url' => '/admin/staff'], ['label' => 'Create']],
            'staff' => null,
            'departments' => $db->fetchAll("SELECT id, name_en FROM departments WHERE is_active = 1 ORDER BY name_en"),
            'positions' => $db->fetchAll("SELECT id, title_en FROM staff_positions WHERE is_active = 1 ORDER BY title_en"),
            'users' => $db->fetchAll("SELECT id, full_name_en, username FROM auth_users WHERE is_active = 1 AND is_deleted = 0 ORDER BY full_name_en"),
        ]);
    }

    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(), [
            'staff_number'  => 'required|string|max:30',
            'first_name_en' => 'required|string|max:100',
            'last_name_en'  => 'required|string|max:100',
            'hire_date'     => 'required|date',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }

        $id = $this->db()->insert('staff', [
            'staff_number'  => $request->post('staff_number'),
            'first_name_en' => $request->post('first_name_en'),
            'last_name_en'  => $request->post('last_name_en'),
            'first_name_ar' => $request->post('first_name_ar'),
            'last_name_ar'  => $request->post('last_name_ar'),
            'department_id' => $request->post('department_id') ?: null,
            'position_id'   => $request->post('position_id') ?: null,
            'user_id'       => $request->post('user_id') ?: null,
            'phone'         => $request->post('phone'),
            'email'         => $request->post('email'),
            'gender'        => $request->post('gender') ?: null,
            'hire_date'     => $request->post('hire_date'),
            'status'        => 'active',
            'created_by'    => Auth::id(),
        ]);
        $this->audit('create', 'staff', $id, 'Created staff member');
        $this->json(['success' => true, 'message' => 'Staff member created', 'redirect' => '/admin/staff']);
    }

    public function show(Request $request): void
    {
        $id = (int)$request->routeParam('id');
        $db = $this->db();
        $staff = $db->fetchOne(
            "SELECT s.*, d.name_en as dept_name, sp.title_en as position_name, u.username as linked_username
             FROM staff s LEFT JOIN departments d ON s.department_id = d.id
             LEFT JOIN staff_positions sp ON s.position_id = sp.id LEFT JOIN auth_users u ON s.user_id = u.id
             WHERE s.id = ? AND s.is_deleted = 0", [$id]
        );
        if (!$staff) { $this->abort(404); return; }

        $tasks = $db->fetchAll("SELECT * FROM staff_tasks WHERE assigned_to = ? ORDER BY created_at DESC LIMIT 20", [$id]);
        $shifts = $db->fetchAll("SELECT * FROM staff_shifts WHERE staff_id = ? ORDER BY shift_date DESC LIMIT 20", [$id]);
        $reviews = $db->fetchAll("SELECT spr.*, u.full_name_en as reviewer_name FROM staff_performance_reviews spr LEFT JOIN auth_users u ON spr.reviewer_id = u.id WHERE spr.staff_id = ? ORDER BY spr.review_period_end DESC", [$id]);

        $this->view('staff/view', [
            'title' => $staff['first_name_en'] . ' ' . $staff['last_name_en'],
            'breadcrumbs' => [['label' => lang('admin.administration'), 'url' => '/admin/staff'], ['label' => lang('admin.staff'), 'url' => '/admin/staff'], ['label' => 'View']],
            'staff' => $staff, 'tasks' => $tasks, 'shifts' => $shifts, 'reviews' => $reviews,
        ]);
    }

    public function edit(Request $request): void
    {
        $id = (int)$request->routeParam('id');
        $db = $this->db();
        $staff = $db->fetchOne("SELECT * FROM staff WHERE id = ? AND is_deleted = 0", [$id]);
        if (!$staff) { $this->abort(404); return; }

        $this->view('staff/form', [
            'title' => 'Edit Staff',
            'breadcrumbs' => [['label' => lang('admin.administration'), 'url' => '/admin/staff'], ['label' => lang('admin.staff'), 'url' => '/admin/staff'], ['label' => 'Edit']],
            'staff' => $staff,
            'departments' => $db->fetchAll("SELECT id, name_en FROM departments WHERE is_active = 1 ORDER BY name_en"),
            'positions' => $db->fetchAll("SELECT id, title_en FROM staff_positions WHERE is_active = 1 ORDER BY title_en"),
            'users' => $db->fetchAll("SELECT id, full_name_en, username FROM auth_users WHERE is_active = 1 AND is_deleted = 0 ORDER BY full_name_en"),
        ]);
    }

    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('staff', [
            'first_name_en' => $request->post('first_name_en'),
            'last_name_en'  => $request->post('last_name_en'),
            'first_name_ar' => $request->post('first_name_ar'),
            'last_name_ar'  => $request->post('last_name_ar'),
            'department_id' => $request->post('department_id') ?: null,
            'position_id'   => $request->post('position_id') ?: null,
            'user_id'       => $request->post('user_id') ?: null,
            'phone'         => $request->post('phone'),
            'email'         => $request->post('email'),
            'status'        => $request->post('status', 'active'),
            'updated_at'    => date('Y-m-d H:i:s'),
        ], 'id = ?', [$id]);
        $this->audit('update', 'staff', $id, 'Updated staff member');
        $this->json(['success' => true, 'message' => 'Staff updated', 'redirect' => '/admin/staff']);
    }
}