<?php
namespace App\Controllers;

use App\Models\AEmployeeModel;
use App\Models\ATaskModel;

class TaskController extends BaseController
{
    protected $employeeModel;
    protected $taskModel;

    public function __construct()
    {
        $this->employeeModel = new AEmployeeModel();
        $this->taskModel = new ATaskModel();
    }

    public function index()
{
    $employees = $this->employeeModel->findAll();
    $tasks = $this->taskModel->findAll();

    // คำนวณจำนวนงานรวมทั้งหมดจาก quantity
    $totalQuantity = array_sum(array_column($tasks, 'quantity'));
    $employeeCount = count($employees);

    // คำนวณจำนวนงานเฉลี่ยต่อพนักงาน
    $averageQuantity = $employeeCount > 0 ? ceil($totalQuantity / $employeeCount) : 0;

    // จัดกลุ่ม quantity ของแต่ละพนักงาน
    $employeeQuantities = array_fill_keys(array_column($employees, 'id'), 0);

    foreach ($tasks as $task) {
        if ($task['employee_id'] && isset($employeeQuantities[$task['employee_id']])) {
            $employeeQuantities[$task['employee_id']] += $task['quantity'];
        }
    }

    // คำนวณจำนวนงานที่ต้องเพิ่มหรือลด
    $adjustments = [];
    foreach ($employees as $employee) {
        $currentQuantity = $employeeQuantities[$employee['id']];
        $adjustments[] = [
            'employee_id' => $employee['id'],
            'name' => $employee['name'],
            'current_quantity' => $currentQuantity,
            'adjustment' => $averageQuantity - $currentQuantity
        ];
    }

        return view('task_view', [
        'adjustments' => $adjustments,
        'averageQuantity' => $averageQuantity,
        'totalQuantity' => $totalQuantity,
        'employees' => $employees,
            'tasks' => $tasks
        ]);
    }

    public function addTask()
{
    $description = $this->request->getPost('description');
    $employeeId = $this->request->getPost('employee_id');

    $this->taskModel->save([
        'description' => $description,
        'employee_id' => $employeeId
    ]);

    return redirect()->to('/tasks');
}

public function updateTask($id)
{
    $description = $this->request->getPost('description');
    $employeeId = $this->request->getPost('employee_id');

    $this->taskModel->update($id, [
        'description' => $description,
        'employee_id' => $employeeId,
    ]);

    return redirect()->to('/tasks');
}


    public function editTask($id)
    {
        $task = $this->taskModel->find($id);
        $employees = $this->employeeModel->findAll();

        return view('edit_task_view', [
            'task' => $task,
            'employees' => $employees
        ]);
    }

    public function deleteTask($id)
    {
        $this->taskModel->delete($id);
        return redirect()->to('/tasks');
    }
    

}