<?php

namespace App\Database\Migrations;

use App\Models\OrdenTrabajo\OrdenTrabajoTarea;
use CodeIgniter\Database\Migration;
use CodeIgniter\Database\RawSql;
use CodeIgniter\I18n\Time;

class AddTableOrdenTrabajoTareaProgressDates extends Migration
{

    protected array $COLUMNS = [
        "id" => [
            "type" => "INT",
            "unsigned" => true,
            "auto_increment" => true,
        ],
        "ot_tarea_id" => [
            "type" => "INT",
            "unsigned" => true,
        ],
        "action_at" => [
            "type" => "DATETIME",
            "comment" => "Datetime task init"
        ],
        "action_user_id" => [
            "type" => "INT",
            "unsigned" => true,
            "constraint" => 11,
            "null" => true,
        ],
        "estado" => [
            "type" => "ENUM",
            "constraint" => ["P", "I", "S", "D", "F", "E"],
            "default" => "P",
            "comment" => "(P)ENDING,(I)NIT,(S)TOPPED,(D)ELAY,(F)INISHED,(E)RROR"
        ]
    ];
    public function up()
    {
        $this->forge->addField($this->COLUMNS);
        $currenttime = new RawSql('CURRENT_TIMESTAMP');
        $this->forge->addField([
            'created_at' => [
                'type' => 'TIMESTAMP',
                'default' => $currenttime,
            ],
            'updated_at' => [
                'type' => 'TIMESTAMP',
                'null' => true,
            ],
            'deleted_at' => [
                'type' => 'TIMESTAMP',
                'null' => true,

            ],
        ]);
        $this->forge->addPrimaryKey('id');
        $this->forge->addForeignKey('ot_tarea_id', 'orden_trabajo_tareas', 'id');
        $this->forge->createTable("orden_trabajo_tarea_progress_dates");

        $m = model(OrdenTrabajoTarea::class);
        $tareas = $m->findAll();
        try {
            foreach ($tareas as $key => $tarea) {
                $this->db->table('orden_trabajo_tarea_progress_dates')->insert([
                    "ot_tarea_id" => $tarea->id,
                    "action_at" => $tarea->created_at->format('Y-m-d H:i:s'),
                    "action_user_id" => $tarea?->orden_trabajo()?->user_created_id ?? null,
                ]);
            }
        } catch (\Throwable $th) {
            echo $th->getMessage();
        }
    }

    public function down()
    {
        $this->forge->dropTable("orden_trabajo_tarea_progress_dates");
    }
}
