<?php
namespace App\Controllers;

use App\Models\GroupModel;
use App\Models\StaffModel;

class GroupController extends BaseController
{
    protected $groupModel;
    protected $staffModel;

    public function __construct()
    {
        $this->groupModel = new GroupModel();
        $this->staffModel = new StaffModel();
    }

    // API สำหรับดึงข้อมูลกลุ่มทั้งหมด
    public function getGroups()
    {
        try {
            $groups = $this->groupModel->orderBy('id', 'ASC')->findAll();

            return $this->response->setJSON([
                'status' => 'success',
                'data' => $groups
            ]);
        } catch (\Exception $e) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'เกิดข้อผิดพลาด: ' . $e->getMessage()
            ]);
        }
    }

    // API สำหรับดึงข้อมูลพนักงานตามกลุ่ม
    public function getStaffByGroup($groupId)
    {
        try {
            $staff = $this->staffModel
                ->select('id, name, current_jobs')
                ->where('group_id', $groupId)
                ->orderBy('id', 'ASC')
                ->findAll();

            if (empty($staff)) {
                return $this->response->setJSON([
                    'status' => 'error',
                    'message' => 'ไม่มีพนักงานในกลุ่มนี้'
                ]);
            }

            return $this->response->setJSON([
                'status' => 'success',
                'data' => $staff
            ]);
        } catch (\Exception $e) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'เกิดข้อผิดพลาด: ' . $e->getMessage()
            ]);
        }
    }
}
