<?php

namespace App\Controllers;

use App\Models\EmployeeModel;
use App\Models\ScannedDataModel;
use App\Models\TaskModel;

class ScanController extends BaseController
{
    public function index()
    {
        $employeeModel = new EmployeeModel();
        $employees = $employeeModel->findAll();

        return view('scan/index', ['employees' => $employees]);
    }
    
     public function getScannedData()
    {
        $scannedDataModel = new ScannedDataModel();
        $data = $scannedDataModel
            ->select('scanned_data.barcode, employees.name as employee_name, scanned_data.created_at')
            ->join('employees', 'employees.id = scanned_data.employee_id', 'left')
            ->orderBy('scanned_data.created_at', 'DESC')
            ->findAll();

        return $this->response->setJSON($data);
    }

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

        $scannedDataModel = new ScannedDataModel();
        $existing = $scannedDataModel->where('barcode', $barcode)->first();

        if ($existing) {
            return json_encode(['status' => 'duplicate', 'message' => 'Barcode already scanned!']);
        }

        $scannedDataModel->save(['barcode' => $barcode, 'employee_id' => $employeeId]);

        return json_encode(['status' => 'success', 'message' => 'Barcode scanned successfully!']);
    }

    public function assignTasks()
    {
        $employeeModel = new EmployeeModel();
        $taskModel = new TaskModel();

        $employees = $employeeModel->findAll();
        $totalTasks = (new ScannedDataModel())->countAllResults();

        if (count($employees) > 0) {
            $tasksPerEmployee = floor($totalTasks / count($employees));
            
            foreach ($employees as $employee) {
                $taskModel->save([
                    'employee_id' => $employee['id'],
                    'total_tasks' => $tasksPerEmployee
                ]);
            }
        }

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