<?php
namespace App\Controllers;

use App\Models\BarcodeModel;
use App\Models\EmployeeModel;
use App\Models\TaskDistributionModel;

class BarcodeController extends BaseController
{
    protected $barcodeModel;
    protected $employeeModel;
    protected $taskDistributionModel;

    public function __construct()
    {
        $this->barcodeModel = new BarcodeModel();
        $this->employeeModel = new EmployeeModel();
        $this->taskDistributionModel = new TaskDistributionModel();
    }

    public function scanBarcode()
    {
        $barcode = $this->request->getPost('barcode');

        if ($this->barcodeModel->isDuplicate($barcode)) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Barcode already scanned']);
        }

        $this->barcodeModel->insert(['barcode' => $barcode]);
        return $this->response->setJSON(['status' => 'success', 'message' => 'Barcode scanned successfully']);
    }

    public function distributeTasks()
    {
        $employees = $this->employeeModel->getAllEmployees();
        $barcodes = $this->barcodeModel->findAll();

        if (empty($employees)) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'No employees found']);
        }

        $employeeCount = count($employees);
        $barcodeCount = count($barcodes);

        $index = 0;
        foreach ($barcodes as $barcode) {
            $employeeId = $employees[$index % $employeeCount]['id'];
            $this->taskDistributionModel->assignTask($employeeId, $barcode['id']);
            $index++;
        }

        return $this->response->setJSON(['status' => 'success', 'message' => 'Tasks distributed successfully']);
    }

    public function getTaskSummary()
    {
        $employees = $this->employeeModel->getAllEmployees();
        $summary = [];

        foreach ($employees as $employee) {
            $tasks = $this->taskDistributionModel->getTasksByEmployee($employee['id']);
            $summary[] = [
                'employee' => $employee['name'],
                'tasks' => count($tasks)
            ];
        }

        return view('task_summary', ['summary' => $summary]);
    }
}
