<?php

namespace WMS\Repositories;

class WarehouseTaskRepository extends BaseRepository
{
    protected string $table = 'warehouse_tasks';

    /**
     * Obtiene tareas pendientes/asignadas por tipo.
     */
    public function getOpenTasks(int $warehouseId, ?string $taskType = null, ?int $assignedTo = null): array
    {
        $sql = "SELECT wt.*, i.item_code, i.item_name,
                       fb.code AS from_bin_code, tb.code AS to_bin_code,
                       bt.batch_number, bt.expiry_date,
                       u.full_name AS assigned_to_name
                FROM warehouse_tasks wt
                JOIN items i ON wt.item_id = i.id
                LEFT JOIN bins fb ON wt.from_bin_id = fb.id
                LEFT JOIN bins tb ON wt.to_bin_id = tb.id
                LEFT JOIN batches bt ON wt.batch_id = bt.id
                LEFT JOIN users u ON wt.assigned_to = u.id
                WHERE wt.warehouse_id = ?
                  AND wt.status IN ('PENDING','ASSIGNED','IN_PROGRESS')";
        $params = [$warehouseId];

        if ($taskType) {
            $sql .= " AND wt.task_type = ?";
            $params[] = $taskType;
        }
        if ($assignedTo) {
            $sql .= " AND wt.assigned_to = ?";
            $params[] = $assignedTo;
        }

        $sql .= " ORDER BY wt.priority ASC, wt.created_at ASC";
        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll();
    }

    /**
     * Asigna una tarea a un operador.
     */
    public function assignTask(int $taskId, int $userId): bool
    {
        return $this->update($taskId, [
            'assigned_to' => $userId,
            'status'      => 'ASSIGNED',
        ]);
    }

    /**
     * Marca tarea como en progreso.
     */
    public function startTask(int $taskId): bool
    {
        return $this->update($taskId, [
            'status'     => 'IN_PROGRESS',
            'started_at' => date('Y-m-d H:i:s'),
        ]);
    }

    /**
     * Completa una tarea.
     */
    public function completeTask(int $taskId, float $confirmedQty): bool
    {
        return $this->update($taskId, [
            'status'        => 'COMPLETED',
            'confirmed_qty' => $confirmedQty,
            'completed_at'  => date('Y-m-d H:i:s'),
        ]);
    }
}
