<?php

namespace App\Models;

use DateTime;

class Stage {
    public ?int $id;
    public int $project_id;
    public ?int $parent_id; // id del Stage padre
    public string $name;
    public string $description;
    public ?DateTime $start_date;
    public ?DateTime $end_date;
    public string $status;
    public bool $deletable = true;
    public string $status_traffic_light;

    // Relaciones con otros modelos
    public ?Project $project = null;

    /** @var Stage[] */
    public array $children = [];

    /** @var Document[] */
    public array $documents = [];

    public function __construct(array $data = [])
    {
        $this->id = isset($data['id']) ? (int) $data['id'] : 0;
        $this->project_id = isset($data['project_id']) ? (int) $data['project_id'] : 0;
        $this->parent_id = isset($data['parent_id']) ? (int) $data['parent_id'] : null;
        $this->name = $data['name'] ?? '';
        $this->description = $data['description'] ?? '';
        $this->start_date = !empty($data['start_date']) ? new DateTime($data['start_date']) : null;
        $this->end_date = !empty($data['end_date']) ? new DateTime($data['end_date']) : null;
        $this->status = $data['status'] ?? 'abierto';
        $this->project = $data['project'] ?? null;
        $this->status_traffic_light = $data['status_traffic_light'] ?? 'gris';

        if(!empty($data['documents'])){
            $this->documents = array_map(fn($doc) => new Document($doc), $data['documents']);
        }
       
        if (!empty($data['children']) && is_array($data['children'])) {
            $this->children = array_map(fn($child) => new Stage($child), $data['children']);
        }   
    }

    /**
     * Construye un árbol de etapas desde una lista plana
     *
     * @param Stage[] $stages
     * @return Stage[]
    */
    public static function buildTree(array $stages): array {
        $tree = [];
        $map = [];

        foreach ($stages as $stage) {
            $map[$stage->id] = $stage;
            $stage->children = [];
        }

        foreach ($stages as $stage) {
            if ($stage->parent_id === null) {
                $tree[] = $stage;
            } else {
                if (isset($map[$stage->parent_id])) {
                    $map[$stage->parent_id]->children[] = $stage;
                }
            }
        }

        return $tree;
    }
}
