<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class SynchronizeOwnerAdminWorkflow extends Migration
{
    public function up()
    {
        if (! $this->db->fieldExists('production_status', 'orders')) {
            $this->forge->addColumn('orders', [
                'production_status' => ['type' => 'VARCHAR', 'constraint' => 20, 'null' => true, 'default' => 'waiting', 'after' => 'order_status'],
            ]);
        }

        if ($this->db->fieldExists('production_status', 'orders')) {
            $this->db->query("UPDATE orders SET production_status = CASE
                WHEN production_status IN ('antrian', 'waiting') THEN 'waiting'
                WHEN production_status IN ('produksi', 'process') THEN 'process'
                WHEN production_status IN ('selesai', 'completed') THEN 'completed'
                WHEN production_status IN ('cancelled', 'cancel') THEN 'cancelled'
                ELSE 'waiting'
            END WHERE production_status IS NOT NULL");
        }

        if (! $this->db->tableExists('payrolls')) {
            $this->forge->addField([
                'id_payroll' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'auto_increment' => true],
                'id_user' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true],
                'periode' => ['type' => 'DATE'],
                'gaji_pokok' => ['type' => 'DECIMAL', 'constraint' => '18,2', 'default' => 0],
                'bonus' => ['type' => 'DECIMAL', 'constraint' => '18,2', 'default' => 0],
                'potongan' => ['type' => 'DECIMAL', 'constraint' => '18,2', 'default' => 0],
                'total_gaji' => ['type' => 'DECIMAL', 'constraint' => '18,2', 'default' => 0],
                'status' => ['type' => 'VARCHAR', 'constraint' => 20, 'default' => 'Pending'],
                'paid_at' => ['type' => 'DATETIME', 'null' => true],
                'created_at' => ['type' => 'DATETIME', 'null' => true],
                'updated_at' => ['type' => 'DATETIME', 'null' => true],
            ]);
            $this->forge->addKey('id_payroll', true);
            $this->forge->createTable('payrolls');
        }
    }

    public function down()
    {
        if ($this->db->tableExists('payrolls')) $this->forge->dropTable('payrolls');
        if ($this->db->fieldExists('production_status', 'orders')) $this->forge->dropColumn('orders', 'production_status');
    }
}
